# shellcheck shell=sh disable=SC3043
# Section: init

___x_cmd_job_failfast_pidofsubshell(){
    sh -c 'printf "pid:%s/%s\n" '"$___X_CMD_JOB_OFFER_LEN"' "$PPID"'
}

___x_cmd_job_failfast_pidofsubshell0(){
    sh -c 'printf "%s\n" "$PPID"'
}

___X_CMD_JOB_LOGSTORE="${___X_CMD_LOG_STORE_DEFAULT}/job/DEFAULT"
___X_CMD_JOB_LOGSTORE_LIST="$___X_CMD_JOB_LOGSTORE/list"

___x_cmd_job_failfast_init(){
    job:info "Starting job init"

    ___X_CMD_JOB_FAILFAST_INTERRUPTED=""
    ___X_CMD_JOB_OFFER_ALIVE=0
    ___X_CMD_JOB_OFFER_LEN=0

    ___X_CMD_JOB_RUNID="$(x pidid)"

    ___X_CMD_JOB_OFFER_MAX="${1:-8}"
    ___X_CMD_JOB_DESC="${2:-""}"
    ___X_CMD_JOB_OFFER_LOG="${___X_CMD_JOB_LOGSTORE}/${___X_CMD_JOB_RUNID}"
    ___X_CMD_JOB_OFFER_LOG_DISPATCHER="${___X_CMD_JOB_OFFER_LOG}/dispatcher"

    [ ! -d "${___X_CMD_JOB_OFFER_LOG}" ] || x rmrf "${___X_CMD_JOB_OFFER_LOG}"
    x mkdirp "${___X_CMD_JOB_OFFER_LOG}"

    printf "%s\n%s\n" "$___X_CMD_JOB_RUNID" "$___X_CMD_JOB_DESC" >>"$___X_CMD_JOB_LOGSTORE_LIST"
    printf "%s\n" "${___X_CMD_JOB_OFFER_LOG}"
    job:info "LogDir=${___X_CMD_JOB_OFFER_LOG}"

    ___x_cmd_job_failfast_pidofsubshell0

    trap '
        ___X_CMD_JOB_FAILFAST_INTERRUPTED=1         # Error Exit
        job:warn "Interrupted. Recv ErrorExit. Clear SIGINT for the following exit process.";
        trap "" INT;
    ' USR2      # Error Exit: errexit

    trap '
        ___X_CMD_JOB_FAILFAST_INTERRUPTED=1
        printf "%s\n" "interrupt"
        job:warn "Interrupted. Recv SIGINT in $___X_CMD_PIDOFSUBSHELL. Clear SIGINT for the following exit process.";
        trap "" INT;
    ' INT       # Interrupt by user
}

___x_cmd_job_failfast_max(){
    printf "%s\n" "$___X_CMD_JOB_OFFER_MAX"
}

___x_cmd_job_failfast_setmax(){
    ___X_CMD_JOB_OFFER_MAX="${1:?Provide max}"
}

## EndSection
