#!/bin/bash
# Executed by init script

INITHOOKS_DEFAULT=/etc/default/inithooks
. $INITHOOKS_DEFAULT

TKLINFO=/var/lib/turnkey-info/inithooks.service

unset PID LOGFILE

log() {
    # log to journal as well as $LOGFILE
    LEVEL=$1 # err|warn|info|debug
    shift
    logger -t inithooks -p $LEVEL "$@"
    [ -n "$LOGFILE" ] && echo "${LEVEL^^}: $@" >> "$LOGFILE"
}

if [ "$(echo $REDIRECT_OUTPUT | tr [A-Z] [a-z] )" = "true" ]; then
    # redirect stdout/stderr (use when preseeding headless deployments)
    LOGFILE=/var/log/inithooks.log
    touch $LOGFILE; chmod 640 $LOGFILE

    # on xen redirection is performed by the inithooks-xen service
    # on lxc and other headless deployments, redirection is handled below
    # otherwise redirection is handled by inithooks service and redirected to tty8

    if [ ! -f "$TKLINFO/xen" ]; then
        TTY=$(cat /sys/devices/virtual/tty/tty0/active)
        [ -z $TTY ] && TTY=console
        tail -f $LOGFILE > /dev/$TTY &
        PID="$!"
    fi
fi

exec_scripts() {
    SCRIPT_DIR=$1
    [ -d $SCRIPT_DIR ] || return 0
    for SCRIPT in $(find $SCRIPT_DIR -type f -or -type l | sort); do
        [ -e $INITHOOKS_CONF ] && . $INITHOOKS_CONF
        [ -x $SCRIPT ] || continue
        log info "running $SCRIPT"
        $SCRIPT
        RET=$?
        if [ "$RET" -eq 0 ]; then
            log info "successfully completed $SCRIPT"
        elif [ "$(basename $SCRIPT)" = "95secupdates" ] && [ "$RET" -eq 2 ]; then
            log info "running live, so skipping security updates"
        else
            log warn "completed $SCRIPT - exit code $RET"
        fi
        # the script requested a reboot before we can continue
        if [ $RET -eq 42 ]; then
            log warn "Exit code 42 indicates a reboot is required"
            log err 'Rebooting now!'
            systemctl reboot
            exit 0
        fi
    done
    return 0
}

[ -e $INITHOOKS_CONF ] && . $INITHOOKS_CONF
export INITHOOKS_CONF=$INITHOOKS_CONF

if [ "$(echo $RUN_FIRSTBOOT | tr [A-Z] [a-z] )" = "true" ]; then
    exec_scripts $INITHOOKS_PATH/firstboot.d
fi
exec_scripts $INITHOOKS_PATH/everyboot.d

if [ -n "$PID" ];  then
    kill -9 $PID || true
fi

log info "Inithook run completed, now starting confconsole"
sleep 2 # anyway to replace this?
confconsole --usage
log info "Confconsole completed, now exiting"

exit 0
