#!/usr/bin/env bash
# Copyright (c) 2026 Oracle and/or its affiliates.
set -euo pipefail

bundle_dir="${OCI_DR_HPC_OCA_BUNDLE:-/usr/libexec/oracle-cloud-agent/bundled/oci-dr-hpc-v2}"
config_file="${OCI_DR_HPC_OCA_CONFIG:-/etc/oci-dr-hpc-v2/oci-dr-hpc-v2.yml}"
default_binary="$bundle_dir/oci-dr-hpc-v2"
snap_default_binary="${OCI_DR_HPC_OCA_SNAP_BINARY:-/snap/oracle-cloud-agent/current/usr/libexec/oracle-cloud-agent/bundled/oci-dr-hpc-v2/oci-dr-hpc-v2}"
validation_timeout_seconds=5
validation_output_limit_kib=64

log() {
    printf 'oci-dr-hpc-v2 selector: %s\n' "$*" >&2
}

trim() {
    local value="$1"
    value="${value#"${value%%[![:space:]]*}"}"
    value="${value%"${value##*[![:space:]]}"}"
    printf '%s' "$value"
}

read_executable_path() {
    local schema_lines path_lines unexpected_lines value

    unexpected_lines="$(sed -nE \
        '/^[[:space:]]*($|#)/d; /^(schema_version|executable_path)[[:space:]]*:/d; p' \
        "$config_file")"
    [[ -z "$unexpected_lines" ]] || return 1

    schema_lines="$(sed -nE 's/^schema_version[[:space:]]*:[[:space:]]*(1)[[:space:]]*(#.*)?$/\1/p' "$config_file")"
    [[ "$schema_lines" == "1" ]] || return 1

    path_lines="$(sed -nE 's/^executable_path[[:space:]]*:[[:space:]]*(.*)$/\1/p' "$config_file")"
    [[ -n "$path_lines" && "$path_lines" != *$'\n'* ]] || return 1
    value="${path_lines%%#*}"
    value="$(trim "$value")"
    if [[ "$value" == \"*\" && "$value" == *\" ]]; then
        value="${value:1:${#value}-2}"
    elif [[ "$value" == \'*\' && "$value" == *\' ]]; then
        value="${value:1:${#value}-2}"
    fi
    [[ -z "$value" || "$value" = /* ]] || return 1
    printf '%s' "$value"
}

path_owner_mode() {
    local path="$1" metadata

    if metadata="$(stat -c '%u %a' -- "$path" 2>/dev/null)"; then
        printf '%s\n' "$metadata"
    else
        stat -f '%u %Lp' "$path" 2>/dev/null
    fi
}

validate_trusted_path() {
    local path="$1" expected_type="$2" component metadata owner mode mode_value

    [[ "$path" = /* && "$path" != *"//"* && "$path" != */../* && "$path" != */./* ]] ||
        return 1

    component="$path"
    while true; do
        [[ ! -L "$component" ]] || return 1
        if [[ "$component" == "$path" ]]; then
            case "$expected_type" in
                executable) [[ -f "$component" && -x "$component" ]] || return 1 ;;
                file) [[ -f "$component" ]] || return 1 ;;
                *) return 1 ;;
            esac
        else
            [[ -d "$component" ]] || return 1
        fi

        metadata="$(path_owner_mode "$component")" || return 1
        read -r owner mode <<< "$metadata"
        [[ "$owner" =~ ^[0-9]+$ && "$mode" =~ ^[0-7]+$ ]] || return 1
        # OCA invokes this launcher as root. Allowing the invoking user here as
        # well keeps non-privileged local tests useful without weakening a root run.
        [[ "$owner" == 0 || ( "${EUID:-$(id -u)}" != 0 && "$owner" == "${EUID:-$(id -u)}" ) ]] ||
            return 1
        mode_value=$((8#$mode))
        (( (mode_value & 0022) == 0 )) || return 1

        [[ "$component" == / ]] && break
        component="${component%/*}"
        [[ -n "$component" ]] || component=/
    done
}

probe_binary_version() {
    local path="$1" output_file probe_pid timer_pid status

    output_file="$(mktemp /tmp/oci-dr-hpc-v2-version.XXXXXX)" || return 1
    (
        # Bound a broken override's output independently of the time limit.
        # Bash expresses RLIMIT_FSIZE in KiB; the kernel stops further writes.
        ulimit -f "$validation_output_limit_kib"
        exec "$path" --version
    ) > "$output_file" 2>&1 &
    probe_pid=$!
    (
        sleep "$validation_timeout_seconds"
        kill -TERM "$probe_pid" 2>/dev/null || exit 0
        sleep 1
        kill -KILL "$probe_pid" 2>/dev/null || true
    ) >/dev/null 2>&1 &
    timer_pid=$!

    if wait "$probe_pid"; then
        status=0
    else
        status=$?
    fi
    kill "$timer_pid" >/dev/null 2>&1 || true
    wait "$timer_pid" 2>/dev/null || true
    cat "$output_file"
    rm -f "$output_file"
    return "$status"
}

validate_default_binary() {
    if [[ -L "$default_binary" ]]; then
        [[ "$(readlink "$default_binary")" == "$snap_default_binary" && \
            -f "$default_binary" && -x "$default_binary" ]]
        return
    fi
    [[ -f "$default_binary" && -x "$default_binary" ]]
}

validate_override_binary() {
    local path="$1" output version

    validate_trusted_path "$path" executable || return 1
    output="$(probe_binary_version "$path")" || return 1
    version="$(printf '%s\n' "$output" |
        sed -nE 's/^oci-dr-hpc-v2 version[[:space:]]+([^[:space:]]+).*$/\1/p' |
        tail -n 1)"
    [[ -n "$version" ]]
}

selected_binary="$default_binary"
if [[ -e "$config_file" || -L "$config_file" ]]; then
    if ! validate_trusted_path "$config_file" file; then
        log "override configuration is not root-controlled; using bundled default"
    elif configured_path="$(read_executable_path)"; then
        if [[ -z "$configured_path" ]]; then
            log "executable override is empty; using bundled default"
        elif [[ -f "$configured_path" && -x "$configured_path" && ! -L "$configured_path" ]]; then
            if validate_override_binary "$configured_path"; then
                selected_binary="$configured_path"
                log "using executable override $configured_path"
            else
                log "executable override is not a compatible oci-dr-hpc-v2 binary; using bundled default"
            fi
        else
            log "executable override is missing or unsafe; using bundled default"
        fi
    else
        log "override configuration is invalid; using bundled default"
    fi
else
    log "override configuration is absent; using bundled default"
fi

if [[ "$selected_binary" == "$default_binary" ]]; then
    validate_default_binary || {
        log "bundled default is missing or unsafe: $default_binary"
        exit 1
    }
else
    validate_trusted_path "$selected_binary" executable || {
        log "selected override is missing or unsafe: $selected_binary"
        exit 1
    }
fi

exec "$selected_binary" "$@"
