#!/usr/bin/env bash

set -euo pipefail

echo "======================================"
echo " Ubuntu Dual-Boot Time Fix Script"
echo " (Local Time Method)"
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 Local Time (to match Windows default)..."
# This is the crucial change: '1' sets it to Local Time
timedatectl set-local-rtc 1 --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"
echo "======================================"
echo
echo "Your system is now configured with:"
echo "  - Timezone: $CURRENT_TZ"
echo "  - RTC stored in Local Time"
echo "  - NTP synchronization enabled"
echo
echo "Note: You can safely ignore any 'RTC in local TZ' warnings"
echo "from timedatectl, as they are expected with this configuration."
echo

cat <<'EOF'
--------------------------------------------------
WINDOWS CONFIGURATION (IF NEEDED)
--------------------------------------------------
Linux is now expecting the hardware clock to be in Local Time,
which is the default behavior for Windows.

If you previously added a registry key to force Windows into UTC,
you must remove it. Run this in Windows Administrator CMD:

reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation" /v RealTimeIsUniversal /f

If you never changed Windows time settings, you are completely done!
EOF