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

BASE=/opt/apusic-real
ALB=$BASE/install/ALB-V2.0.5-SE-amd64
APP=$BASE/app-dual-php
RUNTIME=$BASE/runtime
PHP73=/www/server/php/73/sbin/php-fpm
PHP74=/www/server/php/74/sbin/php-fpm

mkdir -p "$APP" "$RUNTIME" "$BASE/logs" \
  "$ALB/logs" "$ALB/client_body_temp" "$ALB/proxy_temp" \
  "$ALB/fastcgi_temp" "$ALB/uwsgi_temp" "$ALB/scgi_temp"

cat > "$APP/index.php" <<'PHP'
<?php
header('Content-Type: application/json; charset=utf-8');

function redis_cmd($host, $port, array $parts, $timeout = 2) {
    $errno = 0;
    $errstr = '';
    $start = microtime(true);
    $fp = @fsockopen($host, (int)$port, $errno, $errstr, $timeout);
    if (!$fp) {
        return ['ok' => false, 'error' => $errstr ?: ('errno=' . $errno)];
    }
    $payload = '*' . count($parts) . "\r\n";
    foreach ($parts as $part) {
        $part = (string)$part;
        $payload .= '$' . strlen($part) . "\r\n" . $part . "\r\n";
    }
    fwrite($fp, $payload);
    stream_set_timeout($fp, $timeout);
    $resp = trim((string)fgets($fp));
    fclose($fp);
    return [
        'ok' => $resp !== '',
        'response' => $resp,
        'elapsed_ms' => round((microtime(true) - $start) * 1000, 2),
    ];
}

$ping = redis_cmd('127.0.0.1', 6359, ['PING']);
$set = redis_cmd('127.0.0.1', 6359, ['SET', 'apusic:php:version', PHP_VERSION]);
$get = redis_cmd('127.0.0.1', 6359, ['GET', 'apusic:php:version']);

echo json_encode([
    'service' => 'real apusic alb + amdc + php-fpm verification',
    'time' => date('c'),
    'server_port' => $_SERVER['SERVER_PORT'] ?? '',
    'php' => PHP_VERSION,
    'sapi' => PHP_SAPI,
    'amdc_ping' => $ping,
    'amdc_set' => $set,
    'amdc_get' => $get,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
PHP

make_fpm_conf() {
  local version="$1"
  local port="$2"
  local conf="$RUNTIME/php${version}-fpm.conf"
  cat > "$conf" <<EOF
[global]
pid = $RUNTIME/php${version}-fpm.pid
error_log = $BASE/logs/php${version}-fpm-error.log
daemonize = yes

[www]
listen = 127.0.0.1:$port
listen.backlog = 64
user = nobody
group = nobody
pm = static
pm.max_children = 1
request_terminate_timeout = 60s
chdir = /
catch_workers_output = yes
EOF
}

make_fpm_conf 73 19073
make_fpm_conf 74 19074

cat > "$ALB/conf/alb-php73-74.conf" <<EOF
worker_processes 1;
pid $RUNTIME/alb-php73-74.pid;
error_log $BASE/logs/alb-php73-74-error.log info;

events {
    worker_connections 256;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    access_log $BASE/logs/alb-php73-74-access.log;
    sendfile on;
    keepalive_timeout 30;

    server {
        listen 18073;
        server_name localhost;
        root $APP;
        index index.php;
        location / { try_files \$uri \$uri/ /index.php?\$query_string; }
        location ~ \\.php$ {
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            fastcgi_param SCRIPT_NAME \$fastcgi_script_name;
            fastcgi_pass 127.0.0.1:19073;
        }
    }

    server {
        listen 18074;
        server_name localhost;
        root $APP;
        index index.php;
        location / { try_files \$uri \$uri/ /index.php?\$query_string; }
        location ~ \\.php$ {
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
            fastcgi_param SCRIPT_NAME \$fastcgi_script_name;
            fastcgi_pass 127.0.0.1:19074;
        }
    }
}
EOF

if [ -f "$RUNTIME/alb-php73-74.pid" ]; then
  "$ALB/sbin/alb" -p "$ALB" -c conf/alb-php73-74.conf -s stop || true
fi
for version in 73 74; do
  if [ -f "$RUNTIME/php${version}-fpm.pid" ]; then
    kill "$(cat "$RUNTIME/php${version}-fpm.pid")" 2>/dev/null || true
  fi
done
pkill -f "php73-fpm.conf" 2>/dev/null || true
pkill -f "php74-fpm.conf" 2>/dev/null || true
sleep 1

"$PHP73" -y "$RUNTIME/php73-fpm.conf"
"$PHP74" -y "$RUNTIME/php74-fpm.conf"
cd "$ALB"
./sbin/alb -p "$ALB" -c conf/alb-php73-74.conf -t
./sbin/alb -p "$ALB" -c conf/alb-php73-74.conf

sleep 2
echo '== listening =='
ss -lntp | grep -E '18073|18074|19073|19074|6359' || true
echo '== php73 =='
curl -fsS http://127.0.0.1:18073/
echo
echo '== php74 =='
curl -fsS http://127.0.0.1:18074/
echo
echo '== memory =='
free -h
