#!/usr/bin/env bash
# Build the salmanoff snap from the enclosing SMO repo tree.
set -euo pipefail

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

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

Build salmanoff snap with snapcraft (source: SMO repo root via local snapcraft.yaml).

Options:
  --refetch-source  Clean salmanoff part before pack (re-copy tree + submodules)
  --clean           Remove all snapcraft parts/prime/stage before building
  --lxd             Use LXD cleanroom instead of --destructive-mode
  -h, --help        Show this help

Prerequisites:
  snap install snapcraft --classic
  For --lxd on core26: LXD outbound internet (run: sudo scripts/fix-lxd-network.sh)
  For --destructive-mode: run on Ubuntu 26.04 or use --lxd
EOF
}

clean=false
refetch_source=false
use_lxd=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --clean) clean=true; shift ;;
        --refetch-source) refetch_source=true; shift ;;
        --lxd) use_lxd=true; shift ;;
        -h|--help) usage; exit 0 ;;
        *) echo "Unknown option: $1" >&2; usage >&2; exit 1 ;;
    esac
done

if ! command -v snapcraft >/dev/null 2>&1; then
    echo "snapcraft not found. Install with: sudo snap install snapcraft --classic" >&2
    exit 1
fi

if [[ "$clean" == true ]]; then
    rm -rf "${SNAP_DIR}/parts" "${SNAP_DIR}/stage" "${SNAP_DIR}/prime" \
        "${SNAP_DIR}/.snapcraft" "${SNAP_DIR}"/*.snap 2>/dev/null || true
fi

cd "$SNAP_DIR"

pack_flags=()
if [[ "$use_lxd" != true ]]; then
    pack_flags+=(--destructive-mode)
else
    pack_flags+=(--use-lxd)
fi

if [[ "$refetch_source" == true && "$clean" != true ]]; then
    echo "Refetching salmanoff source (clean part + pull)..."
    snapcraft clean salmanoff "${pack_flags[@]}"
fi

cmd=(snapcraft pack "${pack_flags[@]}")

echo "UC root:  $UC_ROOT"
echo "Snap dir: $SNAP_DIR"
echo "Running:  ${cmd[*]}"

"${cmd[@]}"

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