#!/usr/bin/env bash
# Install and smoke-test the salmanoff snap (strict by default).
set -euo pipefail

UC_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SNAP_DIR="${UC_ROOT}/snaps/salmanoff"

usage() {
    cat <<'EOF'
Usage: test-snap.sh [OPTIONS] [-- ARGS_FOR_SALMANOFF...]

Install the newest salmanoff_*.snap and run a smoke test.

Options:
  --snap PATH     Specific .snap file (default: newest in snaps/salmanoff/)
  --no-install    Skip install; only run snap run (snap already installed)
  --devmode       Install with --devmode (overrides strict snap metadata)
  -- ARGS         Passed to salmanoff (default: --help)
  -h, --help      Show this help
EOF
}

snap_file=""
do_install=true
use_devmode=false
extra_args=(--help)

while [[ $# -gt 0 ]]; do
    case "$1" in
        --snap) snap_file="$2"; shift 2 ;;
        --no-install) do_install=false; shift ;;
        --devmode) use_devmode=true; shift ;;
        --) shift; extra_args=("$@"); break ;;
        -h|--help) usage; exit 0 ;;
        *) extra_args=("$@"); break ;;
    esac
done

if [[ -z "$snap_file" ]]; then
    snap_file="$(ls -1t "${SNAP_DIR}"/*.snap 2>/dev/null | head -1 || true)"
fi

if [[ -z "$snap_file" || ! -f "$snap_file" ]]; then
    if [[ "$do_install" == true ]]; then
        echo "No .snap found. Build first: ./scripts/build-snap.sh" >&2
        exit 1
    fi
else
    echo "Newest .snap: $snap_file"
fi

connect_plugs() {
    local plug
    for plug in network network-bind hardware-observe camera media-control; do
        if snap interfaces 2>/dev/null | grep -q "salmanoff:${plug}"; then
            if ! snap interfaces 2>/dev/null | grep -q "salmanoff:${plug}.*-"; then
                echo "Connecting plug: ${plug}"
                sudo snap connect "salmanoff:${plug}" 2>/dev/null || true
            fi
        fi
    done
}

if [[ "$do_install" == true ]]; then
    install_flags=(--dangerous)
    if [[ "$use_devmode" == true ]]; then
        install_flags+=(--devmode)
    fi
    sudo snap install "${install_flags[@]}" "$snap_file"
    connect_plugs
fi

echo "Running: snap run salmanoff ${extra_args[*]}"
snap run salmanoff "${extra_args[@]}"
