#!/usr/bin/env bash
# Build stock Ubuntu Core 26 amd64 image from Canonical's signed model assertion.
set -euo pipefail

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

MODEL="${UC_ROOT}/models/ubuntu-core-26-amd64.model"
WORKDIR="${UC_ROOT}/work/ubuntu-image-snap"
OUTPUT_DIR="${UC_ROOT}/artifacts/images"
LOG_DIR="${UC_ROOT}/artifacts/logs"

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

Build a stock ubuntu-core-26-amd64 disk image with ubuntu-image snap.

Options:
  --fresh-workdir   Remove work/ubuntu-image-snap before building (full re-download)
  --resume          Pass --resume to ubuntu-image (continue partial build)
  -h, --help        Show this help

Outputs:
  artifacts/images/pc.img
  artifacts/images/pc.img.seed.manifest
  artifacts/logs/build-<timestamp>.log

Host prerequisites:
  snap install ubuntu-image --classic
  scripts/fetch-model.sh   (download signed model if missing)
EOF
}

fresh_workdir=false
resume=false

while [[ $# -gt 0 ]]; do
    case "$1" in
        --fresh-workdir) fresh_workdir=true; shift ;;
        --resume) resume=true; shift ;;
        -h|--help) usage; exit 0 ;;
        *) echo "Unknown option: $1" >&2; usage >&2; exit 1 ;;
    esac
done

if [[ ! -f "$MODEL" ]]; then
    echo "Missing model assertion: $MODEL" >&2
    echo "Run: scripts/fetch-model.sh" >&2
    exit 1
fi

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

mkdir -p "$OUTPUT_DIR" "$LOG_DIR"

if [[ "$fresh_workdir" == true ]] || [[ "$resume" == false ]]; then
    if [[ -d "$WORKDIR" ]]; then
        echo "Removing workdir: $WORKDIR"
        rm -rf "$WORKDIR"
    fi
fi
mkdir -p "$WORKDIR"

timestamp="$(date +%Y%m%d-%H%M%S)"
log_file="${LOG_DIR}/build-${timestamp}.log"

cmd=(ubuntu-image snap
    --workdir "$WORKDIR"
    --output-dir "$OUTPUT_DIR"
    --image-size 4G
    "$MODEL")

if [[ "$resume" == true ]]; then
    cmd+=(--resume)
fi

echo "Model:      $MODEL"
echo "Workdir:    $WORKDIR"
echo "Output dir: $OUTPUT_DIR"
echo "Log:        $log_file"
echo "Running:    ${cmd[*]}"

"${cmd[@]}" 2>&1 | tee "$log_file"

img="${OUTPUT_DIR}/pc.img"
if [[ ! -f "$img" ]]; then
    echo "Build finished but $img not found" >&2
    exit 1
fi

echo ""
echo "Done. Image: $img"
ls -lh "$img" "${img}.seed.manifest" 2>/dev/null || ls -lh "$img"
