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

BASE=/opt/apusic-real
ALB=$BASE/install/ALB-V2.0.5-SE-amd64
AMDC=$BASE/install/amdc
APP=$BASE/app
RUNTIME=$BASE/runtime

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_ping($host, $port, $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)];
    }
    fwrite($fp, "*1\r\n$4\r\nPING\r\n");
    stream_set_timeout($fp, $timeout);
    $resp = fgets($fp);
    fclose($fp);
    return [
        'ok' => trim((string)$resp) === '+PONG',
        'response' => trim((string)$resp),
        'elapsed_ms' => round((microtime(true) - $start) * 1000, 2),
    ];
}

echo json_encode([
    'service' => 'real apusic alb + php-fpm + amdc verification',
    'time' => date('c'),
    'php' => PHP_VERSION,
    'amdc_ping' => redis_ping('127.0.0.1', 6359),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
PHP

cat > "$RUNTIME/php-fpm.conf" <<EOF
[global]
pid = $RUNTIME/php-fpm.pid
error_log = $BASE/logs/php-fpm-error.log
daemonize = yes

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

cp "$AMDC/amdc.yaml" "$RUNTIME/amdc-poc.yaml"
python3 - <<'PY'
from pathlib import Path
p = Path('/opt/apusic-real/runtime/amdc-poc.yaml')
s = p.read_text()
s = s.replace('    protected-mode: yes', '    protected-mode: no')
s = s.replace('    daemonize: no', '    daemonize: yes')
s = s.replace('    pidfile: /var/run/redis_6379.pid', '    pidfile: /opt/apusic-real/runtime/amdc.pid')
s = s.replace('    dir: ./', '    dir: /opt/apusic-real/runtime')
p.write_text(s)
PY

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

events {
    worker_connections 256;
}

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

    server {
        listen 18080;
        server_name localhost;
        root $APP;
        index index.php index.html;

        location = /health {
            add_header Content-Type text/plain;
            return 200 "alb ok\\n";
        }

        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:19000;
            fastcgi_read_timeout 60s;
        }
    }
}
EOF

if [ -f "$RUNTIME/alb.pid" ]; then
  "$ALB/sbin/alb" -p "$ALB" -c conf/alb-poc.conf -s stop || true
fi
if [ -f "$RUNTIME/amdc.pid" ]; then
  kill "$(cat "$RUNTIME/amdc.pid")" 2>/dev/null || true
fi
if [ -f "$RUNTIME/php-fpm.pid" ]; then
  kill "$(cat "$RUNTIME/php-fpm.pid")" 2>/dev/null || true
fi
pkill -f "php-fpm: master process \\($RUNTIME/php-fpm.conf\\)" 2>/dev/null || true
sleep 1

php-fpm -y "$RUNTIME/php-fpm.conf"
cd "$AMDC"
./amdc-server "$RUNTIME/amdc-poc.yaml" > "$BASE/logs/amdc-start.log" 2>&1 || {
  cat "$BASE/logs/amdc-start.log"
  exit 1
}
cd "$ALB"
./sbin/alb -p "$ALB" -c conf/alb-poc.conf -t
./sbin/alb -p "$ALB" -c conf/alb-poc.conf

sleep 2
echo '== listening =='
ss -lntp | grep -E '18080|19000|6359' || true
echo '== memory =='
free -h
