#!/bin/bash

# ==============================================================================
# Script Name: set_network.sh
# Description: Automatically update hostname and static IP address on Ubuntu.
#              This script modifies /etc/hostname, /etc/hosts, and Netplan config.
# Args:
#   1. New Hostname (1-63 chars, alphanumeric and hyphen)
#   2. IP Host Segment (1-254)
# Returns:
#   0: Success
#   1: Invalid arguments
#   2: File operation error
#   3: Network configuration error
# ==============================================================================

# ------------------------------------------------------------------------------
# Constants and Variables
# ------------------------------------------------------------------------------
NEW_HOSTNAME="$1"
IP_SEGMENT="$2"
CURRENT_IP=""
NEW_IP=""
ETC_DIR="${ETC_DIR:-/etc}"
NETPLAN_DIR="${ETC_DIR}/netplan"
REBOOT_CMD="${REBOOT_CMD:-reboot}"

# ------------------------------------------------------------------------------
# Functions
# ------------------------------------------------------------------------------

# Function: log_info
# Description: Print info message with timestamp
log_info() {
    echo "[INFO] $(date '+%Y-%m-%d %H:%M:%S') - $1"
}

# Function: error_exit
# Description: Print error message and exit with specific code
# Args:
#   1. Error message
#   2. Exit code
error_exit() {
    echo "[ERROR] $(date '+%Y-%m-%d %H:%M:%S') - $1" >&2
    exit "$2"
}

# Function: check_root
# Description: Ensure script is run as root
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        error_exit "This script must be run as root." 1
    fi
}

# Function: validate_args
# Description: Validate input arguments
validate_args() {
    # Check number of arguments
    if [ $# -ne 2 ]; then
        error_exit "Invalid number of arguments. Usage: $0 <new_hostname> <ip_segment>" 1
    fi

    # Validate Hostname
    # Length 1-63, Alphanumeric + hyphen, no leading/trailing hyphen
    if [[ ! "$NEW_HOSTNAME" =~ ^[a-zA-Z0-9-]{1,63}$ ]]; then
        error_exit "Invalid hostname format. Only alphanumeric and hyphens allowed, length 1-63." 1
    fi
    if [[ "$NEW_HOSTNAME" =~ ^- ]] || [[ "$NEW_HOSTNAME" =~ -$ ]]; then
        error_exit "Hostname cannot start or end with a hyphen." 1
    fi

    # Validate IP Segment (1-254)
    if ! [[ "$IP_SEGMENT" =~ ^[0-9]+$ ]]; then
        error_exit "IP segment must be a number." 1
    fi
    if [ "$IP_SEGMENT" -lt 1 ] || [ "$IP_SEGMENT" -gt 254 ]; then
        error_exit "IP segment must be between 1 and 254." 1
    fi

    log_info "Arguments validated successfully."
}

# Function: calculate_new_ip
# Description: Get current IP and construct new IP
calculate_new_ip() {
    # Get current primary IP address
    # Using 'ip route get' to find the source IP used for external connectivity
    # Output format: 1.1.1.1 via GW dev IF src IP ...
    # We use sed to extract the IP after 'src'
    CURRENT_IP=$(ip route get 1.1.1.1 2>/dev/null | sed -n 's/.*src \([0-9.]*\).*/\1/p')
    
    if [ -z "$CURRENT_IP" ]; then
        # Fallback to hostname -I if ip route fails
        CURRENT_IP=$(hostname -I | awk '{print $1}')
    fi

    if [ -z "$CURRENT_IP" ]; then
        error_exit "Failed to determine current IP address." 3
    fi

    log_info "Current IP address: $CURRENT_IP"

    # Verify current IP format
    if [[ ! "$CURRENT_IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        error_exit "Current IP format invalid: $CURRENT_IP" 3
    fi

    # Extract first three segments
    local prefix
    prefix=$(echo "$CURRENT_IP" | cut -d. -f1-3)
    
    # Construct new IP
    NEW_IP="${prefix}.${IP_SEGMENT}"
    log_info "New IP address will be: $NEW_IP"

    # Verify new IP format
    if [[ ! "$NEW_IP" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        error_exit "Generated new IP address is invalid: $NEW_IP" 3
    fi
}


# Function: apply_changes
# Description: Modify system configuration files
apply_changes() {
    # 1. Update /etc/hostname
    log_info "Updating ${ETC_DIR}/hostname..."

    echo "$NEW_HOSTNAME" > "${ETC_DIR}/hostname" || error_exit "Failed to write to ${ETC_DIR}/hostname" 2

    # 2. Update /etc/hosts
    log_info "Updating ${ETC_DIR}/hosts..."

    # Replace the hostname associated with 127.0.1.1
    # Using sed with word boundaries to ensure we match the entry correctly
    if grep -q "127.0.1.1" "${ETC_DIR}/hosts"; then
        sed -i "s/^127.0.1.1.*/127.0.1.1\t$NEW_HOSTNAME/" "${ETC_DIR}/hosts" || error_exit "Failed to update ${ETC_DIR}/hosts" 2
    else
        # If 127.0.1.1 doesn't exist, maybe append it? Standard Ubuntu has it.
        # Just logging a warning or appending if missing.
        echo -e "127.0.1.1\t$NEW_HOSTNAME" >> "${ETC_DIR}/hosts" || error_exit "Failed to append to ${ETC_DIR}/hosts" 2
    fi

    # 3. Update Netplan
    log_info "Updating Netplan configuration..."
    
    # Find the netplan file containing the current IP
    local netplan_file=""
    # Use grep to find which file contains the current IP
    # We look for the IP followed by a slash (CIDR notation) or end of line/quote
    # to avoid partial matches (e.g. matching 192.168.1.10 in 192.168.1.100)
    netplan_file=$(grep -l -r "$CURRENT_IP" "$NETPLAN_DIR"/*.yaml 2>/dev/null | head -n 1)

    if [ -z "$netplan_file" ]; then
        error_exit "Current IP $CURRENT_IP not found in any Netplan configuration file in $NETPLAN_DIR. Is the system using DHCP or a different static IP?" 3
    fi

    log_info "Found current IP in Netplan file: $netplan_file"


    # Replace old IP with new IP using sed
    # We assume the format is like '192.168.1.X/24' or just '192.168.1.X'
    # We only replace the IP part, preserving the CIDR suffix if present
    # Pattern: match current IP, replace with new IP
    sed -i "s/$CURRENT_IP/$NEW_IP/g" "$netplan_file" || error_exit "Failed to update Netplan file" 2
    
    log_info "Netplan configuration updated."
}

# Function: finalize
# Description: Apply changes and reboot
finalize() {
    log_info "Hostname and IP address updated successfully. System will reboot now."
    
    # In a real scenario, we might want to 'netplan apply' first to verify,
    # but the requirement says "Reboot system".
    # Applying netplan might disconnect the session immediately if run via SSH.
    
    # Sync filesystem to ensure writes are flushed
    sync
    
    # Reboot
    $REBOOT_CMD
}

# ------------------------------------------------------------------------------
# Main Execution Flow
# ------------------------------------------------------------------------------

# 1. Check Root
check_root

# 2. Validate Args
validate_args "$@"

# 3. Calculate IPs
calculate_new_ip

# 4. Apply Changes
apply_changes

# 5. Finalize (Reboot)
finalize

exit 0
