#!/usr/bin/env bash
# Run this script inside a freshly created Proxmox LXC container
# (Debian 12 or Ubuntu 22.04/24.04) to install and configure the
# ThermoPro CYD frontend.

set -euo pipefail

INSTALL_DIR="/opt/thermopro-frontend"
DATA_DIR="/data"
SERVICE_NAME="thermopro-frontend"

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root (e.g. inside the LXC container)" >&2
   exit 1
fi

echo "=== Updating packages ==="
apt-get update
apt-get upgrade -y

echo "=== Installing Python tooling ==="
apt-get install -y python3 python3-pip git curl

echo "=== Creating application user ==="
useradd -r -s /bin/false -d "${INSTALL_DIR}" thermopro || true

echo "=== Creating data directory ==="
mkdir -p "${DATA_DIR}"
chown thermopro:thermopro "${DATA_DIR}"

if [[ ! -d "${INSTALL_DIR}" ]]; then
    echo "ERROR: ${INSTALL_DIR} does not exist."
    echo "Copy the frontend/ folder into the container at ${INSTALL_DIR} first."
    echo "Example from Proxmox host:"
    echo "  pct push <ctid> /path/to/frontend.tar.gz /tmp/frontend.tar.gz"
    echo "  pct exec <ctid> -- tar -xzf /tmp/frontend.tar.gz -C /opt"
    exit 1
fi

cd "${INSTALL_DIR}"

echo "=== Installing Python dependencies into vendor/ ==="
pip3 install --target vendor --upgrade -r requirements.txt

echo "=== Setting ownership ==="
chown -R thermopro:thermopro "${INSTALL_DIR}"

echo "=== Installing systemd service ==="
cp "${INSTALL_DIR}/deploy/thermopro-frontend.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable "${SERVICE_NAME}"
systemctl start "${SERVICE_NAME}"

echo "=== Waiting for service to start ==="
sleep 2
systemctl status "${SERVICE_NAME}" --no-pager

echo ""
echo "=== Installation complete ==="
echo "The frontend should now be running on http://<container-ip>:5000"
echo ""
echo "To check logs:   journalctl -u ${SERVICE_NAME} -f"
echo "To edit config: nano /etc/systemd/system/${SERVICE_NAME}.service"
echo "Then reload:    systemctl daemon-reload && systemctl restart ${SERVICE_NAME}"
