#!/usr/bin/env bash
# MySQL + Redis inside WSL (no Docker Desktop). Idempotent.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
MYSQL_PORT="${MYSQL_HOST_PORT:-3307}"
MYSQL_ROOT_PASSWORD="${MYSQL_ROOT_PASSWORD:-changeme}"
MYSQL_DB="chajia"
ACTION="${1:-status}"

log() { echo "[wsl-infra] $*"; }

need_sudo() {
  if ! sudo -n true 2>/dev/null; then
    log "sudo required for first-time setup (install mysql/redis)"
  fi
}

install_deps() {
  need_sudo
  if ! command -v mysql >/dev/null 2>&1; then
    log "installing mysql-server..."
    sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq mysql-server redis-server
  elif ! command -v redis-cli >/dev/null 2>&1; then
    log "installing redis-server..."
    sudo DEBIAN_FRONTEND=noninteractive apt-get update -qq
    sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq redis-server
  fi
}

configure_mysql() {
  need_sudo
  local cnf="/etc/mysql/mysql.conf.d/mysqld.cnf"
  if [ -f "$cnf" ] && ! grep -q "chajia-dev-port" "$cnf" 2>/dev/null; then
    sudo tee -a "$cnf" >/dev/null <<EOF

# chajia-dev-port
port = ${MYSQL_PORT}
bind-address = 0.0.0.0
EOF
  fi
  sudo service mysql restart || sudo systemctl restart mysql || true
}

configure_redis() {
  need_sudo
  local cnf="/etc/redis/redis.conf"
  if [ -f "$cnf" ]; then
    if grep -q '^bind ' "$cnf"; then
      sudo sed -i 's/^bind .*/bind 0.0.0.0 ::1/' "$cnf"
    else
      echo "bind 0.0.0.0 ::1" | sudo tee -a "$cnf" >/dev/null
    fi
    if grep -q '^protected-mode ' "$cnf"; then
      sudo sed -i 's/^protected-mode yes/protected-mode no/' "$cnf"
    fi
  fi
  sudo service redis-server restart || sudo systemctl restart redis-server || true
}

init_db() {
  need_sudo
  sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${MYSQL_ROOT_PASSWORD}'; CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED WITH mysql_native_password BY '${MYSQL_ROOT_PASSWORD}'; GRANT ALL ON *.* TO 'root'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;" 2>/dev/null || true
  mysql -h127.0.0.1 -P"${MYSQL_PORT}" -uroot -p"${MYSQL_ROOT_PASSWORD}" -e "CREATE DATABASE IF NOT EXISTS ${MYSQL_DB};" 2>/dev/null \
    || sudo mysql -h127.0.0.1 -P"${MYSQL_PORT}" -e "CREATE DATABASE IF NOT EXISTS ${MYSQL_DB};" 2>/dev/null \
    || true
}

wait_ports() {
  local i
  for i in $(seq 1 30); do
    if (echo >/dev/tcp/127.0.0.1/"${MYSQL_PORT}") 2>/dev/null && redis-cli ping 2>/dev/null | grep -q PONG; then
      return 0
    fi
    sleep 1
  done
  return 1
}

case "$ACTION" in
  install)
    install_deps
    configure_mysql
    configure_redis
    init_db
    wait_ports && log "install ok" || { log "install finished but ports not ready"; exit 1; }
    ;;
  start)
    configure_mysql
    configure_redis
    wait_ports && log "start ok" || { log "start failed"; exit 1; }
    ;;
  status)
    mysql_ok=0
    redis_ok=0
    (echo >/dev/tcp/127.0.0.1/"${MYSQL_PORT}") 2>/dev/null && mysql_ok=1
    redis-cli ping 2>/dev/null | grep -q PONG && redis_ok=1
    log "mysql:${MYSQL_PORT}=$mysql_ok redis:6379=$redis_ok"
    [ "$mysql_ok" -eq 1 ] && [ "$redis_ok" -eq 1 ]
    ;;
  *)
    echo "usage: $0 {install|start|status}"
    exit 2
    ;;
esac
