#!/usr/bin/env bash
# Sync portal (file server) content from the repo to the LXC.
# Updates /var/lib/cm4-provisioning/portal-files/ so first-boot and the
# dashboard /files/ serve the same scripts and assets as in the repo.
# Usage: ./sync-portal-files-to-lxc.sh [user@lxc_ip]
# Example: ./sync-portal-files-to-lxc.sh root@10.130.60.141

set -e
LXC="${1:-root@10.130.60.141}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_DIR="$(dirname "$SCRIPT_DIR")"
CLOUDINIT_DIR="$REPO_DIR/cloud-init"
REMOTE_PORTAL="/var/lib/cm4-provisioning/portal-files"
REMOTE_FIRST_BOOT="${REMOTE_PORTAL}/first-boot"

if [[ ! -d "$CLOUDINIT_DIR" ]]; then
  echo "Error: cloud-init dir not found: $CLOUDINIT_DIR"
  exit 1
fi

echo "Syncing portal files to $LXC ($REMOTE_PORTAL) ..."
ssh "$LXC" "command -v rsync >/dev/null 2>&1 || (apt-get update -qq && apt-get install -y rsync)"
ssh "$LXC" "mkdir -p $REMOTE_FIRST_BOOT"

# first-boot.sh at portal root (cloud-init downloads it by URL, not from first-boot/ subfolder)
rsync -avz "$CLOUDINIT_DIR/first-boot.sh" "$LXC:$REMOTE_PORTAL/"

# config-files/* (includes chromium-kiosk.desktop) → portal-files/first-boot/
rsync -avz --exclude='README.md' \
  "$CLOUDINIT_DIR/config-files/" \
  "$LXC:$REMOTE_FIRST_BOOT/"

# start-chromium.sh → portal-files/first-boot/
rsync -avz "$CLOUDINIT_DIR/start-chromium.sh" "$LXC:$REMOTE_FIRST_BOOT/"

# plymouth-custom/* (custom.plymouth, custom.script, splash.png if present) → portal-files/first-boot/
rsync -avz \
  "$CLOUDINIT_DIR/files-from-guard/plymouth-custom/" \
  "$LXC:$REMOTE_FIRST_BOOT/"

# one-shot scripts from cloud-init root → portal-files/first-boot/ (wallpaper set in first-boot via labwc autostart)
rsync -avz \
  "$CLOUDINIT_DIR/set-rotation-once.sh" \
  "$LXC:$REMOTE_FIRST_BOOT/"

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