#!/bin/sh
# run-builder.sh — trigger containerized ISO build on a remote builder host
#
# Usage:
#   sh scripts/run-builder.sh
#   sh scripts/run-builder.sh --authorized-keys /path/to/authorized_keys

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# load .env
ENV_FILE="${REPO_ROOT}/.env"
if [ -f "$ENV_FILE" ]; then
    # shellcheck disable=SC1090
    . "$ENV_FILE"
fi

BUILDER_HOST="${BUILDER_HOST:-}"
BUILDER_USER="${BUILDER_USER:-}"
if [ -z "$BUILDER_HOST" ]; then
    echo "ERROR: BUILDER_HOST not set. Copy .env.example to .env and set the address."
    exit 1
fi
if [ -z "$BUILDER_USER" ]; then
    echo "ERROR: BUILDER_USER not set. Set it in .env."
    exit 1
fi

EXTRA_ARGS=""
while [ $# -gt 0 ]; do
    case "$1" in
        --authorized-keys) EXTRA_ARGS="--authorized-keys $2"; shift 2 ;;
        *) echo "unknown arg: $1"; exit 1 ;;
    esac
done

echo "=== bee builder ==="
echo "Builder: ${BUILDER_USER}@${BUILDER_HOST}"
echo ""

# --- check local repo is in sync with remote ---
cd "${REPO_ROOT}"
git fetch --quiet origin main
LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse origin/main)
if [ "$LOCAL" != "$REMOTE" ]; then
    echo "ERROR: local repo is not in sync with remote."
    echo "  local:  $LOCAL"
    echo "  remote: $REMOTE"
    echo ""
    echo "Push or pull before building:"
    echo "  git push   — if you have unpushed commits"
    echo "  git pull   — if remote is ahead"
    exit 1
fi
echo "repo: in sync with remote ($LOCAL)"
echo ""

ssh -o StrictHostKeyChecking=no "${BUILDER_USER}@${BUILDER_HOST}" /bin/sh <<ENDSSH
set -e
REPO="/home/${BUILDER_USER}/bee"
LOG=/tmp/bee-build.log

if [ ! -d "\$REPO/.git" ]; then
    echo "--- cloning bee repo ---"
    git clone https://git.mchus.pro/reanimator/bee.git "\$REPO"
fi

cd "\$REPO"
echo "--- pulling latest ---"
sudo git checkout -- .
git pull --ff-only
chmod +x iso/overlay/usr/local/bin/* 2>/dev/null || true

# Kill any previous build session
screen -S bee-build -X quit 2>/dev/null || true

echo "--- starting build in screen session (survives SSH disconnect) ---"
echo "--- log: \$LOG ---"
screen -dmS bee-build sh -c "sh iso/builder/build-in-container.sh ${EXTRA_ARGS} > \$LOG 2>&1; echo \$? > /tmp/bee-build-exit"

# Stream log until build finishes
echo "--- streaming build log (Ctrl+C safe — build continues on VM) ---"
tail -n +1 -f "\$LOG" 2>/dev/null &
TAIL_PID=\$!
while screen -list 2>/dev/null | grep -q bee-build; do
    sleep 2
done
sleep 1
kill \$TAIL_PID 2>/dev/null || true

tail -n 20 "\$LOG" 2>/dev/null || true

EXIT_CODE=\$(cat /tmp/bee-build-exit 2>/dev/null || echo 1)
exit \$EXIT_CODE
ENDSSH

echo ""
echo "=== downloading ISO ==="
LOCAL_ISO_DIR="${REPO_ROOT}/iso/out"
mkdir -p "${LOCAL_ISO_DIR}"
if command -v rsync >/dev/null 2>&1 && ssh -o StrictHostKeyChecking=no "${BUILDER_USER}@${BUILDER_HOST}" command -v rsync >/dev/null 2>&1; then
    rsync -az --progress \
        -e "ssh -o StrictHostKeyChecking=no" \
        "${BUILDER_USER}@${BUILDER_HOST}:/home/${BUILDER_USER}/bee/dist/*.iso" \
        "${LOCAL_ISO_DIR}/"
else
    scp -o StrictHostKeyChecking=no \
        "${BUILDER_USER}@${BUILDER_HOST}:/home/${BUILDER_USER}/bee/dist/*.iso" \
        "${LOCAL_ISO_DIR}/"
fi
echo ""
echo "=== build complete ==="
echo "ISO saved to: ${LOCAL_ISO_DIR}/"
ls -lh "${LOCAL_ISO_DIR}/"*.iso 2>/dev/null || true
