#!/bin/sh
# start/stop/status the managed container.
# '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.
CONTAINER="kvmusic"
DOCKER="${SYNOPKG_PKGDEST}/tool/kv-helper"

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
}

case "$1" in
    start)
        wait_docker || { echo "start-stop-status: Docker not ready" >&2; exit 1; }
        i=0
        while [ "$i" -lt 10 ]; do
            if "${DOCKER}" inspect "${CONTAINER}" >/dev/null 2>&1; then
                "${DOCKER}" start "${CONTAINER}" >/dev/null 2>&1 && break
            else
                # container missing (e.g. first boot after install raced) —
                # nothing to start; setup runs from postinst/postupgrade
                break
            fi
            i=$((i + 1))
            sleep 2
        done
        # verify it is actually running
        "${DOCKER}" inspect "${CONTAINER}" 2>/dev/null | grep -q '"Status": "running"' && exit 0
        echo "start-stop-status: container not running after retries" >&2
        exit 1
        ;;
    stop)
        wait_docker || exit 0
        "${DOCKER}" stop "${CONTAINER}" >/dev/null 2>&1 || true
        ;;
    status)
        "${DOCKER}" inspect "${CONTAINER}" 2>/dev/null | grep -q '"Status": "running"' || exit 1
        ;;
    log)
        ;;
    *)
        echo "Usage: $0 {start|stop|status}" >&2
        exit 1
        ;;
esac
exit 0
