#!/bin/bash

source $(dirname $0)/setman-common.sh
source $(dirname $0)/setman-metadata.sh

export SETMAN_COMPONENT=setman-boot

set_next_action_to_init() {
    setman-action delete
    setman-action write init
    exit 0
}

mkdir -p "${SETMAN_SERVICE_STARTUP_FINISHED_PATH}"

if ! command -v inotifywait &> /dev/null; then
    setman-log error "Missing inotifywait util"
fi

action=$(setman-action read-action)

if [ $? -ne 0 ]; then
    setman-log warning "no action in next action, writing init"
    set_next_action_to_init
else
    boot_action=$(setman-action read)

    $(setman_is_valid_action ${boot_action})
    if [ $? -ne 0 ]; then
        set_next_action_to_init
    fi

    setman-log notice "execute pending action: ${boot_action}"
fi

if [ "$action" == "restore" ]; then
    restore_paths=$(setman-action read-restore-dirs)
    if [ $? != 0 ]; then
        setman-log error "restore paths reading failed, fall back to init"
        set_next_action_to_init
    fi

    $(setman-action is-forced)
    forced_output=$?

    for restore_path in $restore_paths; do
        verify_restore_output=$(setman_verify_restore $restore_path !$forced_output)
        if [ $? -ne 0 ]; then
            setman-log error "verify_restore_output failed with: $verify_restore_output, fall back to init"
            set_next_action_to_init
        fi
    done
elif [ "$action" == "backup" ]; then
    backup_path=$(setman-action read-backup-dir)
    if [ $? != 0 ]; then
        setman-log error "backup dir path reading failed, fall back to init"
        set_next_action_to_init
    fi

    verify_backup_output=$(setman_verify_backup_dir $backup_path)
    if [ $? -ne 0 ]; then
        setman-log error "setman_verify_backup_dir failed with: $verify_backup_output, fall back to init"
        set_next_action_to_init
    fi
fi

