#!/bin/sh

# Временная метка
timestamp=$(date +"%Y%m%d_%H%M%S")
# Лог-файл с временной меткой
log_file="/tmp/ec_cmdline_$timestamp.log"

# Имя хоста
hostname_current=$(hostname)
hostname_cmdline=$(tr ' ' '\n' < /proc/cmdline | grep '^netcfg/get_hostname=' | cut -d'=' -f2)
# Часовой пояс
time_zone=$(tr ' ' '\n' < /proc/cmdline | grep '^timezone=' | cut -d'=' -f2)

ssh_config="/etc/ssh/sshd_config"
search_string="Port 22"
new_string="Port 3389"


# Функция для вывода в консоль и запись в лог-файл
log() {
    echo "$1"
    echo "$1" >> "$log_file"
}

log "==================================================================="
log "===== Preseed Partman EC cmdline script (network). Version 1 ======"
log "==================================================================="


if grep -q "$search_string" "$ssh_config"; then
    if ! grep -q "$new_string" "$ssh_config"; then
        sed -i "/$search_string/a $new_string" "$ssh_config"
        echo "Line '$new_string' has been added after '$search_string'."
    else
        echo "Line '$new_string' already exists in $ssh_config."
    fi
else
    echo "Line '$search_string' was not found in config file $ssh_config."
fi

echo "Restarting SSH service..."
sshd_pid=$(ps | grep '/usr/sbin/sshd' | grep -v grep | tr -s ' ' | cut -d ' ' -f 2)
if [ -n "$sshd_pid" ]; then
    echo "Terminating the sshd process with PID $sshd_pid..."
    kill "$sshd_pid"
fi
echo "Starting the sshd process sshd..."
/usr/sbin/sshd

# Установка временной зоны
if [ -z "$time_zone" ]; then
    log "Warning: timezone is empty. No timezone found in /proc/cmdline. Setting default timezone to Europe/Moscow."
    time_zone="Europe/Moscow"
else
    log "Timezone from cmdline: $time_zone"
fi
log "Setting timezone to $time_zone."
echo "$time_zone" > /etc/timezone
ln -sf "/usr/share/zoneinfo/$time_zone" /etc/localtime
if dpkg-reconfigure -f noninteractive tzdata; then
    log "Timezone successfully set to $time_zone."
else
    log "Error: Failed to set timezone to $time_zone."
fi

if [ -z "$hostname_cmdline" ]; then
    log "Error: hostname_cmdline is empty. No netcfg/get_hostname found in /proc/cmdline. Skipping hostname change."
else
    log "Current hostname: $hostname_current"
    log "Cmdline hostname: $hostname_cmdline"

    if [ "$hostname_current" != "$hostname_cmdline" ]; then
        log "Hostnames do not match. Setting hostname to $hostname_cmdline."
        echo "$hostname_cmdline" > /etc/hostname
        hostname "$hostname_cmdline"
        new_hostname=$(hostname)
        if [ "$new_hostname" = "$hostname_cmdline" ]; then
            log "Hostname successfully updated to $new_hostname."
        else
            log "Error: Failed to update hostname. Current hostname is $new_hostname."
        fi
    else
        log "Hostnames match. No changes needed."
    fi
fi
