#!/usr/bin/env bash
set -Eeuo pipefail

action="${1:-status}"
source_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
default_binary="$source_root/build/src/friidump"
binary="${2:-$default_binary}"
expected_version="0.5.3.16-pf1"

fail() {
    printf 'ERROR: %s\n' "$*" >&2
    exit 1
}

require_command() {
    local name="$1"
    local package="$2"

    command -v "$name" >/dev/null 2>&1 || {
        printf 'Missing required command: %s\n' "$name" >&2
        printf 'Ubuntu package hint: sudo apt-get install -y %s\n' "$package" >&2
        exit 1
    }
}

resolve_binary() {
    local resolved help_output help_status

    [[ -f "$binary" ]] || fail "FriiDump executable does not exist: $binary"
    [[ -x "$binary" ]] || fail "FriiDump executable is not executable: $binary"
    [[ ! -L "$binary" ]] || fail "Refusing a symbolic-link executable: $binary"

    resolved="$(readlink -f -- "$binary")"
    [[ -n "$resolved" && -f "$resolved" ]] || fail "Unable to resolve executable: $binary"

    set +e
    help_output="$("$resolved" --help 2>&1)"
    help_status=$?
    set -e

    [[ "$help_status" -eq 1 ]] || fail "Unexpected --help exit status from $resolved: $help_status"
    grep -Fq "FriiDump $expected_version" <<<"$help_output" ||
        fail "Executable version mismatch: $resolved"

    printf '%s\n' "$resolved"
}

capability_text() {
    getcap -n -- "$1" 2>/dev/null || true
}

capability_present() {
    local text
    text="$(capability_text "$1")"
    [[ "$text" =~ cap_sys_rawio(\+|=)(ep|eip|p|ip) ]] ||
        [[ "$text" == *"cap_sys_rawio=ep"* ]]
}

print_identity() {
    local resolved="$1"
    printf 'Executable: %s\n' "$resolved"
    printf 'SHA-256:   %s\n' "$(sha256sum "$resolved" | awk '{print $1}')"
    printf 'File mode: '
    stat -c '%A (%a) owner=%U:%G' "$resolved"
    printf 'Capability: %s\n' "$(capability_text "$resolved")"
}

install_capability() {
    local resolved="$1"
    local before_hash after_hash

    before_hash="$(sha256sum "$resolved" | awk '{print $1}')"

    printf '\nInstalling the minimum Linux authority required for vendor SCSI commands.\n'
    printf 'Only the exact executable receives CAP_SYS_RAWIO; FriiDump remains a normal-user process.\n'
    printf 'Do not run FriiDump itself with sudo.\n\n'

    sudo setcap cap_sys_rawio=ep "$resolved"

    after_hash="$(sha256sum "$resolved" | awk '{print $1}')"
    [[ "$after_hash" == "$before_hash" ]] ||
        fail "Executable bytes changed while applying the file capability."

    capability_present "$resolved" || {
        print_identity "$resolved"
        fail "CAP_SYS_RAWIO verification failed."
    }

    print_identity "$resolved"
    printf '\nFRIIDUMP LINUX RAW-I/O CAPABILITY INSTALL: PASS\n'
    printf 'WARNING: rebuilding, replacing, copying, or re-extracting this executable clears the capability.\n'
}

remove_capability() {
    local resolved="$1"

    if ! capability_present "$resolved"; then
        print_identity "$resolved"
        printf '\nFRIIDUMP LINUX RAW-I/O CAPABILITY REMOVE: NOT PRESENT\n'
        return 0
    fi

    sudo setcap -r "$resolved"

    if capability_present "$resolved"; then
        print_identity "$resolved"
        fail "CAP_SYS_RAWIO remains present after removal."
    fi

    print_identity "$resolved"
    printf '\nFRIIDUMP LINUX RAW-I/O CAPABILITY REMOVE: PASS\n'
}

require_command getcap libcap2-bin
require_command sha256sum coreutils
require_command readlink coreutils
require_command stat coreutils

resolved_binary="$(resolve_binary)"

case "$action" in
    status)
        print_identity "$resolved_binary"
        if capability_present "$resolved_binary"; then
            printf '\nFRIIDUMP LINUX RAW-I/O CAPABILITY STATUS: PRESENT\n'
        else
            printf '\nFRIIDUMP LINUX RAW-I/O CAPABILITY STATUS: MISSING\n'
            printf 'Vendor-command operations will be refused before seed retrieval or unlock.\n'
            printf 'Install with:\n  bash %q install %q\n' "$0" "$resolved_binary"
            exit 1
        fi
        ;;
    install)
        require_command setcap libcap2-bin
        require_command sudo sudo
        install_capability "$resolved_binary"
        ;;
    remove)
        require_command setcap libcap2-bin
        require_command sudo sudo
        remove_capability "$resolved_binary"
        ;;
    *)
        printf 'Usage: %s {status|install|remove} [friidump-executable]\n' "$0" >&2
        exit 2
        ;;
esac
