#!/bin/sh
# publish.sh — Copy built ISO to CMS nginx downloads
#
# Called after build.sh completes successfully. Copies the ISO to the
# CMS jail's nginx /downloads/ directory for public distribution.
#
# Requirements:
#   - Must run as root (sudo)
#   - CMS jail must be running
#   - Assumes CMS mountpoint: /jails/cms (customize below if needed)

set -e

SCRIPT_DIR="$(dirname "$(realpath "$0")")"
PARENT_DIR="$(dirname "$SCRIPT_DIR")"
OUTPUT_DIR="${PARENT_DIR}/tmp/output"
. "${PARENT_DIR}/build.cfg"

# CMS jail location (customize if different)
CMS_JAIL_ROOT="/jails/cms"
CMS_DOWNLOADS="${CMS_JAIL_ROOT}/usr/local/nginx/html/downloads"

# Find the most recent built ISO
ISO_FILE=$(ls -t "${OUTPUT_DIR}"/clawdie-iso-*.img 2>/dev/null | head -1)

if [ -z "$ISO_FILE" ]; then
    echo "ERROR: No ISO file found in ${OUTPUT_DIR}"
    exit 1
fi

echo "==> Publishing ISO to CMS downloads..."
echo "    Source: ${ISO_FILE}"
echo "    Destination: ${CMS_DOWNLOADS}/"

if [ ! -d "$CMS_DOWNLOADS" ]; then
    echo "ERROR: CMS downloads directory not found: ${CMS_DOWNLOADS}"
    echo "       Is the CMS jail running? Check CMS_JAIL_ROOT setting."
    exit 1
fi

# Copy ISO to CMS (preserve modification time)
cp -p "$ISO_FILE" "${CMS_DOWNLOADS}/"
echo "    Done."
