#!/usr/bin/env bash
set -euo pipefail

ROLE="${ROLE:-app}"
PHASE="${PHASE:-environment}"

if [ "$ROLE" != "app" ] && [ "$ROLE" != "db" ]; then
    echo "ROLE must be app or db." >&2
    exit 2
fi

if [ "$PHASE" != "environment" ] && [ "$PHASE" != "project" ]; then
    echo "PHASE must be environment or project." >&2
    exit 2
fi

echo "## Sifangda identifiers"
printf 'main_business=%s\n' 'zhct_sfd'
printf 'ai_business=%s\n' 'aizhct_sfd'

if [ "$ROLE" = "db" ]; then
    echo
    echo "## Database configuration scan"
    test -f /etc/my.cnf
    if grep -nE '__SFD_[A-Z0-9_]+__' /etc/my.cnf; then
        echo "Unresolved Sifangda placeholders found in /etc/my.cnf." >&2
        exit 1
    fi
    if grep -nE 'zhct_bzjk|aizhct_bzjk|bziht|10\.10\.12\.|yyangpt|kxunpt' /etc/my.cnf; then
        echo "Cross-customer residue found in /etc/my.cnf." >&2
        exit 1
    fi
    echo
    echo "## MySQL 5.6"
    mysql_version="$(mysql --version)"
    printf '%s\n' "$mysql_version"
    if ! printf '%s\n' "$mysql_version" | grep -Eq 'Distrib 5\.6\.|Ver 14\.14 Distrib 5\.6\.'; then
        echo "MySQL 5.6 is required." >&2
        exit 1
    fi
    grep -E '^(bind-address|character-set-server|collation-server|sql-mode)=' /etc/my.cnf
    ss -lntp | grep -E ':3306\b' || true
    test "$(systemctl is-active mysql)" = "active"
    test "$(systemctl is-enabled mysql)" = "enabled"
    systemctl status mysql --no-pager
    exit 0
fi

echo
echo "## Placeholder scan"
placeholder_targets=(
    /usr/local/nginx/conf/vhost/zhct_sfd.conf
    /usr/local/nginx/conf/vhost/aizhct_sfd.conf
    /etc/redis.conf
)
if [ "$PHASE" = "project" ]; then
    placeholder_targets+=(
        /workspace/wwwroot/zhct_sfd/project/application/config/prod/zhct_sfd
        /workspace/wwwroot/aizhct_sfd/project/.env.prodaizhct_sfd
    )
fi
for required_target in "${placeholder_targets[@]}"; do
    if [ ! -e "$required_target" ]; then
        echo "Required Sifangda configuration is missing: $required_target" >&2
        exit 1
    fi
done
if grep -RInE '__SFD_[A-Z0-9_]+__' "${placeholder_targets[@]}" 2>/dev/null; then
    echo "Unresolved Sifangda placeholders found." >&2
    exit 1
else
    echo "No unresolved placeholders found in installed Sifangda configuration."
fi

echo
echo "## Cross-customer residue scan"
residue_targets=(
    /usr/local/nginx/conf/vhost/zhct_sfd.conf
    /usr/local/nginx/conf/vhost/aizhct_sfd.conf
)
if [ "$PHASE" = "project" ]; then
    residue_targets+=(
        /etc/supervisor/conf.d
        /workspace/wwwroot/zhct_sfd/project/application/config/prod/zhct_sfd
        /workspace/wwwroot/aizhct_sfd/project/.env.prodaizhct_sfd
    )
fi
if grep -RInE 'zhct_bzjk|aizhct_bzjk|bziht|10\.10\.12\.|yyangpt|kxunpt' \
    "${residue_targets[@]}" 2>/dev/null; then
    echo "Cross-customer residue found." >&2
    exit 1
else
    echo "No Binzhou/customer residue found in Sifangda configuration."
fi

echo
echo "## Nginx"
/usr/local/nginx/sbin/nginx -t

echo
echo "## PHP runtimes"
test -s /usr/local/php7.3/bin/php
test -s /usr/local/php7.4/bin/php
/usr/local/php7.3/bin/php -r 'exit(PHP_VERSION === "7.3.33" ? 0 : 1);'
/usr/local/php7.4/bin/php -r 'exit(PHP_VERSION === "7.4.33" ? 0 : 1);'
/usr/local/php7.3/bin/php -v
/usr/local/php7.4/bin/php -v
test -L /usr/local/php/bin/php
test "$(readlink /usr/local/php/bin/php)" = "/usr/local/php7.3/bin/php"
echo "php_link=/usr/local/php/bin/php -> /usr/local/php7.3/bin/php"

