#!/usr/bin/env bash
set -Eeuo pipefail
[[ $EUID -eq 0 ]] || { printf 'Run as root\n' >&2; exit 1; }
app_host=${1:?Application hostname or IPv4 required}
public_key_file=${2:?Actions public key file required}
[[ "$app_host" =~ ^[a-zA-Z0-9.-]+$ && -f "$public_key_file" ]]
export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get install -y nginx php-fpm php-cli php-pgsql php-sqlite3 php-mbstring php-xml php-curl php-zip php-intl composer postgresql acl python3-venv
app_root=/var/www/eventcloudai
php_version=$(php -r 'echo PHP_MAJOR_VERSION,".",PHP_MINOR_VERSION;')

id eventcloud > /dev/null 2>&1 || useradd --create-home --shell /bin/bash eventcloud
usermod -a -G www-data eventcloud
install -d -o eventcloud -g eventcloud -m 700 /home/eventcloud/.ssh
touch /home/eventcloud/.ssh/authorized_keys
key="restrict $(cat "$public_key_file")"
grep -qxF "$key" /home/eventcloud/.ssh/authorized_keys || printf '%s\n' "$key" >> /home/eventcloud/.ssh/authorized_keys
chown eventcloud:eventcloud /home/eventcloud/.ssh/authorized_keys
chmod 600 /home/eventcloud/.ssh/authorized_keys
install -d -o eventcloud -g eventcloud -m 750 /home/eventcloud/bin
install -d -o eventcloud -g www-data -m 2770 "$app_root" "$app_root/releases" "$app_root/shared"
for folder in '' app app/private app/public framework framework/cache framework/cache/data framework/sessions framework/views logs; do
  install -d -o eventcloud -g www-data -m 2770 "$app_root/shared/storage/$folder"
done
install -d -o eventcloud -g eventcloud -m 700 "$app_root/shared/backups"
install -d -o www-data -g www-data -m 755 /var/www/acme/.well-known/acme-challenge

python3 - "$app_root" "$app_host" <<'PY'
import base64
import os
import pathlib
import secrets
import subprocess
import sys

root = pathlib.Path(sys.argv[1])
env_file = root / 'shared/.env'
if not env_file.exists():
    password = secrets.token_hex(32)
    app_key = base64.b64encode(secrets.token_bytes(32)).decode()
    env_file.write_text(f'''APP_NAME="EventCloud AI"
APP_ENV=production
APP_KEY=base64:{app_key}
APP_DEBUG=false
APP_URL=http://{sys.argv[2]}
FRONTEND_URL=http://{sys.argv[2]}/app
APP_LOCALE=es
APP_FALLBACK_LOCALE=en
APP_MAINTENANCE_DRIVER=file
LOG_CHANNEL=daily
LOG_LEVEL=warning
LOG_DAILY_DAYS=14
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=eventcloud
DB_USERNAME=eventcloud
DB_PASSWORD={password}
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=true
SESSION_SECURE_COOKIE=false
SESSION_SAME_SITE=lax
SANCTUM_STATEFUL_DOMAINS={sys.argv[2]}
QUEUE_CONNECTION=database
CACHE_STORE=database
FILESYSTEM_DISK=local
MAIL_MAILER=log
MAIL_FROM_ADDRESS=notifications@eventcloud.invalid
MAIL_FROM_NAME="EventCloud AI"
OPENAI_API_KEY=
AI_RESPONSE_MODEL=
AI_EMBEDDING_MODEL=
''')
    env_file.chmod(0o640)
settings = dict(line.split('=', 1) for line in env_file.read_text().splitlines() if line and not line.startswith('#') and '=' in line)
database_password = settings['DB_PASSWORD']
query = "SELECT 1 FROM pg_roles WHERE rolname='eventcloud';"
exists = subprocess.check_output(['runuser', '-u', 'postgres', '--', 'psql', '-tAc', query], text=True).strip()
if not exists:
    sql = "CREATE ROLE eventcloud LOGIN PASSWORD '" + database_password.replace("'", "''") + "';"
    subprocess.run(['runuser', '-u', 'postgres', '--', 'psql', '-v', 'ON_ERROR_STOP=1'], input=sql, text=True, check=True)
query = "SELECT 1 FROM pg_database WHERE datname='eventcloud';"
exists = subprocess.check_output(['runuser', '-u', 'postgres', '--', 'psql', '-tAc', query], text=True).strip()
if not exists:
    subprocess.run(['runuser', '-u', 'postgres', '--', 'createdb', '-O', 'eventcloud', 'eventcloud'], check=True)
print('Application configuration and PostgreSQL database ready.')
PY
chown eventcloud:www-data "$app_root/shared/.env"
chmod 640 "$app_root/shared/.env"

