#!/bin/sh

OLD_FINGERPRINT=/etc/unipi/fingerprint
ULIB_PATH="/usr/lib/unipi"

if [ "$(id -u)" != "0" ]; then
    echo "This program must be run as root!" >&2
    exit 1
fi

if bash -c "[[ \"$TERM\" =~ \"color\" ]] || [[ \"$DPKG_COLORS\" != \"never\" ]]"; then
  RED="\e[31m"
  NORMAL="\e[0m"
fi

if [ "$1" = "--check" ]; then
    echo "<6>OS Configurator: check started" > /dev/kmsg
    FG="$($ULIB_PATH/unipiid fingerprint)"
    if [ -n "$FG" ]; then
        rm /run/motd.d/99-unipi-id
    fi

    if [ "$FG" = "$(cat ${OLD_FINGERPRINT})" ]; then
        echo "<6>OS Configurator: Check complete, no changes" > /dev/kmsg
        exit 0
    fi

    echo "<1>OS Configurator: Changes found, calling update..." > /dev/kmsg
    shift

fi
if [ "$1" = "--update" ]; then
    echo "<6>OS Configurator: Update invoked" > /dev/kmsg
    export UNIPI_OSCONF_UPDATE=1
    if python3 "$ULIB_PATH/os-configurator.py" "$@"; then
        "$ULIB_PATH/unipiid" fingerprint > "${OLD_FINGERPRINT}"
        echo "${RED}Reboot system to apply all changes in configuration${NORMAL}"
        sync
        mount / -o remount,ro
        #sleep 2;
        sync
        systemctl start reboot.target --job-mode=replace-irreversibly --no-block
        #systemctl reboot
    fi
    exit $?
fi
if [ "$1" = "--force" ]; then
    export UNIPI_OSCONF_FORCE=1
    if python3 "$ULIB_PATH/os-configurator.py" "$@"; then
        "$ULIB_PATH/unipiid" fingerprint > "${OLD_FINGERPRINT}"
    else
        rm -f "${OLD_FINGERPRINT}"
    fi
    echo "${RED}Reboot system to apply all changes in configuration${NORMAL}"
    exit 0
fi
exec python3 "$ULIB_PATH/os-configurator.py" "$@"
