#!/bin/bash
# License: GPL
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to synchronize time in Clonezilla live.
# This file contains code generated by Grok, created by xAI.

#
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/usr/share/drbl}"
. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions
. /etc/drbl/drbl-ocs.conf
. $DRBL_SCRIPT_PATH/sbin/ocs-functions

# Load the config in ocs-live.conf. This is specially for Clonezilla live. It will overwrite some settings of /etc/drbl/drbl-ocs.conf, such as $DIA...
[ -e "/etc/ocs/ocs-live.conf" ] && . /etc/ocs/ocs-live.conf

# Settings
force_run="no"
batch_mode="no"

USAGE() {
  echo "$ocs - To sync time"
  echo "Usage:"
  echo "To run $ocs:"
  echo "$ocs [OPTION]"
  echo "Options:"
  echo "-b, --batch-mode      Run in batch mode"
  echo "-f, --force           Run anyway even it was ran before"
  echo "-i, --sync-via-net    Time sync via internet"
  echo "-m, --set-via-kernel  Set the system time zone without internet. This will only work in interactive (non-batch) mode"
  echo
} # end of USAGE
# Function to determine timezone based on IP-based geolocation
get_timezone() {
  # Use ip-api.com to get location data
  location_data=$(LC_ALL=C curl -s http://ip-api.com/json)
  if [ $? -eq 0 ]; then
    timezone=$(echo "$location_data" | grep -oP '"timezone":"[^"]+"' | cut -d'"' -f4)
    echo "$timezone"
  else
    # Fallback to system default or UTC if API fails
    echo "UTC"
  fi
} # end of get_timezone
#
sync_via_internet() {
  echo "Checking internet connection..."
  if check_internet; then
    echo "Internet connection detected."
    # Get timezone
    timezone=$(get_timezone)
    echo "Detected timezone: $timezone"
  
    # Configure timezone
    tz_set_cmd="timedatectl set-timezone \"$timezone\""
    echo "Setting timezone to $timezone..."
    echo "Running: $tz_set_cmd"
    eval $tz_set_cmd
    if [ $? -eq 0 ]; then
      echo "Timezone set successfully."
    else
      echo "Failed to set timezone. Continuing with time sync..."
    fi
  
    # Sync time using ntpdate-debian
    echo "Synchronizing time. Running: ntpdate-debian..."
    ntpdate-debian
    if [ $? -eq 0 ]; then
      touch /run/live/$ocs
      echo "Time synchronized successfully."
      return 0
    else
      [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
      echo "Failed to synchronize time via internet."
      [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
      return 1
    fi
    else
      echo "Internet connection was not detected."
      return 1
  fi
} # End of sync_via_internet
#
sync_via_kernel() {
  if [ "$batch_mode" = "yes" ]; then
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Sync time without internet must be in non-batch mode because we have to ask you the time zome."
    echo "No way to run in batch mode."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    return 2
  fi
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  echo "$msg_no_net_so_set_timezone_manually"
  echo "$msg_current_time_on_this_system"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  date +%F" "%X" "%Z
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  if [ "$batch_mode" = "no" ]; then
    echo -n "$msg_press_enter_to_continue..."
    read
  fi
  echo "$msg_next_choose_timezone"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  echo -n "$msg_are_u_sure_u_want_to_continue (Y/n) " | tee --append ${OCS_LOGFILE}
  read continue_confirm_ans
  case "$continue_confirm_ans" in
    n|N|[nN][oO])
       echo "$msg_program_stop." | tee --append ${OCS_LOGFILE}
       # Copy error log to image dir.
       copy_error_log
       return 1
       ;;
    *) 
       echo "$msg_ok_let_do_it" | tee --append ${OCS_LOGFILE}
       dpkg-reconfigure tzdata
       if [ $? -eq 0 ]; then
         # Check boot parameters for hardware clock setting first
         if grep -qw "utc=no" /proc/cmdline || grep -qw "live-config.utc=no" /proc/cmdline; then
           echo "$msg_rtc_is_local_time_by_boot_param"
           timedatectl set-local-rtc 1 --adjust-system-clock
         elif grep -qw "utc=yes" /proc/cmdline || grep -qw "live-config.utc=yes" /proc/cmdline; then
           echo "$msg_rtc_is_utc_by_boot_param"
           timedatectl set-local-rtc 0 --adjust-system-clock
         else
           # Prompt the user interactively
           if [ "$batch_mode" = "no" ]; then
             echo "$msg_ask_bios_clock_utc_or_local"
             echo "$msg_bios_clock_utc_option"
             echo "$msg_bios_clock_local_option"
             echo -n "$msg_please_select_one_or_two"
             read rtc_choice
             case "$rtc_choice" in
               2)
                 echo "$msg_setting_bios_clock_to_local"
                 timedatectl set-local-rtc 1 --adjust-system-clock
                 ;;
               *)
                 echo "$msg_setting_bios_clock_to_utc"
                 timedatectl set-local-rtc 0 --adjust-system-clock
                 ;;
             esac
           else
             # In batch mode, default to UTC
             timedatectl set-local-rtc 0 --adjust-system-clock
           fi
         fi
         touch /run/live/$ocs
       fi
       return 0
       ;;
  esac
} # end of sync_via_kernel

