#!/usr/bin/env bash
# Nginx · 第 02 章 · 一键体验脚本
# 用法：bash commands.sh up      启动
#       bash commands.sh down    停止
#       bash commands.sh logs    跟踪日志
#       bash commands.sh test    nginx -t 测试配置语法
#       bash commands.sh reload  reload 配置（不断连）

set -euo pipefail

CONTAINER=nginx-learn
IMAGE=nginx:1.25-alpine
PORT=${PORT:-8080}
ROOT=$(cd "$(dirname "$0")" && pwd)

cmd_up() {
  mkdir -p "$ROOT/html" "$ROOT/conf" "$ROOT/logs"
  if [ ! -f "$ROOT/html/index.html" ]; then
    cat > "$ROOT/html/index.html" <<'EOF'
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>Hello Nginx</title></head>
<body style="font-family:sans-serif;text-align:center;padding:40px;">
  <h1>👋 Hello Nginx</h1>
  <p>第一份属于你的网页 · 来自 Nginx 学习笔记</p>
</body>
</html>
EOF
  fi
  if [ ! -f "$ROOT/conf/default.conf" ]; then
    cp "$ROOT/default.conf" "$ROOT/conf/default.conf"
  fi

  docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
  docker run -d \
    --name "$CONTAINER" \
    -p "${PORT}:80" \
    -v "$ROOT/html:/usr/share/nginx/html:ro" \
    -v "$ROOT/conf/default.conf:/etc/nginx/conf.d/default.conf:ro" \
    -v "$ROOT/logs:/var/log/nginx" \
    "$IMAGE" >/dev/null

  echo "✅ Nginx 已启动 → http://localhost:${PORT}"
  echo "    健康检查 → http://localhost:${PORT}/healthz"
}

cmd_down() {
  docker rm -f "$CONTAINER" >/dev/null 2>&1 || true
  echo "🛑 已停止并移除容器 $CONTAINER"
}

cmd_logs()   { docker logs -f "$CONTAINER"; }
cmd_test()   { docker exec "$CONTAINER" nginx -t; }
cmd_reload() { docker exec "$CONTAINER" nginx -s reload && echo "🔁 Reload 完成"; }
cmd_shell()  { docker exec -it "$CONTAINER" sh; }

case "${1:-}" in
  up)     cmd_up ;;
  down)   cmd_down ;;
  logs)   cmd_logs ;;
  test)   cmd_test ;;
  reload) cmd_reload ;;
  shell)  cmd_shell ;;
  *)
    echo "Usage: $0 {up|down|logs|test|reload|shell}" ;;
esac
