#!/bin/bash
# License: GPL 
# Author: Steven Shiau <steven _at_ clonezilla org>
# Description: Program to check internet connection then sync time for the machine
# 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

# Function to determine timezone based on IP-based geolocation
get_timezone() {
  # Use ip-api.com to get location data
  location_data=$(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
}

####################
### Main program ###
####################
check_if_root
ask_and_load_lang_set

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
    echo "Time synchronized successfully."
    echo "Current time:"
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    date +%F" "%X" "%Z
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    echo -n "$msg_press_enter_to_continue..."
    read
  else
    [ "$BOOTUP" = "color" ] && $SETCOLOR_WARNING
    echo "Failed to synchronize time."
    [ "$BOOTUP" = "color" ] && $SETCOLOR_NORMAL
    exit 1
  fi
else
  echo "No internet connection. Cannot sync time."
  echo -n "$msg_press_enter_to_continue..."
  read
  exit 1
fi
