#!/usr/bin/env bash
# vintage-radio-install.sh — Materializes the Vintage Stereo bundled web assets.
#
# The Vintage Stereo radio template serves its UI through an nginx:alpine
# container that mounts /opt/vintage-radio/web as /usr/share/nginx/html. This
# script copies the assets (index.html, radio.css, radio.js, stations.json)
# from the DashCaddy source tree into that mount target.
#
# Usage:
#   bash /usr/local/bin/vintage-radio-install.sh
#
# Environment overrides:
#   DASHCADDY_ROOT  — Path to the DashCaddy install root (defaults to /opt/dashcaddy).
#   TARGET_DIR      — Mount target directory (defaults to /opt/vintage-radio/web).
#
# Idempotent: safe to re-run; overwrites the target files each time.

set -euo pipefail

DASHCADDY_ROOT="${DASHCADDY_ROOT:-/opt/dashcaddy}"
TARGET_DIR="${TARGET_DIR:-/opt/vintage-radio/web}"
SOURCE_DIR="${DASHCADDY_ROOT}/dashcaddy-api/static-sites/vintage-radio/web"

if [[ ! -d "$SOURCE_DIR" ]]; then
  echo "FATAL: source assets not found at $SOURCE_DIR" >&2
  echo "       Install DashCaddy, or set DASHCADDY_ROOT to its location." >&2
  exit 1
fi

if [[ ! -f "$SOURCE_DIR/index.html" || ! -f "$SOURCE_DIR/radio.css" \
   || ! -f "$SOURCE_DIR/radio.js"   || ! -f "$SOURCE_DIR/stations.json" ]]; then
  echo "FATAL: incomplete assets in $SOURCE_DIR" >&2
  ls -la "$SOURCE_DIR" >&2
  exit 1
fi

mkdir -p "$TARGET_DIR"

install -m 0644 "$SOURCE_DIR/index.html"    "$TARGET_DIR/index.html"
install -m 0644 "$SOURCE_DIR/radio.css"     "$TARGET_DIR/radio.css"
install -m 0644 "$SOURCE_DIR/radio.js"      "$TARGET_DIR/radio.js"
install -m 0644 "$SOURCE_DIR/stations.json" "$TARGET_DIR/stations.json"

chmod 0755 "$TARGET_DIR"

echo "Vintage Stereo assets installed:"
echo "  Source: $SOURCE_DIR"
echo "  Target: $TARGET_DIR"
ls -la "$TARGET_DIR"