cat > "/etc/php/$php_version/fpm/pool.d/eventcloudai.conf" <<EOF
[eventcloudai]
user = www-data
group = www-data
listen = /run/php/eventcloudai.sock
listen.owner = www-data
listen.group = www-data
pm = dynamic
pm.max_children = 12
pm.start_servers = 3
pm.min_spare_servers = 2
pm.max_spare_servers = 5
pm.max_requests = 500
php_admin_value[memory_limit] = 128M
php_admin_value[upload_max_filesize] = 10M
php_admin_value[post_max_size] = 12M
php_admin_flag[display_errors] = off
EOF
cat > "/etc/php/$php_version/fpm/conf.d/99-eventcloudai.ini" <<'EOF'
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=20000
opcache.validate_timestamps=1
expose_php=Off
EOF
if [[ -f "/etc/php/$php_version/fpm/pool.d/www.conf" ]]; then
  mv "/etc/php/$php_version/fpm/pool.d/www.conf" "/etc/php/$php_version/fpm/pool.d/www.conf.disabled"
fi

cat > /etc/nginx/sites-available/eventcloudai <<'EOF'
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name __APP_HOST__;
    root /var/www/eventcloudai/current/public;
    index index.php index.html;
    charset utf-8;
    client_max_body_size 12m;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    location ^~ /.well-known/acme-challenge/ {
        root /var/www/acme;
        try_files $uri =404;
    }
    location / { try_files $uri $uri/ /index.php?$query_string; }
    location = /app/index.html { add_header Cache-Control "no-cache"; }
    location ~* \.(?:css|js|svg|png|jpg|jpeg|webp|woff2?)$ {
        try_files $uri =404;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
    location ~ ^/index\.php(/|$) {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/eventcloudai.sock;
        fastcgi_hide_header X-Powered-By;
    }
    location ~ \.php$ { return 404; }
    location ~ /\.(?!well-known).* { deny all; }
}
EOF
sed -i "s/__APP_HOST__/$app_host/g" /etc/nginx/sites-available/eventcloudai
if [[ -L /etc/nginx/sites-enabled/default ]]; then
  unlink /etc/nginx/sites-enabled/default
fi
ln -sfn /etc/nginx/sites-available/eventcloudai /etc/nginx/sites-enabled/eventcloudai

cat > /etc/systemd/system/eventcloudai-queue.service <<'EOF'
[Unit]
Description=EventCloudAI queue worker
After=network.target postgresql.service
ConditionPathExists=/var/www/eventcloudai/current/artisan
[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/eventcloudai/current
ExecStart=/usr/bin/php artisan queue:work --sleep=3 --tries=3 --timeout=60 --memory=128 --max-time=3600 --no-interaction
Restart=always
RestartSec=5
TimeoutStopSec=180
KillSignal=SIGTERM
[Install]
WantedBy=multi-user.target
EOF
cat > /etc/systemd/system/eventcloudai-scheduler.service <<'EOF'
[Unit]
Description=EventCloudAI scheduled tasks
After=postgresql.service
ConditionPathExists=/var/www/eventcloudai/current/artisan
[Service]
Type=oneshot
User=www-data
Group=www-data
WorkingDirectory=/var/www/eventcloudai/current
ExecStart=/usr/bin/php artisan schedule:run --no-interaction
EOF
cat > /etc/systemd/system/eventcloudai-scheduler.timer <<'EOF'
[Unit]
Description=Run EventCloudAI scheduler every minute
[Timer]
OnCalendar=*-*-* *:*:00
AccuracySec=1s
Persistent=true
[Install]
WantedBy=timers.target
EOF
cat > /usr/local/sbin/eventcloudai-reload <<EOF
#!/bin/sh
set -eu
/usr/sbin/nginx -t
/usr/bin/systemctl reload php$php_version-fpm
/usr/bin/systemctl reload nginx
/usr/bin/systemctl restart eventcloudai-queue
EOF
chmod 755 /usr/local/sbin/eventcloudai-reload
printf 'eventcloud ALL=(root) NOPASSWD: /usr/local/sbin/eventcloudai-reload\n' > /etc/sudoers.d/eventcloudai
chmod 440 /etc/sudoers.d/eventcloudai
visudo -cf /etc/sudoers.d/eventcloudai
nginx -t
systemctl daemon-reload
systemctl enable --now postgresql "php$php_version-fpm" nginx eventcloudai-scheduler.timer
systemctl enable eventcloudai-queue
systemctl restart "php$php_version-fpm"
systemctl reload nginx
printf 'Server ready for a clean deployment at http://%s/app\n' "$app_host"
