#!/bin/bash

# Script to set the hostname for k3OS by writing directly to the hostname file.
# This script requires root privileges and prompts the user for the new hostname.

HOSTNAME_FILE="/var/lib/rancher/k3os/hostname"

# --- Function to check for root/sudo privileges ---
check_privileges() {
    if [[ $EUID -ne 0 ]]; then
        echo "Error: This script must be run with root/sudo privileges."
        echo "Please run: sudo $0"
        exit 1
    fi
}

# --- Function to get user input ---
get_hostname_input() {
    # Loop until a non-empty hostname is provided
    while true; do
        read -r -p "Enter the desired new hostname: " NEW_HOSTNAME
        if [ -n "$NEW_HOSTNAME" ]; then
            break
        else
            echo "Error: Hostname cannot be empty. Please enter a valid name."
        fi
    done
}

# --- Function to write the hostname to the file ---
write_hostname() {
    local NEW_HOSTNAME="$1"
    
    echo "Attempting to write new hostname: **$NEW_HOSTNAME** to **$HOSTNAME_FILE**"
    
    # Write the new hostname, ensuring no extra whitespace or newlines
    echo -n "$NEW_HOSTNAME" > "$HOSTNAME_FILE"
    
    # Check if the write operation was successful
    if [ $? -eq 0 ]; then
        echo "Success: The new hostname has been written to $HOSTNAME_FILE."
        echo ""
        echo "--- Verification ---"
        echo "File content: $(cat "$HOSTNAME_FILE")"
        echo ""
        echo "Action Required: A **system reboot is necessary** for the new hostname to take effect."
        echo "You can reboot now using the 'reboot' command."
    else
        echo "Error: Failed to write to $HOSTNAME_FILE. Check file permissions or disk status."
        exit 1
    fi
}

# --- Main execution ---
check_privileges
get_hostname_input
write_hostname "$NEW_HOSTNAME"