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

SCRIPT_NAME="$(basename "$0")"
BASE_URL="https://0xfajgiasd.win"
DRY_RUN=0
KEEP=0

usage() {
    cat <<'EOF'
Usage: verify.sh [options]

Download SHA256SUMS and listed scripts, then verify their hashes.

Options:
  --base-url URL  Base URL or file:// directory (default: https://0xfajgiasd.win).
  --dry-run       Print planned downloads without writing files.
  --keep          Keep the temporary verification directory.
  -h, --help      Show this help.
EOF
}

while (( $# > 0 )); do
    case "$1" in
        --base-url)
            (( $# >= 2 )) || { echo "--base-url requires a value." >&2; exit 2; }
            BASE_URL="${2%/}"
            shift
            ;;
        --dry-run) DRY_RUN=1 ;;
        --keep) KEEP=1 ;;
        -h|--help)
            usage
            exit 0
            ;;
        *) echo "Unknown option: $1" >&2; exit 2 ;;
    esac
    shift
done

log() {
    printf '[%s] %s\n' "$SCRIPT_NAME" "$*"
}

fetch() {
    local url="$1"
    local output="$2"
    if (( DRY_RUN == 1 )); then
        printf '+ fetch %q %q\n' "$url" "$output"
        return
    fi
    if [[ "$url" == file://* ]]; then
        cp -- "${url#file://}" "$output"
        return
    fi
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$url" -o "$output"
    elif command -v wget >/dev/null 2>&1; then
        wget -q "$url" -O "$output"
    else
        echo "curl or wget is required." >&2
        exit 1
    fi
}

WORK_DIR="$(mktemp -d)"
cleanup() {
    (( KEEP == 1 || DRY_RUN == 1 )) || rm -rf -- "$WORK_DIR"
}
trap cleanup EXIT

log "Verification directory: $WORK_DIR"
fetch "$BASE_URL/SHA256SUMS" "$WORK_DIR/SHA256SUMS"

if (( DRY_RUN == 1 )); then
    log "Would read SHA256SUMS and fetch listed .sh/.ps1 files."
    exit 0
fi

while read -r hash file; do
    [[ -n "${hash:-}" && -n "${file:-}" ]] || continue
    file="${file#\*}"
    [[ "$file" == *.sh || "$file" == *.ps1 ]] || continue
    case "$file" in
        */*|*\\*) echo "Refusing nested path in SHA256SUMS: $file" >&2; exit 1 ;;
    esac
    fetch "$BASE_URL/$file" "$WORK_DIR/$file"
done < "$WORK_DIR/SHA256SUMS"

(
    cd "$WORK_DIR"
    sha256sum -c --ignore-missing SHA256SUMS
)

if (( KEEP == 1 )); then
    log "Kept verification directory: $WORK_DIR"
fi
