#!/bin/bash
# Install/refresh systemd services for Qwen-Image-Edit on the A6000 (CUDA) box.
# Installs 3 services + 1 target; run with sudo.
set -e

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

A6K="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"   # a6000-comfy/
REPO="$( cd "$A6K/.." && pwd )"                            # repo root
TOUR="$REPO/tour-comfy"
TEMPLATES="$A6K/systemd"

SVC_USER="${SUDO_USER:-$(stat -c '%U' "$A6K")}"
SVC_GROUP="$(id -gn "$SVC_USER")"

echo "Installing services:  user=$SVC_USER  group=$SVC_GROUP"
echo "  a6k=$A6K"
echo "  tour=$TOUR"

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

cp "$TEMPLATES/comfyui.target" /etc/systemd/system/comfyui.target
echo "  wrote /etc/systemd/system/comfyui.target"

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

echo "Enabling services + target..."
systemctl enable comfyui-backend.service comfyui-api.service comfyui-watcher.service comfyui.target

echo "Starting system..."
systemctl start comfyui.target

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