#!/live/bin/sh

### BEGIN INIT INFO
# Provides:          persist-autosave
# Required-Start:
# Required-Stop:
# Should-Start:
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description:
# Description:       Run persist-config on startup if needed.  Run persist-save if needed
### END INIT INFO

export PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:/live/bin

test -d /live/config/tsplash && DO_TSPLASH=true

# . /usr/share/antiX/lib/live-init-utils.sh
. /live/lib/live-init-utils.sh

read DISTRO 2>/dev/null </live/config/distro
case $DISTRO in
    [mM][xX]*) LOCKOUT_TIME=60 ;;
            *) LOCKOUT_TIME=15 ;;
esac

start_init_logging
load_translation
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/live/bin

[ "$LIB_CMD_LANG" ] && export LANG=$LIB_CMD_LANG.UTF-8

main() {
    case $1 in
        start) do_start                      ;;
         stop) do_stop                       ;;
            *) echo "Usage: $0 {start|stop}"
               exit 1                        ;;
    esac
    exit 0
}

do_start() {
    local persist_conf=/etc/live/config/persist-config.conf
    local new_passwd=/live/config/new-passwords

    # Bail early if no persist-config is needed
    if [ -e $persist_conf ]; then
        # But still do a persist-save if there are new passwords
        [ -e $new_passwd ] || exit 0
        echo "Saving new passwords in persistence file"
        persist-save --quiet -cli --nolog
        exit 0
    fi

    [ "$DO_TSPLASH" ] && tsplash_clear

    persist-config --cli --startup --nolog
    [ -e $persist_conf -o -e $new_passwd ] || exit 0
    [ -e $new_passwd ]   && echo_live "$_Save_new_passwords_"
    [ -e $persist_conf ] && echo_live "$_Save_new_autosave_selection_"

    persist-save --quiet -cli --nolog

    [ "$DO_TSPLASH" ] && tsplash-on
}

do_stop() {

    # bail early
    [ -e /live/config/save-persist ] || return
    echo_script "$_Possibly_save_persistent_information_" $0

    # Don't auto-save twice in a row
    local last_as_file=/live/config/last-auto-save
    local last_ps_file=/live/config/last-persist-save

    local file prev now=$(date +%s)
    for file in $last_as_file $last_ps_file; do
        test -r $file || continue
        read prev 2>/dev/null <$file
        local diff=$(( $now - $prev))
        if [ $diff -le $LOCKOUT_TIME ]; then
            echo_live "$_Already_saved_X_seconds_ago_" $diff
            echo_live "$_Wont_autosave_within_X_seconds_of_a_previous_save_" $LOCKOUT_TIME
            return
        fi
    done

    local p_config=/usr/local/bin/persist-config
    test -x $p_config && $p_config --cli --shutdown
}

#------------------------------------------------------------------------------
#
#------------------------------------------------------------------------------
tsplash_clear() {
    [ "$DO_TSPLASH" ] || return

    if [ -z "$TSPLASH_CLEARED" ]; then
        clear
        sleep .2
        TSPLASH_CLEARED=true
    fi
    chvt 1
}

main "$@" 2>&1 | tee -a $INIT_LOG_FILE

