#!/usr/bin/env bash
#
# SPDX-FileCopyrightText: 2025-present Artem Lykhvar and contributors
#
# SPDX-License-Identifier: MIT
#
# vet - A safer way to run remote scripts.
# Version: v1.0.2
#
# This tool fetches a script, shows a diff against previous versions,
# and asks for explicit confirmation before executing.

set -euo pipefail

readonly APP_NAME="vet"
readonly VERSION="v1.0.2"
readonly CACHE_DIR="${HOME}/.cache/${APP_NAME}"

if [ -t 1 ]; then
    readonly C_RESET=$'\033[0m' C_INFO=$'\033[0;34m'  C_WARN=$'\033[0;33m'
    readonly C_ERROR=$'\033[0;31m' C_OK=$'\033[0;32m'    C_BOLD=$'\033[1m'
else
    readonly C_RESET='' C_INFO='' C_WARN='' C_ERROR='' C_OK='' C_BOLD=''
fi

log_info()  { echo -e "${C_INFO}==> $1${C_RESET}"; }
log_warn()  { echo -e "${C_WARN}==> WARNING: $1${C_RESET}"; }
log_error() { echo -e "${C_ERROR}==> ERROR: $1${C_RESET}" >&2; }
log_ok()    { echo -e "${C_OK}==> $1${C_RESET}"; }

usage() {
    cat <<EOF
vet ${VERSION} - A safer way to run remote scripts.

USAGE:
    vet [OPTIONS] <URL> [SCRIPT_ARGUMENTS...]

OPTIONS:
    -f, --force     Skip all interactive prompts and execute immediately.
                    Use with extreme caution in trusted environments.
    -h, --help      Display this help message.
EOF
}

# shellcheck disable=SC2317
cleanup() {
    [ -n "${TMPFILE:-}" ] && [ -f "${TMPFILE}" ] && rm -f "${TMPFILE}"
    [ -n "${TMPFILE_DIFF:-}" ] && [ -f "${TMPFILE_DIFF}" ] && rm -f "${TMPFILE_DIFF}"
}

check_dependencies() {
    if command -v curl &>/dev/null; then
        DOWNLOAD_CMD=(curl -fsSL -o)
    elif command -v wget &>/dev/null; then
        DOWNLOAD_CMD=(wget -qO)
    else
        log_error "This tool requires either 'curl' or 'wget'."
        exit 1
    fi
}

trap cleanup EXIT INT TERM

FORCE_MODE=0

while [[ $# -gt 0 ]]; do
    case "$1" in
        -f|--force)
            FORCE_MODE=1
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        --)
            shift
            break
            ;;
        -?*)
            log_error "Unknown option: $1"
            usage
            exit 1
            ;;
        *)
            break
            ;;
    esac
done

URL="${1-}"

if [ -z "$URL" ]; then
    log_error "No URL provided."
    usage
    exit 1
fi
shift

SCRIPT_ARGS=("$@")

check_dependencies

mkdir -p "$CACHE_DIR"
TMPFILE=$(mktemp) || { log_error "Failed to create temporary file."; exit 1; }
TMPFILE_DIFF=$(mktemp) || { log_error "Failed to create temporary diff file."; exit 1; }

log_info "Downloading script from: $URL"
if ! "${DOWNLOAD_CMD[@]}" "$TMPFILE" "$URL"; then
    log_error "Download failed. Check URL and network connection."
    exit 1
fi

if [ ! -s "$TMPFILE" ]; then
    log_error "Downloaded file is empty. The URL may be incorrect."
    exit 1
fi

# Find a suitable syntax highlighter command,
# accounting for the 'batcat' rename
BAT_CMD=""
if command -v bat &>/dev/null; then
    BAT_CMD="bat"
elif command -v batcat &>/dev/null; then
    BAT_CMD="batcat"
fi

# Generate a filesystem-safe cache key from the URL.
CACHE_FILE_ID=$(echo -n "$URL" | sha256sum | awk '{print $1}')
CACHE_FILE_PATH="${CACHE_DIR}/${CACHE_FILE_ID}.sh"

if [ -f "$CACHE_FILE_PATH" ]; then
    if diff -u "$CACHE_FILE_PATH" "$TMPFILE" > "$TMPFILE_DIFF"; then
        log_ok "No changes detected since last run."
    elif [ "$FORCE_MODE" -eq 0 ]; then
        log_warn "Script has CHANGED since the last run."
        printf "[?] %sShow diff?%s [y/N] " "$C_BOLD" "$C_RESET"
        read -n 1 -r REPLY; echo
        if [[ "$REPLY" =~ ^[Yy]$ ]]; then
            less -U "$TMPFILE_DIFF"
        fi
    fi
fi

execute_script() {
    EXEC_EXIT_CODE=0
    bash "$TMPFILE" "${SCRIPT_ARGS[@]}" || EXEC_EXIT_CODE=$?
    if [ $EXEC_EXIT_CODE -eq 0 ]; then
        cp "$TMPFILE" "$CACHE_FILE_PATH"
        log_info "Script cached for future comparison."
        log_ok "Script finished with exit code ${EXEC_EXIT_CODE}."
    else
        log_warn "Script finished with a non-zero exit code: ${EXEC_EXIT_CODE}."
    fi
    exit $EXEC_EXIT_CODE
}

if [ "$FORCE_MODE" -eq 1 ]; then
    log_warn "Executing in --force mode without review."
    execute_script
fi

if command -v shellcheck &>/dev/null; then
    log_info "Running ShellCheck analysis..."
    if ! shellcheck "$TMPFILE"; then
        log_warn "ShellCheck found potential issues."
        printf "[?] %sContinue with review despite issues?%s [y/N] " "$C_BOLD" "$C_RESET"
        read -n 1 -r REPLY; echo
        if [[ ! "$REPLY" =~ ^[Yy]$ ]]; then
            log_info "Execution aborted due to ShellCheck warnings."
            exit 1
        fi
    else
        log_ok "ShellCheck analysis passed."
    fi
fi

# Check if we are in an interactive terminal before trying to use a pager.
if [ -t 0 ]; then
    # log_info "Displaying script for review. Press 'q' to exit viewer."
    printf "[?] %sDisplaying script for review?%s [y/N] " "$C_BOLD" "$C_RESET"
    read -n 1 -r REPLY; echo
    if [[ "$REPLY" =~ ^[Yy]$ ]]; then
        if [ -n "$BAT_CMD" ]; then
            "$BAT_CMD" -l sh --paging=always "$TMPFILE"
        else
            less -U "$TMPFILE"
        fi
    fi
    printf "[?] %sExecute this script?%s [y/N] " "$C_BOLD" "$C_RESET"
    read -n 1 -r REPLY; echo
else
    # Non-interactive session (e.g., CI/CD): Just print the script content.
    log_info "Running in non-interactive mode. Displaying script content:"
    echo "----------------------------------------------------------------------"
    cat "$TMPFILE"
    echo "----------------------------------------------------------------------"
    if read -t 0.1 -n 1 -r REPLY; then
        echo # Add a newline to match the piped input char.
    else
        # Otherwise for non-interactive mode, we assume 'no'
        # unless --force was used.
        REPLY="n"
    fi
fi

if [[ "$REPLY" =~ ^[Yy]$ ]]; then
    log_info "Executing script..."
    execute_script
else
    log_info "Execution aborted by user."
    exit 1
fi
