#!/usr/bin/env bash
# Detect 1Panel App Store MySQL/Redis container names on 1panel-network.
# See: https://github.com/1Panel-dev/1Panel/issues/11676
#      https://github.com/1Panel-dev/appstore (mysql/redis → networks: 1panel-network)

set -euo pipefail

network_container_names() {
    docker network inspect 1panel-network --format '{{range .Containers}}{{.Name}} {{end}}' 2>/dev/null \
        | tr ' ' '\n' | sed '/^$/d'
}

pick_service_container() {
    local kind="$1"
    local names line
    names="$(network_container_names)"
    if [[ -z "$names" ]]; then
        docker ps --format '{{.Names}}' 2>/dev/null | grep -iE "(^1Panel-${kind}-|${kind})" | head -1 || true
        return
    fi
    line="$(echo "$names" | grep -iE "^1Panel-${kind}-" | head -1 || true)"
    if [[ -n "$line" ]]; then
        echo "$line"
        return
    fi
    echo "$names" | grep -i "$kind" | head -1 || true
}

if ! docker network inspect 1panel-network >/dev/null 2>&1; then
    echo "1panel-network not found" >&2
    exit 1
fi

MYSQL_HOST="$(pick_service_container mysql)"
REDIS_HOST="$(pick_service_container redis)"

if [[ -z "$MYSQL_HOST" && -z "$REDIS_HOST" ]]; then
    echo "No MySQL/Redis containers on 1panel-network" >&2
    exit 2
fi

[[ -n "$MYSQL_HOST" ]] && echo "NEXUS_1PANEL_DB_HOST=${MYSQL_HOST}"
[[ -n "$REDIS_HOST" ]] && echo "NEXUS_1PANEL_REDIS_HOST=${REDIS_HOST}"
