#!/bin/bash
# Konfiguracja czasu systemowego: strefa, NTP lub czas ręczny
# Użycie: set-time-config MODE TIMEZONE NTP_SERVER [DATE TIME]
#   MODE        : ntp | manual
#   TIMEZONE    : strefa IANA np. Europe/Warsaw, lub "" żeby nie zmieniać
#   NTP_SERVER  : serwer NTP, lub "default" żeby użyć systemowego
#   DATE        : YYYY-MM-DD (tylko manual, opcjonalne)
#   TIME        : HH:MM lub HH:MM:SS (tylko manual, opcjonalne)
set -euo pipefail

MODE="${1:?Wymagany tryb: ntp|manual}"
TIMEZONE="${2:-}"
NTP_SERVER="${3:-default}"
DATE="${4:-}"
TIME="${5:-}"

# 1. Ustaw strefę czasową
if [ -n "$TIMEZONE" ] && [ "$TIMEZONE" != "-" ]; then
    /usr/bin/timedatectl set-timezone "$TIMEZONE"
fi

# 2. Synchronizacja
if [ "$MODE" = "ntp" ]; then
    # Skonfiguruj serwer NTP jeśli nie domyślny
    if [ -n "$NTP_SERVER" ] && [ "$NTP_SERVER" != "default" ] && [ "$NTP_SERVER" != "-" ]; then
        mkdir -p /etc/systemd/timesyncd.conf.d
        printf '[Time]\nNTP=%s\nFallbackNTP=pool.ntp.org\n' "$NTP_SERVER" \
            > /etc/systemd/timesyncd.conf.d/99-nivato.conf
        /usr/bin/systemctl daemon-reload 2>/dev/null || true
        /usr/bin/systemctl restart systemd-timesyncd 2>/dev/null || true
    fi
    /usr/bin/timedatectl set-ntp true
else
    # Tryb ręczny — wyłącz NTP, ustaw czas
    /usr/bin/timedatectl set-ntp false
    if [ -n "$DATE" ] && [ "$DATE" != "-" ] && [ -n "$TIME" ] && [ "$TIME" != "-" ]; then
        [[ "$TIME" =~ ^[0-9]{2}:[0-9]{2}$ ]] && TIME="${TIME}:00"
        /usr/bin/timedatectl set-time "${DATE} ${TIME}"
    fi
fi