echo
echo "## Required PHP extensions"
for php_bin in /usr/local/php7.3/bin/php /usr/local/php7.4/bin/php; do
    for extension in bcmath curl gd intl mbstring mysqli pdo_mysql redis soap sockets zip; do
        if ! "$php_bin" -m | grep -qx "$extension"; then
            echo "Required extension is missing: $php_bin -> $extension" >&2
            exit 1
        fi
    done
    printf '%s required extensions: PASS\n' "$php_bin"
done

echo
echo "## Redis protection"
grep -E '^(bind|protected-mode|port) ' /etc/redis.conf
grep -q '^requirepass .\+' /etc/redis.conf && echo 'requirepass=present'

echo
echo "## Listening ports"
ss -lntp | grep -E ':(80|81|3300|6379)\b' || true

echo
echo "## Base services"
for service in nginx php-fpm73 php-fpm74 redis-sfd supervisor; do
    test "$(systemctl is-active "$service")" = "active"
    test "$(systemctl is-enabled "$service")" = "enabled"
    printf '%s=active/enabled\n' "$service"
done

test "$(stat -c '%U:%G:%a' /tmp/php-cgi.sock)" = "www:www:660"
test "$(stat -c '%U:%G:%a' /tmp/php-cgi7.4.sock)" = "www:www:660"
echo "php_fpm_sockets=www:www:660"

su -s /bin/sh -c 'test -x /workspace/wwwroot && test -x /workspace/wwwroot/log' www
echo "wwwroot_traversal=PASS"

if [ "$PHASE" = "environment" ]; then
    echo
    echo "## Environment-stage business runtime check"
    if find /etc/supervisor/conf.d -maxdepth 1 -type f -name '*_sfd.ini' -print -quit 2>/dev/null | grep -q .; then
        echo "Sifangda Supervisor business configuration was installed too early." >&2
        exit 1
    fi
    if crontab -u www -l 2>/dev/null | grep -q '^# BEGIN SIFANGDA PROJECT CRON$'; then
        echo "Sifangda project Cron was enabled too early." >&2
        exit 1
    fi
    echo "No Sifangda business Cron or Supervisor program is enabled."
    curl -fsS http://127.0.0.1/__sfd_env_health
    curl -fsS http://127.0.0.1:81/__sfd_env_health
    exit 0
fi

echo
echo "## Project directories"
test -d /workspace/wwwroot/zhct_sfd/current
test -d /workspace/wwwroot/zhct_sfd/project
test -d /workspace/wwwroot/aizhct_sfd/current
test -d /workspace/wwwroot/aizhct_sfd/project

echo
echo "## Supervisor"
shopt -s nullglob
supervisor_files=(/etc/supervisor/conf.d/*_sfd.ini)
if [ "${#supervisor_files[@]}" -eq 0 ]; then
    echo "Sifangda Supervisor business configuration is missing." >&2
    exit 1
fi
for supervisor_file in "${supervisor_files[@]}"; do
    if ! grep -Eq '^directory=/workspace/wwwroot/(zhct_sfd|aizhct_sfd)/project/?$' "$supervisor_file"; then
        echo "Supervisor directory is not a Sifangda project runtime path: $supervisor_file" >&2
        exit 1
    fi
done
/usr/local/bin/supervisorctl status

echo
echo "## Cron"
managed_cron="$(crontab -u www -l | sed -n '/^# BEGIN SIFANGDA PROJECT CRON$/,/^# END SIFANGDA PROJECT CRON$/p')"
if [ -z "$managed_cron" ]; then
    echo "Managed Sifangda project Cron block is missing." >&2
    exit 1
fi
printf '%s\n' "$managed_cron"
if printf '%s\n' "$managed_cron" | grep -q '/current/'; then
    echo "Managed Sifangda project Cron references current." >&2
    exit 1
fi

if grep -RIn '/current/' /etc/supervisor/conf.d/*_sfd.ini 2>/dev/null; then
    echo "Sifangda Supervisor configuration references current." >&2
    exit 1
fi

echo
echo "## HTTP checks"
curl -fsSI http://127.0.0.1/dist/ | head -n 1
curl -fsSI http://127.0.0.1/aizhct/ | head -n 1
