#!/bin/bash

OLLAMA_MODEL="deepseek-r1:70b"
OPENWEBUI_PORT=8080
VENV_DIR="/opt/open-webui/venv"
APP_DIR="/opt/open-webui"
LOCK_FILE="/var/lib/dpkg/lock-frontend"
LOCK_FILE2="/var/lib/apt/lists/lock"
MAX_WAIT=300
WAIT_INTERVAL=10
ELAPSED=0

export HOME=/root
export USER=root
export DEBIAN_FRONTEND=noninteractive
export NEEDRESTART_MODE=a

if systemctl is-active --quiet unattended-upgrades; then
    systemctl stop unattended-upgrades
fi

while fuser $LOCK_FILE $LOCK_FILE2 >/dev/null 2>&1; do
    sleep $WAIT_INTERVAL
    ELAPSED=$((ELAPSED + WAIT_INTERVAL))

    if [ $ELAPSED -ge $MAX_WAIT ]; then
        PIDS=$(fuser $LOCK_FILE $LOCK_FILE2 2>/dev/null)
	if [ -n "$PIDS" ]; then
	    kill -9 $PIDS
	fi
	dpkg --configure -a
	break
    fi
done
apt-get update
apt-get install -y curl python3 python3-venv python3-pip

if ! command -v ollama &>/dev/null; then
    curl -fsSL https://ollama.com/install.sh | sh
else
    echo "Ollama Installed"
fi
systemctl enable ollama
systemctl restart ollama
until curl -fsS http://127.0.0.1:11434/api/tags >/dev/null 2>&1; do
    echo "Waiting Ollama start..."
    sleep 2
done
echo "Ollama API Working"

ollama pull "$OLLAMA_MODEL"

mkdir -p "$APP_DIR"
if [ ! -d "$VENV_DIR" ]; then
    python3 -m venv "$VENV_DIR"
fi

"$VENV_DIR/bin/pip" install --upgrade pip
"$VENV_DIR/bin/pip" install open-webui

mkdir -p /root/.open-webui
cat >/root/.open-webui/config.json <<EOF
{
  "OLLAMA_BASE_URL": "http://127.0.0.1:11434",
  "DEFAULT_MODEL": "$OLLAMA_MODEL"
}
EOF

cat >/etc/systemd/system/open-webui.service <<EOF
[Unit]
Description=Open WebUI Service
After=network.target ollama.service

[Service]
Type=simple
User=root
WorkingDirectory=$APP_DIR
ExecStart=$VENV_DIR/bin/open-webui serve --host 0.0.0.0 --port $OPENWEBUI_PORT 
Restart=always
StandardOutput=append:/var/log/open-webui.log
StandardError=append:/var/log/open-webui.log

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable open-webui
systemctl restart open-webui
