#!/bin/bash
# Executed by init script

# load/set general global vars
INITHOOKS_DEFAULT="${INITHOOKS_DEFAULT:-/etc/default/inithooks}"
# - give shellcheck explict repo path for linting package
# shellcheck source=default/inithooks
source "$INITHOOKS_DEFAULT"
TERM=${TERM:-linux}
RUN_FIRSTBOOT="${RUN_FIRSTBOOT,,}"
TKLINFO="${TKLINFO:-/var/lib/turnkey-info}"
REDIRECT_OUTPUT="${REDIRECT_OUTPUT,,}"
PID=

# load preseeds if they exist - although preseeds file should always be empty
# unless RUN_FIRSTBOOT=true (firstboot will wipe preseeds file)
if [[ -f $INITHOOKS_CONF ]]; then
    # hide this shellcheck warning for now, although we probably should
    # include an example conf file?!
    # shellcheck source=/dev/null
    source "$INITHOOKS_CONF"
    export INITHOOKS_CONF="$INITHOOKS_CONF"
fi

# ensure that log file exists and has appropriate permissions
export INITHOOKS_LOGFILE="${INITHOOKS_LOGFILE:-/var/log/inithooks.log}"
mkdir -p "$(dirname "$INITHOOKS_LOGFILE")"
touch "$INITHOOKS_LOGFILE"
chmod 640 "$INITHOOKS_LOGFILE"

everyboot_ran() {
    # read lastboot time
    lastboot_time="$(date '+%s' -d "$(cut -f1 -d. /proc/uptime) seconds ago")"
    if [[ -f /run/inithooks/everyboot_ran ]]; then
        # time stamp written
        prev_lastboot_time="$(</run/inithooks/everyboot_ran)"
        if [[ "$lastboot_time" -eq "$prev_lastboot_time" ]]; then
            # time stamp of last boot is the same as our last boot, everyboot
            # scripts already ran
            return 0
        else
            # time stamp of last boot is different from our last boot, everyboot
            # scripts not already ran
            echo "$lastboot_time" > /run/inithooks/everyboot_ran
            return 1
        fi
    else
        # no time stamp written, haven't run everyboot scripts since last boot
        mkdir -p /run/inithooks
        echo "$lastboot_time" > /run/inithooks/everyboot_ran
        return 1
    fi
}

log() {
    # log to journal as well as $INITHOOKS_LOGFILE
    local level=$1 # err|warn|info|debug
    shift
    logger -t inithooks -p "${level,,}" "$@"
    if [[ -f "$INITHOOKS_LOGFILE" ]]; then
        echo "${level^^}: $*" >> "$INITHOOKS_LOGFILE"
    fi
}

if [[ "$REDIRECT_OUTPUT" == "true" ]]; then
    # 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)
        if [[ -z $TTY ]]; then
            TTY=console
        fi
        tail -f "$INITHOOKS_LOGFILE" > "/dev/$TTY" &
        PID="$!"
    fi
fi

exec_scripts() {
    local script_dir=$1
    local script_executable=
    local script=
    [[ -d "$script_dir" ]] || return 0
    readarray -d '' all_scripts < <(find "$script_dir" \( -type f -or -type l \) -print0 | sort -z)
    for script_executable in "${all_scripts[@]}"; do
        # this is already sourced above is it needed again here?
        if [[ -e $INITHOOKS_CONF ]]; then
            # as per above shellcheck $INITHOOKS_CONF note
            # shellcheck source=/dev/null
            source "$INITHOOKS_CONF"
        fi
        script=$(basename "$script_executable")
        if [[ ! -x "$script_executable" ]]; then
            log warn "[$script] skipping"
            continue
        fi
        log info "[$script] running"
        "$script_executable"
        exit_code=$?
        if [[ "$exit_code" -eq 0 ]]; then
            log info "[$script] successfully completed"
        elif [[ "$script" = "95secupdates" ]] && [[ "$exit_code" -eq 2 ]]; then
            log info "[$script] detected live system - skipping"
        elif [[ "$script" = "95secupdates" ]] && [[ "$exit_code" -eq 42 ]]; then
            log warn "[$script] reboot is required"
            log err 'Rebooting now!'
            systemctl reboot
            exit 0
        else
            log err "[$script] failed - exit code $exit_code"
        fi
    done
    return 0
}


if [[ "$RUN_FIRSTBOOT" == "true" ]]; then
    log info "Running firstboot scripts"
    exec_scripts "$INITHOOKS_PATH/firstboot.d"
fi

if ! everyboot_ran; then
    log info "Running everyboot scripts"
    exec_scripts "$INITHOOKS_PATH/everyboot.d"
fi

if [[ -n "$PID" ]];  then
    log info "Killing inithooks pid $PID"
    kill -9 $PID || true
fi

if [[ "$REDIRECT_OUTPUT" == "true" ]]; then
    log info "Inithook run completed, exiting."
else
    log info "Inithook run completed, now starting confconsole"
    sleep 2 # anyway to replace this?
    confconsole --usage
    log info "Confconsole started, inithooks exiting"
fi

exit 0
