#!/bin/bash
#
# This is an sdm plugin for: clockfake
#
# The plugin is called three times: for Phase 0, Phase 1, and post-install.
#

function loadparams() {
    source $SDMPT/etc/sdm/sdm-readparams
}

# $1 is the phase: "0", "1", or "post-install"
# $2 is the argument list: arg1=val1|arg2=val2|arg3=val3| ...
#
# Main code for the Plugin
#
phase=$1
pfx="$(basename $0)"     #For messages
args="$2"
vargs="|burntime|interval|"
rqdargs=""
loadparams

if [ "$phase" == "0" ]
then
    #
    # In Phase 0 all references to directories in the image must be preceded by $SDMPT
    #
    logtoboth "* Plugin $pfx: Start Phase 0"
    logtoboth "* Plugin $pfx: Complete Phase 0"

elif [ "$phase" == "1" ]
then
    #
    # Phase 1 (in nspawn)
    #
    logtoboth "* Plugin $pfx: Start Phase 1"
    plugin_getargs $pfx "$args" "$vargs" "$rqdargs" || exit
    plugin_printkeys

    [ "$interval" == "" ] && interval=60
    logtoboth "* Plugin $pfx: Install clockfake"
    rm -f /usr/local/bin/clockfake
    cat >> /usr/local/bin/clockfake <<EOF
#!$(type -p python3)

from datetime import datetime, timezone
import time

fakefile = "/etc/fake-hwclock.data"
# sleeptime is $interval minutes
sleeptime = $interval*60
while True:
    with open(fakefile, 'w') as f:
        now = datetime.now(timezone.utc)
        f.write("{}\n".format(datetime.strftime(now, "%Y-%m-%d %H:%M:%S")))
    time.sleep(sleeptime)

EOF
    chmod 755 /usr/local/bin/clockfake
    rm -f /etc/systemd/system/clockfake.service
    cat >> /etc/systemd/system/clockfake.service <<EOF
[Unit]
Description=Fake HW clock
After=network-online.target

[Service]
Type=simple
ExecStart=/usr/local/bin/clockfake
Restart=on-failure
RestartSec=60s

[Install]
WantedBy=multi-user.target

EOF
    logtoboth "* Plugin $pfx: Complete Phase 1"
else
    #
    # Plugin Post-install edits
    #
    logtoboth "* Plugin $pfx: Start Phase post-install"
    plugin_getargs $pfx "$args" "$vargs" "$rqdargs"
    plugin_printkeys

    systemctl enable clockfake > /dev/null 2>&1
    if [[ "$SDMNSPAWN" =~ "Live" ]]
    then
	systemctl daemon-reload
	systemctl restart clockfake > /dev/null 2&>1
    fi
    logtoboth "* Plugin $pfx: Disable RasPiOS fake-hwclock hourly update"
    [ -f /etc/cron.hourly/fake-hwclock ] && mv /etc/cron.hourly/fake-hwclock /etc/cron.hourly/.fake-hwclock
    #
    # Run the program once here to set the fake hw clock
    #
    if [ "$burntime" == "y" ]
    then
	logtoboth "> Plugin $pfx: Update fake hw clock"
	python3 <<EOF
from datetime import datetime, timezone
with open("/etc/fake-hwclock.data", 'w') as f:
    now = datetime.now(timezone.utc)
    f.write("{}\n".format(datetime.strftime(now, "%Y-%m-%d %H:%M:%S")))
EOF
    fi
    logtoboth "* Plugin $pfx: Complete Phase post-install"
fi
