#!/bin/bash

# ============================================================
# Docker PHP 7.2 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="php:7.2-fpm"
CONTAINER_NAME="php72"
DATA_DIR="/data/php7.2"
FPM_PORT="9000"

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_php72_base_docker.sh [options]

Options:
  --data-dir PATH           Host directory to mount (default: /data/php7.2)
  --container-name NAME     Docker container name (default: php72)
  --port PORT               Host port mapped to PHP-FPM 9000 (default: 9000)
  -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
      ;;
    --port)
      FPM_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}/www" "${DATA_DIR}/conf.d" "${DATA_DIR}/logs"

if [ ! -f "${DATA_DIR}/conf.d/php.ini" ]; then
  info "Writing baseline PHP config to ${DATA_DIR}/conf.d/php.ini"
  cat > "${DATA_DIR}/conf.d/php.ini" <<'EOF'
date.timezone = Asia/Shanghai
memory_limit = 256M
upload_max_filesize = 50M
post_max_size = 50M
max_execution_time = 120
display_errors = Off
log_errors = On
error_log = /var/log/php/php-error.log
EOF
fi

if [ ! -f "${DATA_DIR}/www/index.php" ]; then
  info "Writing placeholder PHP page to ${DATA_DIR}/www/index.php"
  cat > "${DATA_DIR}/www/index.php" <<'EOF'
<?php
header('Content-Type: text/plain; charset=utf-8');
echo "PHP 7.2 container is running\n";
echo "Published by helper.sh/install_php72_base_docker.sh\n";
echo "Mounted app root: /data/php7.2/www\n";
echo "Current PHP version: " . PHP_VERSION . "\n";
EOF
fi

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 "Pulling ${IMAGE} ..."
docker pull "${IMAGE}"

info "Starting ${CONTAINER_NAME} ..."
docker run -d \
  --name "${CONTAINER_NAME}" \
  --restart unless-stopped \
  -p "${FPM_PORT}:9000" \
  -v "${DATA_DIR}/www:/var/www/html" \
  -v "${DATA_DIR}/conf.d:/usr/local/etc/php/conf.d" \
  -v "${DATA_DIR}/logs:/var/log/php" \
  "${IMAGE}" >/dev/null

PHP_READY="0"
for _ in $(seq 1 20); do
  if docker exec "${CONTAINER_NAME}" php -v >/dev/null 2>&1; then
    PHP_READY="1"
    break
  fi
  sleep 2
done

if [ "${PHP_READY}" = "1" ]; then
  success "PHP health check passed"
else
  warning "Container started, but PHP is not responding yet. Check docker logs -f ${CONTAINER_NAME}"
fi

echo ""
echo -e "${GREEN}============================================================${NC}"
echo -e "${GREEN} PHP 7.2 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}PHP-FPM port:${NC}     ${FPM_PORT}"
echo -e "  ${BLUE}Mounted data dir:${NC} ${DATA_DIR}"
echo ""
echo -e "  ${YELLOW}Editable host paths:${NC}"
echo -e "    ${DATA_DIR}/www/index.php"
echo -e "    ${DATA_DIR}/conf.d/php.ini"
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} php -v"
echo -e "    docker exec -it ${CONTAINER_NAME} php -m"
echo ""
