#!/bin/bash
# Install/refresh the systemd services for Qwen-Image-Edit on THIS host.
# Host-agnostic: the service user, group and install path are derived at run
# time, so the same file works on tour, hubby, etc.
#
# Run with sudo (needs to write /etc/systemd/system). Assumes bootstrap.sh has
# already created venv/, ComfyUI/ and the models under BASE.
set -e

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root (use sudo)"
   exit 1
fi

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"   # .../comfyui/api
BASE="$( cd "$SCRIPT_DIR/.." && pwd )"                          # .../comfyui
TEMPLATES="$SCRIPT_DIR/systemd"

# The service should run as the owner of the project, not root.
SVC_USER="${SUDO_USER:-$(stat -c '%U' "$SCRIPT_DIR")}"
SVC_GROUP="$(id -gn "$SVC_USER")"

echo "Installing services:  user=$SVC_USER  group=$SVC_GROUP  base=$BASE"

for unit in comfyui-backend comfyui-api; do
  sed -e "s|__USER__|$SVC_USER|g" \
      -e "s|__GROUP__|$SVC_GROUP|g" \
      -e "s|__BASE__|$BASE|g" \
      "$TEMPLATES/$unit.service" > "/etc/systemd/system/$unit.service"
  echo "  wrote /etc/systemd/system/$unit.service"
done

echo "Reloading systemd daemon..."
systemctl daemon-reload

echo "Enabling + (re)starting services..."
systemctl enable comfyui-backend.service comfyui-api.service
systemctl restart comfyui-backend.service comfyui-api.service

echo "Deployment complete."
echo "Check status with: systemctl status comfyui-backend comfyui-api"
