#!/usr/bin/env bash
# Revision: 2
# Deploy only the dashboard to the LXC by IP (no Proxmox host needed).
# Uses rsync so all files (app, templates, service file, etc.) stay in sync.
# Usage: ./deploy-dashboard-to-lxc.sh [user@lxc_ip]
# Example: ./deploy-dashboard-to-lxc.sh root@10.130.60.119

set -e
LXC="${1:-root@10.130.60.119}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"
DASHBOARD_DIR="$REPO_DIR/dashboard"
REMOTE_DIR="/opt/cm4-provisioning/dashboard"

if [[ ! -d "$DASHBOARD_DIR" ]]; then
  echo "Error: dashboard dir not found: $DASHBOARD_DIR"
  exit 1
fi

echo "Deploying dashboard to $LXC ($REMOTE_DIR) ..."
# Ensure remote has rsync (Debian/Ubuntu LXC)
ssh "$LXC" "command -v rsync >/dev/null 2>&1 || (apt-get update -qq && apt-get install -y rsync)"

# Sync entire dashboard: app, templates, service file, README, requirements, etc.
rsync -avz --delete \
  --exclude='.git' \
  --exclude='__pycache__' \
  --exclude='*.pyc' \
  --exclude='.env' \
  "$DASHBOARD_DIR/" \
  "$LXC:$REMOTE_DIR/"

echo "Installing systemd unit and restarting ..."
ssh "$LXC" "cp $REMOTE_DIR/cm4-dashboard.service /etc/systemd/system/ && systemctl daemon-reload && systemctl restart cm4-dashboard && systemctl is-active --quiet cm4-dashboard && echo 'Dashboard restarted and running.'"

echo "Done. Dashboard at http://$(echo "$LXC" | cut -d@ -f2):5000"
