#!/usr/bin/env bash

set -euo pipefail

echo "======================================"
echo " Linux Dual-Boot Time Fix Script"
echo "======================================"
echo

# Ensure running as root
if [[ $EUID -ne 0 ]]; then
    echo "Please run as root:"
    echo "sudo bash fix-time.sh"
    exit 1
fi

# Detect current timezone instead of hardcoding
CURRENT_TZ=$(timedatectl show -p Timezone --value || echo "UTC")

echo "[1/5] Ensuring timezone is set to $CURRENT_TZ..."
timedatectl set-timezone "$CURRENT_TZ"

echo "[2/5] Configuring RTC to use UTC..."
timedatectl set-local-rtc 0

echo "[3/5] Enabling NTP synchronization..."
timedatectl set-ntp true

echo "[4/5] Restarting time sync daemon (if applicable)..."
systemctl restart systemd-timesyncd 2>/dev/null || true

echo "[5/5] Final time configuration:"
echo
timedatectl

echo
echo "======================================"
echo " SUCCESS"
echo "======================================"
echo
echo "Your system is now configured with:"
echo "  - Timezone: $CURRENT_TZ"
echo "  - RTC stored in UTC"
echo "  - NTP synchronization enabled"
echo
echo "This is the recommended setup for Linux."
echo

cat <<'EOF'
--------------------------------------------------
WINDOWS CONFIGURATION REQUIRED
--------------------------------------------------
If you dual-boot with Windows, configure Windows
to also use UTC to prevent clock drift.

Run this in Windows Administrator CMD:

reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /t REG_DWORD /d 1 /f

Then reboot Windows once.
EOF