####################
### Main program ###
####################
ocs_file="$0"
ocs=`basename $ocs_file`
#
while [ $# -gt 0 ]; do
 case "$1" in
   -b|--batch) batch_mode="yes"; shift;;
   -f|--force)  force_run="yes"; shift;;
   -i|--sync-via-net)  force_run="yes"; mode="net"; shift;;
   -m|--set-via-kernel) force_run="yes"; mode="kernel"; shift;;
   -*)     echo "${0}: ${1}: invalid option" >&2
           USAGE >& 2
           exit 2 ;;
   *)      break ;;
 esac
done
check_if_root
ask_and_load_lang_set

# Fallback localizations if not defined in the loaded language file
[ -z "$msg_rtc_is_local_time_by_boot_param" ] && msg_rtc_is_local_time_by_boot_param="According to boot parameters, hardware clock (RTC) is in local time."
[ -z "$msg_rtc_is_utc_by_boot_param" ] && msg_rtc_is_utc_by_boot_param="According to boot parameters, hardware clock (RTC) is in UTC."
[ -z "$msg_ask_bios_clock_utc_or_local" ] && msg_ask_bios_clock_utc_or_local="Is your BIOS/hardware clock set to UTC or Local Time?"
[ -z "$msg_bios_clock_utc_option" ] && msg_bios_clock_utc_option="1) UTC (Default - Recommended for Linux-only systems)"
[ -z "$msg_bios_clock_local_option" ] && msg_bios_clock_local_option="2) Local Time (Standard for Windows dual-boot systems)"
[ -z "$msg_please_select_one_or_two" ] && msg_please_select_one_or_two="Please select [1/2]: "
[ -z "$msg_setting_bios_clock_to_local" ] && msg_setting_bios_clock_to_local="Configuring system to interpret the BIOS clock as Local Time..."
[ -z "$msg_setting_bios_clock_to_utc" ] && msg_setting_bios_clock_to_utc="Configuring system to interpret the BIOS clock as UTC..."

if [ "$force_run" = "no" ]; then
  if [ -e "/run/live/$ocs" ]; then
    echo "$ocs already ran previously."
    exit 3
  fi
fi

rc=1
case $mode in 
  net)  sync_via_internet; rc=$? ;;
  kernel) sync_via_kernel; rc=$? ;;
  *)    sync_via_internet
        rc=$?
        if [ "$rc" -ne 0 ]; then
          sync_via_kernel
          rc=$?
        fi
        ;;
esac

if [ "$rc" -eq 0 ]; then
  echo "System time and timezone configured."
  echo "Current time:"
  [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
  date +%F" "%X" "%Z
  [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
  if [ "$batch_mode" = "no" ]; then
    echo -n "$msg_press_enter_to_continue..."
    read
  fi
fi
