#!/bin/sh
# QPKG install/remove hooks

CONF=/etc/config/qpkg.conf
QPKG_NAME="mcp-server-qnap-qvs"

pkg_pre_install() {
    CS_DIR=$(getcfg container-station Install_Path -f $CONF 2>/dev/null)
    if [ -z "$CS_DIR" ] || [ ! -x "${CS_DIR}/bin/docker" ]; then
        echo "ERROR: Container Station with Docker is required."
        echo "Install Container Station from the QNAP App Center first."
        return 1
    fi
}

pkg_post_install() {
    QPKG_DIR=$(getcfg $QPKG_NAME Install_Path -f $CONF)

    if [ ! -f "${QPKG_DIR}/.env" ]; then
        cp "${QPKG_DIR}/.env.example" "${QPKG_DIR}/.env"
        echo "Created ${QPKG_DIR}/.env — please edit with your QNAP credentials."
    fi

    chmod +x "${QPKG_DIR}/mcp-server-qnap-qvs.sh"

    CS_DIR=$(getcfg container-station Install_Path -f $CONF)
    "${CS_DIR}/bin/docker" pull ghcr.io/arnstarn/mcp-server-qnap-qvs:latest 2>/dev/null
}

pkg_pre_remove() {
    QPKG_DIR=$(getcfg $QPKG_NAME Install_Path -f $CONF)
    CS_DIR=$(getcfg container-station Install_Path -f $CONF)
    cd "${QPKG_DIR}" && "${CS_DIR}/bin/docker" compose down 2>/dev/null
}
