#!/bin/bash

# Get the address as an argument
address=$1

# Fetch the server date
sync_date=$(wget -t 5 --max-redirect=0 --connect-timeout=5 --dns-timeout=5 --read-timeout=5 --tries=1 -qSO- --max-redirect=0 ${address} 2>&1 | grep Date: | cut -d' ' -f5-8)

# Format the server date
serverDate=$(date -d "$sync_date" +'%Y-%m-%d %H')

# Get the current date in UTC
currentDate=$(date '+%Y-%m-%d %H' -u)

# Check if sync_date is empty
if [ -z "$sync_date" ]; then
    echo "QoE Server Unreachable!"
    exit 1
fi

# Output dates
echo $serverDate
echo $currentDate

# Compare the server date and current date
if [ "$serverDate" == "$currentDate" ]; then
    echo "OK. Date was synced."
    exit 0
else
    echo "Warning! Date was not synced. I am syncing the date ..."
    date -u -s "$sync_date"
    echo "Date is Now Synced."
    exit 0
fi
