#!/bin/bash
# Check if the script is run with root privileges
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi

# Get the current hostname
CURRENT_HOSTNAME=$(hostname)

# New hostname provided as an argument
NEW_HOSTNAME=$1

# Check if new hostname is provided
if [ -z "$NEW_HOSTNAME" ]; then
    echo "Usage: $0 new-hostname"
    exit 1
fi

echo "Current hostname: $CURRENT_HOSTNAME"
echo "New hostname: $NEW_HOSTNAME"

# Temporarily change the hostname
hostname $NEW_HOSTNAME
if [ $? -eq 0 ]; then
    echo "Temporary hostname changed to $NEW_HOSTNAME"
else
    echo "Failed to change temporary hostname"
    exit 1
fi

# Permanently change the hostname in /etc/hostname
echo $NEW_HOSTNAME > /etc/hostname
if [ $? -eq 0 ]; then
    echo "Hostname written to /etc/hostname"
else
    echo "Failed to write to /etc/hostname"
    exit 1
fi

# Update /etc/hosts
sed -i "s/$CURRENT_HOSTNAME/$NEW_HOSTNAME/g" /etc/hosts
if [ $? -eq 0 ]; then
    echo "/etc/hosts updated with new hostname"
else
    echo "Failed to update /etc/hosts"
    exit 1
fi

# Use hostnamectl to set the hostname (for systemd systems)
hostnamectl set-hostname $NEW_HOSTNAME
if [ $? -eq 0 ]; then
    echo "hostnamectl set the hostname to $NEW_HOSTNAME"
else
    echo "Failed to set hostname using hostnamectl"
    exit 1
fi

# Ensure hostname changes are reflected in the shell prompt for all users
echo "export PS1='[\u@\h \W]\$ '" >> /etc/profile.d/hostname.sh

# Apply changes to the current session
source /etc/profile

echo "Hostname successfully changed from $CURRENT_HOSTNAME to $NEW_HOSTNAME"
