#!/bin/bash

#load configuration
. "$(dirname "$0")/config.sh"

# Usage: $0 INSTANCE  server IP_ADDRESS port NUM period NUM
instance=$1
if [ -z "$instance" ]; then
    echo "Instance is required" >&2
    exit 1
fi
shift

# reset the variables in case they already contain something
unset server port period

# now iterate over the rest of the parameters
# if the parameter will be a known key, we will store the next parameter as its value
while [ -n "$1" ]; do
    echo "> $1"
    case "$1" in
    server)
        shift
        # save the server name, but strip any double quotes, which are escaped unfortunatelly
        server="$(echo $1 | tr -d '\"')"
        ;;
    port)
        shift
        port=$1
        ;;
    period)
        shift
        period=$1
        ;;
    *)
        echo "Unknown parameter" >&2
        ;;
    esac
    shift
done

. `dirname $0`/fs-lib    #include library

unlock_fs

################### modify NTP daemon configuration file /etc/ntp.conf
# THIS IS DISABLED, ONLY THE TIMESYNCD WILL BE CONFIGURED
#if systemctl is-active ntp.service > /dev/null; then
#  CFG=/etc/ntp.conf
#  if [ -h $CFG ]; then
#      CFG=`readlink $CFG`
#  fi 
#  cfgdir=`dirname $CFG`
#  if tmp=$(mktemp "${cfgdir}/ntp.XXXXXX"); then
#    #cat $CFG > $tmp
#    chmod --reference=$CFG $tmp
#    chown --reference=$CFG $tmp
#    (
#      echo "# NTP server entry received from ConfigTool server"
#      echo "server $server"
#      sed -r -e '/^ *(server|peer).*$/d;/^# NTP server entry received.*$/d' $CFG
#    ) >>$tmp
#    mv -f $tmp $CFG
#  fi
#  systemctl try-restart ntp
#fi

CFG=/etc/systemd/timesyncd.conf
if [ -w "$CFG" ]; then
    # Replace NTP= in timesyncd.conf 

    function update_confile()
    {
        # check whether the key=value pair is already in the config
        if grep -q "^${1}=.*${2}" "$CFG"; then
            # yes it is, nothing to update
            echo "The key \"$1\" with value $2 is already present"
            return 0
        fi
        
        # the key=value pair is not present or active, we should change the config

        # check whether the key is there, even commented
        if grep -q "^#*${1}=" "$CFG"; then
            # the key is there, we will mangle its value and leave the comment, if there is any
            sed -i "s/^#*${1}=[^#]*/${1}=${2} /" "$CFG"
            echo "The key $1 is already present, but with different value or commented out => changing"
        else
            # the key is not present at all, add it after start of the [Time] section
            sed -i "/\\[Time\\]/a ${1}=${2}" "$CFG"
            echo "The key $1 is not present at all => adding"
        fi

        return 1
    }

    function force_comment()
    {
        # if the parameter is uncommented, comment it
        echo "Forcing comment on $1"
        sed -i "s/\\(^$1:.*\\)/#\\1/" "$CFG"
    }

    # should be the NTP server set or removed?
    # the 'port' condition is for backward compatbility with runtimes which don't double quote the server at all and when the server is left empty in the MervisIDE
    if [ "$server" == "" ] || [ "$server" == "port" ]; then
        echo "Disabling the NTP"
        # disable the NTP syncing
        timedatectl set-ntp off

        # comment out the configuration
        #force_comment "NTP"
    else
        echo "Enabling the NTP, server: $server"
        # set the server
        update_confile "NTP" "$server"
        # set the syncing
        timedatectl set-ntp on
    fi

    systemctl try-restart systemd-timesyncd.service
fi

lock_fs
sync
