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

# Podman helper for local-page-archiver worker-container runs.
# Usage:
#   ./podman-run.sh build
#   ./podman-run.sh archive <URL> [archive CLI options]
#   ./podman-run.sh vnc-archive <URL> [archive CLI options]

IMAGE_NAME="${ARCHIVE_WORKER_IMAGE:-local-page-archiver:latest}"
ARCHIVE_DIR="${ARCHIVE_DIR:-$(pwd)/archives}"

build_image() {
  podman build -t "${IMAGE_NAME}" .
}

ensure_image() {
  if ! podman image exists "${IMAGE_NAME}"; then
    build_image
  fi
}

case "${1:-}" in
  build)
    build_image
    ;;
  archive)
    shift
    ensure_image
    node src/container-runner.mjs archive \
      --runtime podman \
      --image "${IMAGE_NAME}" \
      --archive-path "${ARCHIVE_DIR}" \
      "$@"
    ;;
  vnc-archive|headful-archive)
    shift
    ensure_image
    node src/container-runner.mjs archive \
      --runtime podman \
      --image "${IMAGE_NAME}" \
      --archive-path "${ARCHIVE_DIR}" \
      --vnc \
      "$@"
    ;;
  help|"")
    cat <<EOF
Usage:
  ./podman-run.sh build
  ./podman-run.sh archive <URL> [archive CLI options]
  ./podman-run.sh vnc-archive <URL> [archive CLI options]

Environment:
  ARCHIVE_WORKER_IMAGE=${IMAGE_NAME}
  ARCHIVE_DIR=${ARCHIVE_DIR}
EOF
    ;;
  *)
    ensure_image
    node src/container-runner.mjs archive \
      --runtime podman \
      --image "${IMAGE_NAME}" \
      --archive-path "${ARCHIVE_DIR}" \
      "$@"
    ;;
esac
