#!/bin/sh
# vestibule — CLI entry point inside the Flatpak sandbox.
#
# The Flatpak is a delivery vehicle + self-describing deployment kit: it
# carries usher, the WebExtension, enterprise policies, and the
# provisioning scripts. The actual kiosk provisioning runs on the HOST
# (it must configure systemd, /opt, /etc) — this CLI locates the payload
# from the host's perspective and prints the exact command to run.
#
# Subcommands:
#   vestibule              print status + quick start
#   vestibule version      print the Vestibule version
#   vestibule paths        print host-visible payload paths
#   vestibule provision    print the host-side provisioning command
#
# Host access uses flatpak-spawn (permission: org.freedesktop.Flatpak,
# granted by the manifest). Without it, candidate paths are printed.

VERSION="1.2.2"
APP_ID="net.dcos.Vestibule"
SHARE_REL="files/share/vestibule"

say() { printf '%s\n' "$1"; }

host_sh() {
  # Run a shell snippet on the host. Returns 1 if not permitted.
  flatpak-spawn --host sh -c "$1" 2>/dev/null
}

payload_path() {
  # Resolve the payload directory as visible from the host.
  if host_sh "true"; then
    host_sh "
      for p in \
        /var/lib/flatpak/app/${APP_ID}/current/active/${SHARE_REL} \
        \"\${HOME}/.local/share/flatpak/app/${APP_ID}/current/active/${SHARE_REL}\"; do
        if [ -d \"\$p\" ]; then printf '%s' \"\$p\"; exit 0; fi
      done
      exit 1"
    return
  fi
  return 1
}

cmd_status() {
  say "Vestibule ${VERSION} — kiosk lockdown browser toolkit"
  say ""
  say "This Flatpak carries the deployment kit (usher, extension, policies,"
  say "provisioning scripts). To turn the machine into a kiosk, run:"
  say ""
  cmd_provision
  say ""
  say "Full runbook: DEPLOYMENT.md (also shipped inside this package)."
}

cmd_version() {
  say "${VERSION}"
}

cmd_paths() {
  p=$(payload_path)
  if [ -n "${p}" ]; then
    say "payload : ${p}"
    say "usher   : $(dirname "${p}")/bin/usher"
  else
    say "host access unavailable (flatpak-spawn not permitted). Candidates:"
    say "  /var/lib/flatpak/app/${APP_ID}/current/active/${SHARE_REL}"
    say "  ~/.local/share/flatpak/app/${APP_ID}/current/active/${SHARE_REL}"
  fi
}

cmd_provision() {
  p=$(payload_path)
  if [ -z "${p}" ]; then
    say "# flatpak-spawn not permitted — run on the host:"
    p="/var/lib/flatpak/app/${APP_ID}/current/active/${SHARE_REL}"
  fi
  say "sudo sh '${p}/scripts/provision-kiosk.sh' \\"
  say "     --usher-bin '$(dirname "${p}")/bin/usher' \\"
  say "     --home-url https://your-kiosk-start-page.example.org --yes"
}

case "${1:-status}" in
  status)   cmd_status ;;
  version)  cmd_version ;;
  paths)    cmd_paths ;;
  provision) cmd_provision ;;
  help|-h|--help)
    say "usage: vestibule [status|version|paths|provision]"
    ;;
  *)
    say "unknown command: $1 (try: vestibule help)" >&2
    exit 2
    ;;
esac
