#!/bin/bash 

LOGFILE="/var/log/hostname.log"

# Function to log messages with timestamps
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOGFILE"
}

# Function to read the hostname from the DHCP lease file
get_hostname() {
    sudo cat /var/lib/dhcp/* | grep -a "option host-name" | tail -1 | \
    awk -F '"' '{print $2}'
}

# Function to update /etc/hosts with the new hostname
update_hosts() {
    local hostname="$1"
    # Replace the second line with the new hostname
    sudo sed -i "2s/.*/127.0.1.1   ${hostname}/" /etc/hosts
    log "Updated /etc/hosts with hostname: $hostname"
}

# Read the hostname from DHCP
hostname=$(get_hostname)

if [ -n "$hostname" ]; then
    # Set the hostname using hostnamectl
    sudo hostnamectl set-hostname "$hostname"
    log "Set hostname to: $hostname"
    update_hosts "$hostname"
else
    log "No hostname found."
fi

# Log completion
log "Hostname update script completed."

# Version 1.0:
# Created 2024 by Tim Eertmoed, Christian Hampp @ WiS IT-Solutions GmbH, Germany to work on Raspbian as custom PXE init script.
