#!/bin/bash

# ============================================================
# Docker Nginx 1.22.1 one-shot installer
# Published by: helper.sh
# Script note: generated with Claude and curated by helper.sh
# ============================================================

set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

IMAGE="nginx:1.22.1"
CONTAINER_NAME="nginx-1221"
DATA_DIR="/data/nginx"
HTTP_PORT="80"
HTTPS_PORT="443"

info()    { echo -e "${BLUE}[INFO]${NC}  $1"; }
success() { echo -e "${GREEN}[OK]${NC}    $1"; }
warning() { echo -e "${YELLOW}[WARN]${NC}  $1"; }
error()   { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

usage() {
  cat <<'EOF'
Usage: install_nginx_base_docker.sh [options]

Options:
  --data-dir PATH         Host directory to mount (default: /data/nginx)
  --container-name NAME   Docker container name (default: nginx-1221)
  --http-port PORT        Host port mapped to container 80 (default: 80)
  --https-port PORT       Host port mapped to container 443 (default: 443)
  -h, --help              Show this help message
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --data-dir)
      DATA_DIR="$2"
      shift 2
      ;;
    --container-name)
      CONTAINER_NAME="$2"
      shift 2
      ;;
    --http-port)
      HTTP_PORT="$2"
      shift 2
      ;;
    --https-port)
      HTTPS_PORT="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      error "Unknown argument: $1"
      ;;
  esac
done

if [ "${EUID}" -ne 0 ]; then
  error "Run this script with root privileges: sudo bash $0"
fi

if ! command -v docker >/dev/null 2>&1; then
  error "Docker is not installed. Install Docker first with helper.sh/install_docker_ubuntu_2404.sh"
fi

if ! systemctl is-active --quiet docker; then
  info "Docker service is not running. Starting Docker..."
  systemctl start docker
fi

mkdir -p "${DATA_DIR}/html" "${DATA_DIR}/conf.d" "${DATA_DIR}/logs"

if [ ! -f "${DATA_DIR}/nginx.conf" ]; then
  info "Writing baseline nginx.conf to ${DATA_DIR}/nginx.conf"
  cat > "${DATA_DIR}/nginx.conf" <<'EOF'
user nginx;
worker_processes auto;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
  worker_connections 1024;
}

http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

  access_log /var/log/nginx/access.log main;

  sendfile on;
  tcp_nopush on;
  keepalive_timeout 65;
  types_hash_max_size 4096;

  include /etc/nginx/conf.d/*.conf;
}
EOF
fi

if [ ! -f "${DATA_DIR}/conf.d/default.conf" ]; then
  info "Writing default server block to ${DATA_DIR}/conf.d/default.conf"
  cat > "${DATA_DIR}/conf.d/default.conf" <<'EOF'
server {
  listen 80;
  server_name _;

  root /usr/share/nginx/html;
  index index.html;

  location = /healthz {
    default_type text/plain;
    return 200 'ok';
  }

  location / {
    try_files $uri $uri/ =404;
  }
}
EOF
fi

if [ ! -f "${DATA_DIR}/html/index.html" ]; then
  info "Writing placeholder index page to ${DATA_DIR}/html/index.html"
  cat > "${DATA_DIR}/html/index.html" <<'EOF'
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>helper.sh nginx</title>
    <style>
      body {
        margin: 0;
        min-height: 100vh;
        display: grid;
        place-items: center;
        background: #0f172a;
        color: #e2e8f0;
        font: 16px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
      }
      main {
        max-width: 720px;
        padding: 32px;
      }
      h1 { margin: 0 0 12px; }
      p { margin: 0 0 10px; color: #cbd5e1; }
      code { color: #67e8f9; }
    </style>
  </head>
  <body>
    <main>
      <h1>Nginx 1.22.1 is running</h1>
      <p>This page was created by <code>helper.sh/install_nginx_base_docker.sh</code>.</p>
      <p>Edit <code>/data/nginx/html</code> and <code>/data/nginx/conf.d</code> on the host to customize the service.</p>
    </main>
  </body>
</html>
EOF
fi

info "Pulling ${IMAGE} ..."
docker pull "${IMAGE}"

if docker ps -a --format '{{.Names}}' | grep -Fx "${CONTAINER_NAME}" >/dev/null 2>&1; then
  warning "Container ${CONTAINER_NAME} already exists. Recreating it with the current mount layout."
  docker rm -f "${CONTAINER_NAME}" >/dev/null
fi

info "Starting ${CONTAINER_NAME} ..."
docker run -d \
  --name "${CONTAINER_NAME}" \
  --restart unless-stopped \
  -p "${HTTP_PORT}:80" \
  -p "${HTTPS_PORT}:443" \
  -v "${DATA_DIR}/nginx.conf:/etc/nginx/nginx.conf:ro" \
  -v "${DATA_DIR}/conf.d:/etc/nginx/conf.d:ro" \
  -v "${DATA_DIR}/html:/usr/share/nginx/html:ro" \
  -v "${DATA_DIR}/logs:/var/log/nginx" \
  "${IMAGE}" >/dev/null

if command -v curl >/dev/null 2>&1; then
  if curl -fsS --connect-timeout 3 --max-time 10 "http://127.0.0.1:${HTTP_PORT}/healthz" >/dev/null 2>&1; then
    success "Local health check passed"
  else
    warning "Container started, but /healthz is not responding yet"
  fi
else
  warning "curl is not installed, skipping local HTTP health check"
fi

echo ""
echo -e "${GREEN}============================================================${NC}"
echo -e "${GREEN} Nginx container deployment completed                        ${NC}"
echo -e "${GREEN}============================================================${NC}"
echo ""
echo -e "  ${BLUE}Image:${NC}            ${IMAGE}"
echo -e "  ${BLUE}Container:${NC}        ${CONTAINER_NAME}"
echo -e "  ${BLUE}HTTP port:${NC}        ${HTTP_PORT}"
echo -e "  ${BLUE}HTTPS port:${NC}       ${HTTPS_PORT}"
echo -e "  ${BLUE}Mounted data dir:${NC} ${DATA_DIR}"
echo ""
echo -e "  ${YELLOW}Editable host paths:${NC}"
echo -e "    ${DATA_DIR}/nginx.conf"
echo -e "    ${DATA_DIR}/conf.d/default.conf"
echo -e "    ${DATA_DIR}/html/index.html"
echo -e "    ${DATA_DIR}/logs/"
echo ""
echo -e "  ${YELLOW}Useful commands:${NC}"
echo -e "    docker ps"
echo -e "    docker logs -f ${CONTAINER_NAME}"
echo -e "    docker exec -it ${CONTAINER_NAME} nginx -t"
echo -e "    docker exec -it ${CONTAINER_NAME} nginx -s reload"
echo ""
