#!/usr/bin/env bash
# Grant nexus@'%' on 1Panel App Store MySQL for Docker (1panel-network) install wizard.
# Fixes: Access denied for user 'nexus'@'172.18.x.x' (1045)
#
# Usage:
#   MYSQL_ROOT_PASSWORD='root密码' NEXUS_DB_PASSWORD='nexus密码' bash deploy/fix-1panel-mysql-grant.sh
#   bash deploy/fix-1panel-mysql-grant.sh   # prompts
set -euo pipefail

NEXUS_DB_NAME="${NEXUS_DB_NAME:-nexus}"
NEXUS_DB_USER="${NEXUS_DB_USER:-nexus}"

info() { echo -e "\033[0;32m[INFO]\033[0m  $*"; }
warn() { echo -e "\033[1;33m[WARN]\033[0m  $*"; }
error() { echo -e "\033[0;31m[ERROR]\033[0m $*" >&2; exit 1; }

pick_mysql_container() {
    local name
    if [[ -n "${MYSQL_CONTAINER:-}" ]]; then
        echo "$MYSQL_CONTAINER"
        return 0
    fi
    if docker network inspect 1panel-network >/dev/null 2>&1; then
        name="$(docker network inspect 1panel-network --format '{{range .Containers}}{{.Name}} {{end}}' \
            | tr ' ' '\n' | grep -iE '^1Panel-mysql-' | head -1 || true)"
        [[ -n "$name" ]] && echo "$name" && return 0
    fi
    name="$(docker ps --format '{{.Names}}' | grep -iE '^1Panel-mysql-' | head -1 || true)"
    [[ -n "$name" ]] && echo "$name" && return 0
    error "未找到 1Panel MySQL 容器（可设 MYSQL_CONTAINER=名称）"
}

prompt_secret() {
    local var="$1" prompt="$2"
    if [[ -n "${!var:-}" ]]; then
        return 0
    fi
    read -r -s -p "$prompt: " "$var"
    echo ""
    if [[ -z "${!var:-}" ]]; then
        error "$var 不能为空"
    fi
}

main() {
    [[ "${EUID:-$(id -u)}" -eq 0 ]] || error "请用 root 运行"

    local mysql_c
    mysql_c="$(pick_mysql_container)"
    info "MySQL 容器: $mysql_c"

    prompt_secret MYSQL_ROOT_PASSWORD "1Panel MySQL root 密码"
    prompt_secret NEXUS_DB_PASSWORD "nexus 用户密码（与安装向导步骤 3 一致）"

    info "创建库/用户并授权 ${NEXUS_DB_USER}@'%' → ${NEXUS_DB_NAME}.* ..."

    docker exec -i "$mysql_c" mysql -uroot -p"${MYSQL_ROOT_PASSWORD}" <<SQL
CREATE DATABASE IF NOT EXISTS \`${NEXUS_DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER IF NOT EXISTS '${NEXUS_DB_USER}'@'%' IDENTIFIED BY '${NEXUS_DB_PASSWORD}';
ALTER USER '${NEXUS_DB_USER}'@'%' IDENTIFIED BY '${NEXUS_DB_PASSWORD}';
GRANT ALL PRIVILEGES ON \`${NEXUS_DB_NAME}\`.* TO '${NEXUS_DB_USER}'@'%';
FLUSH PRIVILEGES;
SELECT user, host FROM mysql.user WHERE user = '${NEXUS_DB_USER}';
SQL

    info "完成。请在安装向导步骤 3 使用: 库/用户=${NEXUS_DB_NAME}/${NEXUS_DB_USER}，密码与上面一致"
    info "若已改 install.py，执行: bash deploy/sync-install-wizard-to-container.sh"
}

main "$@"
