#!/bin/sh

set -e

function current_modem {
    mmcli_list_cmd='mmcli -L -J'
    modem_list=$(eval $mmcli_list_cmd)
    while [[ $modem_list == '{"modem-list":[]}' ]]; do
        sleep 1
        modem_list=$(eval $mmcli_list_cmd)
    done
    echo $modem_list | jq -r 'objects["modem-list"][0]'
}

mmcli_time_cmd='mmcli -m $modem --time -J'
qmicli_cmd='qmicli --device-open-mbim -p -d /dev/cdc-wdm0 --dms-get-time'
until modem=$(current_modem); eval $mmcli_time_cmd &> /dev/null || eval $qmicli_cmd &> /dev/null; do
    echo "wait time from $modem"
    sleep 1
done

#timedatectl set-ntp false
exit_code=0
eval $mmcli_time_cmd &> /dev/null || exit_code=$?
if [[ $exit_code -eq 0 ]]; then
    echo "mmcli time source"
    current_time=$(eval $mmcli_time_cmd | jq -r '.modem.time.current')
    # date doesn't have -D flag, need busybox
    timestamp_with_timezone=$(busybox date -u -D %Y-%m-%dT%H:%M:%S%z -d "$current_time" +%s)
    date +%s --set @$timestamp_with_timezone 1> /dev/null
else
    echo "qmicli time source"
    qmicli_time_cmd="eval $qmicli_cmd | grep 'System time' | cut -d\' -f 2 | cut -d' ' -f3-"
    past_date=$(date --date="2025-06-01" +%s)
    current_time=$(eval $qmicli_time_cmd)
    # if the year is in the past, we request valid data again.
    while (( $(date --date="$current_time" +%s) < $past_date )); do
        echo "wrong date: $current_time, wait correct date"
        sleep 1
        current_time=$(eval $qmicli_time_cmd)
    done
    TZ=0 date --set "$current_time" 1> /dev/null
fi
#timedatectl set-ntp true
hwclock -w
echo "New time: $(date)"
