#!/bin/bash

# Function to show the current timezone, with two alternative methods
show_timezone() {
    # Check if the /etc/timezone file exists
    if [ -f /etc/timezone ]; then
        timezone=$(cat /etc/timezone)
    elif [ -f /etc/localtime ]; then
        timezone=$(readlink /etc/localtime)
        timezone=${timezone/\/usr\/share\/zoneinfo\//}
    else
        timezone="Cannot determine timezone."
    fi
    echo "$timezone"
}

# Function to set the timezone
set_timezone() {
    new_timezone="$1"
    echo "$new_timezone" | sudo tee /etc/timezone >/dev/null
    sudo ln -sf /usr/share/zoneinfo/"$new_timezone" /etc/localtime
    if [ -f /etc/environment ]; then sudo sed -i "/TZ/c\TZ=$new_timezone" /etc/environment; fi
    if [ -d /var/run/s6/container_environment ]; then echo "$new_timezone" | sudo tee /var/run/s6/container_environment/TZ > /dev/null; fi
    echo "$new_timezone"
}

# Main script
case "$1" in
    "set-ntp")
        case "$2" in
            "false")
                sudo systemctl stop systemd-timesyncd
                sudo systemctl disable systemd-timesyncd
                echo "NTP disabled"
                ;;
            "true")
                sudo systemctl start systemd-timesyncd
                sudo systemctl enable systemd-timesyncd
                echo "NTP enabled"
                ;;
            *)
                echo "Invalid argument for set-ntp. Use 'false' or 'true'."
                ;;
        esac
        ;;
    "show")
        show_timezone
        ;;
    "set-timezone")
        set_timezone "$2"
        ;;
    *)
        # Get values
        local_time="$(date)"
        utc_time="$(date -u)"
        time_zone="$(show_timezone)"
        # Check if NTP is used
        if sudo systemctl status systemd-timesyncd | grep -q " active"; then
            ntp_status="yes"
            ntp_service="active"
        else
            ntp_status="no"
            ntp_service="inactive"
        fi
        # Print the information
        echo "Local time: $local_time"
        echo "Universal time: $utc_time"
        echo "Time zone: $time_zone"
        echo "Network time on: $ntp_status"
        echo "NTP service: $ntp_service"
        ;;
esac
