#!/bin/bash

function raise_error() {
	echo "$1"
	exit 1
}

if [ -z "$VIRTUAL_ENV" ]; then
	. venv/bin/activate || raise_error "no venv"
fi

#conda install pytorch torchvision torchaudio pytorch-cuda=12.1 -c pytorch -c nvidia

# https://pytorch.org/get-started/locally/
## torchaudio 패키지만 추가함
#pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu129
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu130

SCRIPT_PATH=$(readlink -f "$0")
SCRIPT_DIR=$(dirname $SCRIPT_PATH)

cd "$SCRIPT_DIR"

if [ ! -d workspace ]; then
	git clone https://github.com/comfyanonymous/ComfyUI.git workspace || raise_error "install_error"
        cd workspace
        mkdir -p custom_nodes

        cd custom_nodes
	git clone https://github.com/Comfy-Org/ComfyUI-Manager.git
else
	cd workspace
	git pull || raise_error "git pull error ComfyUI"
	pip install --upgrade -r requirements.txt || raise_error "upgrade error"

        cd custom_nodes || raise_error "Not Exists custom_nodes dir"
	cd ComfyUI-Manager || raise_error "Not Exists ComfyUI-Manager"
	git pull || raise_error "git pull error: ComfyUI-Manager"
fi

#if [[ "$0" == *"bash"* ]]; then
#        echo "Cannot run with \`source\`"
#        return 1
#fi

cd "$SCRIPT_DIR" || raise_error "not exists workspace dir"
if [ -n "$SUDO_USER" ]; then
  USERNAME=$SUDO_USER
else
  USERNAME=$USER
fi

# <<- EOF: 선행탭이 제거되는 heredoc, sed 앞뒤 공백 제거
sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<- EOF > comfyui.service
        [Unit]
        Description=ComfyUI Service
        After=network.target

        [Service]
        Type=simple
        User=$USERNAME
        WorkingDirectory=$SCRIPT_DIR
        ExecStart=$VIRTUAL_ENV/bin/python3 $SCRIPT_DIR/workspace/main.py --multi-user --listen 0.0.0.0
        Restart=always
        RestartSec=3

        [Install]
        WantedBy=multi-user.target
EOF

cd "$SCRIPT_DIR"/workspace || raise_error "not exists workspace dir"
pip install --upgrade pip wheel setuptools
pip install -r requirements.txt
curl -O "https://cdn.gyuri.net/shell-script/ai/comfyui/python3/download_templates_model.py"
curl -O "https://cdn.gyuri.net/shell-script/ai/comfyui/python3/support_lib.py"

sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<- EOF
  $ cd "$SCRIPT_DIR"
  $ sudo cp comfyui.service /etc/systemd/system/
  $ sudo systemctl daemon-reload
  $ sudo systemctl enable comfyui.service
  $ sudo systemctl start comfyui.service
  $ sudo systemctl status comfyui.service
EOF

echo "usage See: https://cdn.gyuri.net/shell-script/ai/comfyui/usage.html"

