#!/usr/bin/env bash

set -euo pipefail

echo "======================================"
echo " Ubuntu Dual-Boot Time Fix Script"
echo " (UTC Method - Highly Recommended)"
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 (to prevent dual-boot conflicts)..."
# '0' sets the hardware clock to UTC
timedatectl set-local-rtc 0 --adjust-system-clock

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 - LINUX CONFIGURED"
echo "======================================"
echo
echo "Your system is now configured with:"
echo "  - Timezone: $CURRENT_TZ"
echo "  - RTC stored in UTC"
echo "  - NTP synchronization enabled"
echo

cat <<'EOF'
--------------------------------------------------
WINDOWS CONFIGURATION (REQUIRED)
--------------------------------------------------
Linux is now correctly expecting the hardware clock to be in UTC.
To make Windows do the same and stop the time from resetting,
you MUST run the following command in Windows.

1. Boot into Windows.
2. Open Command Prompt as Administrator.
3. Run this exact command:

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

4. Restart Windows and sync the time in Settings one last time.
EOF