#!/bin/bash

# 1. Install anaconda3
curl -o /opt/Anaconda3-2025.06-0-Linux-x86_64.sh https://repo.anaconda.com/archive/Anaconda3-2025.06-0-Linux-x86_64.sh
bash /opt/Anaconda3-2025.06-0-Linux-x86_64.sh -b -p "/opt/anaconda3"

# 2. Configure conda channels and create environment
/opt/anaconda3/bin/conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/main
/opt/anaconda3/bin/conda tos accept --override-channels --channel https://repo.anaconda.com/pkgs/r
/opt/anaconda3/bin/conda create -n comfyenv python=3.12 -y

# 3. Activate environment and install dependencies
source /opt/anaconda3/bin/activate comfyenv
conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia -y

# 4. Install ComfyUI
git clone --branch v0.3.56 --single-branch https://github.com/comfyanonymous/ComfyUI.git /opt/ComfyUI
/opt/anaconda3/envs/comfyenv/bin/pip3 install -r /opt/ComfyUI/requirements.txt

# 5. Install custom nodes
git clone --branch 3.33.5 --single-branch https://github.com/Comfy-Org/ComfyUI-Manager.git /opt/ComfyUI/custom_nodes/comfyui-manager
git clone https://github.com/liusida/ComfyUI-Login.git /opt/ComfyUI/custom_nodes/ComfyUI-Login
/opt/anaconda3/envs/comfyenv/bin/pip3 install -r /opt/ComfyUI/custom_nodes/ComfyUI-Login/requirements.txt

wget -q https://huggingface.co/Comfy-Org/stable-diffusion-v1-5-archive/resolve/main/v1-5-pruned-emaonly-fp16.safetensors?download=true -O /opt/ComfyUI/models/checkpoints/v1-5-pruned-emaonly-fp16.safetensors

# 6. Create systemd service
SERVICE_FILE="/etc/systemd/system/comfyui.service"

cat > $SERVICE_FILE <<EOF
[Unit]
Description=ComfyUI Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/ComfyUI
ExecStart=/opt/anaconda3/envs/comfyenv/bin/python /opt/ComfyUI/main.py --listen 0.0.0.0 --port 8188
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable comfyui
systemctl start comfyui

# 7. Check if port 8188 is listening
PORT=8188
TIMEOUT=600
INTERVAL=10
ELAPSED=0

echo "Checking if port $PORT is listening (timeout: $TIMEOUT seconds)..."

while [ $ELAPSED -lt $TIMEOUT ]; do
    if ss -tulnp | grep -q ":$PORT"; then
        echo "Port $PORT is listening (after ${ELAPSED}s)"
        ss -tulnp | grep ":$PORT"
        exit 0
    fi
    sleep $INTERVAL
    ELAPSED=$((ELAPSED + INTERVAL))
    echo "Waited ${ELAPSED}s..."
done

echo "Port $PORT did not start listening within $TIMEOUT seconds, exiting"
exit 1
