#!/usr/bin/bash

# source bash base library
# shellcheck disable=SC1091
source /usr/libexec/bash-base.bash || {
   echo "$0: fatal error: failed to source /usr/libexec/bash-base.bash" >&2
   exit 1
}

function main() {
    bb_msg_del_target default_info_err
    case "${GROB_CALLBACK_LOGLEVEL-9}" in
        0) bb_msg_set_target notrace_stderr stderr err prog notrace;;
        1) bb_msg_set_target notrace_stderr stderr info:err prog notrace;;
        *) bb_msg_set_target notrace_stderr stderr debug:err prog notrace
    esac

    bb_msg debug "starting up"

    if [[ -z "${GROB_OTP-}" ]]
    then
        bb_fatal "FATAL ERROR, GROB_OTP not defined"
    else
        local remote_otp
        bb_msg debug "waiting for GROB_OTP"
        read -r remote_otp
        if [[ "$remote_otp" == "$GROB_OTP" ]]
        then
            bb_msg info "calling: borg serve --append-only" \
                "--restrict-to-repository=\"$GROB_REPO_PATH\""
            borg serve \
                --append-only \
                --restrict-to-repository="$GROB_REPO_PATH"
        else
            bb_fatal "remote otp is invalid ($remote_otp != $GROB_OTP)," \
                "aborting"
        fi
    fi
}

main "$@"
bb_quit
