#!/bin/sh
# start/stop/status the managed containers (db -> companion -> invidious -> ui).
# 'start' waits for the Docker daemon and retries — at DSM boot the package
# service can start before Docker is ready, which previously left apps down
# until the next manual start.
CONTAINERS="kvtube-db kvtube-companion kvtube-invidious kvtube-ui"
DOCKER="${SYNOPKG_PKGDEST}/tool/kv-helper"
PIDFILE="${SYNOPKG_PKGVAR:-/var/packages/kvtube/var}/deploy.pid"

wait_docker() {
    i=0
    while [ "$i" -lt 30 ]; do
        "${DOCKER}" version >/dev/null 2>&1 && return 0
        i=$((i + 1))
        sleep 3
    done
    return 1
}

ui_is_up() {
    "${DOCKER}" inspect kvtube-ui 2>/dev/null | grep -q '"Status": "running"'
}

is_deploying() {
    if [ -f "${PIDFILE}" ]; then
        PID="$(cat "${PIDFILE}" 2>/dev/null)"
        if [ -n "$PID" ] && kill -0 "$PID" 2>/dev/null; then
            return 0
        fi
    fi
    return 1
}

case "$1" in
    start)
        wait_docker || { echo "start-stop-status: Docker not ready" >&2; exit 1; }
        if is_deploying; then
            exit 0
        fi

        # If UI container doesn't exist yet, trigger deployment in background
        if ! "${DOCKER}" inspect kvtube-ui >/dev/null 2>&1; then
            echo "start-stop-status: kvtube-ui container not found, triggering deploy..."
            nohup sh -c ". '${SYNOPKG_PKGDEST}/lib/pkg-lib.sh'; deploy_containers; rm -f '${PIDFILE}'" >> /tmp/kvtube-install.log 2>&1 </dev/null &
            echo "$!" > "${PIDFILE}"
            exit 0
        fi

        for c in ${CONTAINERS}; do
            if "${DOCKER}" inspect "${c}" >/dev/null 2>&1; then
                "${DOCKER}" start "${c}" >/dev/null 2>&1 || true
            fi
        done

        # Wait up to 30 s for the UI container to reach "running".
        i=0
        while [ "$i" -lt 30 ]; do
            ui_is_up && exit 0
            is_deploying && exit 0
            i=$((i + 1))
            sleep 1
        done
        ui_is_up && exit 0
        is_deploying && exit 0
        echo "start-stop-status: UI container not running after 30 s" >&2
        exit 1
        ;;
    stop)
        if [ -f "${PIDFILE}" ]; then
            PID="$(cat "${PIDFILE}" 2>/dev/null)"
            [ -n "$PID" ] && kill "$PID" 2>/dev/null || true
            rm -f "${PIDFILE}"
        fi
        wait_docker || exit 0
        for c in kvtube-ui kvtube-invidious kvtube-companion kvtube-db; do
            "${DOCKER}" stop "${c}" >/dev/null 2>&1 || true
        done
        ;;
    status)
        if ui_is_up; then
            exit 0
        fi
        if is_deploying; then
            exit 0
        fi
        exit 1
        ;;
    log)
        ;;
    *)
        echo "Usage: $0 {start|stop|status}" >&2
        exit 1
        ;;
esac
exit 0