#!/bin/bash
# panel-site-add <domain> <docroot> [user] [--create]
# Create or refresh the Apache vhost for a site (idempotent).
# HTTPS is switched on automatically when /etc/panel/ssl/<domain>/{fullchain,privkey}.pem exist.
set -euo pipefail
. /opt/panel/bin/panel-lib.sh
if [ "${1:-}" = on ]; then   # the same on a connected server
  srv="${2:-}"; ip=$(node_ip "$srv") || die "unknown server: $srv"; shift 2
  exec timeout 60 ssh "${NODE_SSH_OPTS[@]}" "root@$ip" "/opt/panel/bin/panel-site-add $(printf '%q ' "$@")"
fi
d="${1:-}"; root="${2:-}"; u="${3:-$PANEL_USER}"; create="${4:-}"
valid_domain "$d" || die "invalid domain: $d"
valid_user "$u" || die "invalid user: $u"
[ -n "$root" ] || root="/home/$u/public_html/$d"
# Docroot must live inside the user's public_html (also stops path tricks via ../ or symlinks).
base="/home/$u/public_html"
if [ "$create" = "--create" ] && [ ! -d "$root" ]; then
  case "$root" in "$base"/*) ;; *) die "docroot must be inside $base";; esac
  [[ "$root" != *..* ]] || die "invalid docroot"
  install -d -m 750 -o "$u" -g "$u" "$root"
fi
[ -d "$root" ] || die "docroot does not exist: $root"
real=$(realpath "$root")
case "$real" in "$base"|"$base"/*|"$(realpath "$base")"/*) ;; *) die "docroot must be inside $base";; esac

sock="/run/php-fpm/$u.sock"
ssl="$PANEL_SSL/$d"
conf="$(site_conf "$d")"
has_ssl=0; [ -s "$ssl/fullchain.pem" ] && [ -s "$ssl/privkey.pem" ] && has_ssl=1

body() { cat <<B
    ServerName $d
    ServerAlias www.$d
    DocumentRoot $root
    <Directory $root>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    # PHP via FPM. SetHandler wins over old cPanel "AddHandler x-httpd-ea-php" lines in .htaccess, so PHP is never served as source.
    <FilesMatch "\.(php|phtml|php8)$">
        SetHandler "proxy:unix:$sock|fcgi://localhost"
    </FilesMatch>
    DirectoryIndex index.php index.html
    # optional extra settings for this site (e.g. a WebSocket proxy); kept when the vhost is regenerated
    IncludeOptional /etc/panel/vhost-extra/$d.conf
    ErrorLog /var/log/httpd/sites/$d.error.log
    CustomLog /var/log/httpd/sites/$d.access.log combined
B
}
{
  echo "# managed by panel — regenerated by panel-site-add; do not edit by hand"
  echo "<VirtualHost *:80>"; body
  if [ $has_ssl = 1 ]; then
    echo "    RewriteEngine On"
    echo "    RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/"
    echo "    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]"
  fi
  echo "</VirtualHost>"
  if [ $has_ssl = 1 ]; then
    echo "<VirtualHost *:443>"; body
    echo "    SSLEngine on"
    echo "    SSLCertificateFile $ssl/fullchain.pem"
    echo "    SSLCertificateKeyFile $ssl/privkey.pem"
    echo "</VirtualHost>"
  fi
} > "$conf.new"
cp -f "$conf" "$conf.bak" 2>/dev/null || true
mv "$conf.new" "$conf"
# PANEL_NO_RELOAD=1: write the config only (when regenerating many sites, reload once at the end - every reload
# leaves old Apache processes holding open live-chat connections for a while)
[ -n "${PANEL_NO_RELOAD:-}" ] || { [ -x /opt/panel/bin/panel-admin-hosts ] && /opt/panel/bin/panel-admin-hosts; }   # panel also at https://<domain>:8443/
if apachectl -t >/dev/null 2>&1; then
  [ -n "${PANEL_NO_RELOAD:-}" ] || systemctl reload httpd
  echo "site ok: $d -> $root (https: $([ $has_ssl = 1 ] && echo on || echo off))"
else
  apachectl -t 2>&1 | tail -3 >&2
  [ -f "$conf.bak" ] && mv -f "$conf.bak" "$conf" || rm -f "$conf"
  die "apache config test failed — change rolled back"
fi
# a newly created site should show up in the panel (and on connected servers) right away
[ "$create" != "--create" ] || /opt/panel/bin/panel-ssl-status >/dev/null 2>&1 || true
