#!/bin/sh
# Linux/systemd instance manager. All paths are fixed; no configuration is sourced.
set -eu
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
export PATH
umask 077
ROOT=/opt/playeraudio
STATE=/var/lib/playeraudio
ETC=/etc/playeraudio
die() { printf '%s\n' "$*" >&2; exit 1; }
usage() {
 cat <<'EOF'
playeraudio create NAME DOMAIN PORT COMMUNITY_NAME --tls CERT.pem KEY.pem
playeraudio create NAME DOMAIN PORT COMMUNITY_NAME --proxy
playeraudio list
playeraudio start|stop|restart|status|logs NAME
playeraudio backup NAME [--keep]
playeraudio prune-backups NAME
playeraudio relay NAME
playeraudio update NAME HTTPS_MANIFEST_URL
playeraudio certificates NAME CERT.pem KEY.pem
Each instance has its own Linux user, data directory and listening port.
Updates are explicit. Stop/start and updates affect only the selected instance.
Backups are compressed; keep the newest three ordinary backups per instance.
--keep pins a backup against automatic pruning. Migration/named backups are retained.
EOF
}
case ${1:-help} in help|--help|-h) usage; exit 0;; esac
[ "$(uname -s)" = Linux ] || die 'Linux with systemd is required'
[ "$(id -u)" = 0 ] || die 'Run this manager with sudo'
command=$1; shift
mkdir -p "$STATE" "$ETC/instances" "$ETC/sites" "$ROOT/releases"
exec 9>"$STATE/manager.lock"
flock -x 9
valid_name() { case $1 in ''|*[!a-z0-9-]*|-*|*-|?????????????????????????*) die 'Use a name of 1–24 lowercase letters, digits or internal hyphens';; esac; }
instance() { [ "$#" -ge 1 ] || die 'An instance name is required'; name=$1; valid_name "$name"; dir="$STATE/instances/$name"; unit="playeraudio@$name.service"; [ -f "$ETC/instances/$name.env" ] || die 'Unknown instance'; }
# Runs a command as the instance's own Linux user. An instance's data directory belongs to that user, so root
# must not create, overwrite or chown files inside it: the user could have left a symbolic link there and have
# root act on any file on the system. Everything written into data/ after `create` goes through this.
as_instance() { command -v runuser >/dev/null || die 'Missing prerequisite: runuser (util-linux)'; runuser -u "pa-$name" -- "$@"; }
proxy_reload() { caddy validate --config "$ETC/Caddyfile" --adapter caddyfile >/dev/null; systemctl reload-or-restart playeraudio-proxy.service; }
voice_firewall() {
 relay_port=$(jq -r --argjson base "$2" '.relay.port // ($base + 1)' "$1")
 relay_min=$(jq -r '.relay.minPort // 40000' "$1"); relay_max=$(jq -r '.relay.maxPort // 49999' "$1")
 for number in "$relay_port" "$relay_min" "$relay_max"; do case $number in ''|*[!0-9]*) die 'Invalid relay port';; esac; done
 [ "$relay_port" -ge 1024 ] && [ "$relay_port" -le 65533 ] && [ "$relay_min" -ge 1024 ] && [ "$relay_max" -le 65534 ] && [ "$relay_min" -lt "$relay_max" ] || die 'Invalid relay port range'
 if command -v ufw >/dev/null && ufw status | grep -q '^Status: active'; then
   ufw allow "$relay_port/udp" comment 'PlayerAudio voice'
   ufw allow "$relay_port/tcp" comment 'PlayerAudio voice'
   ufw allow "$((relay_port + 1))/tcp" comment 'PlayerAudio voice TLS'
   ufw allow "$relay_min:$relay_max/udp" comment 'PlayerAudio voice media'
 elif command -v firewall-cmd >/dev/null && firewall-cmd --state >/dev/null 2>&1; then
   for item in "$relay_port/udp" "$relay_port/tcp" "$((relay_port + 1))/tcp" "$relay_min-$relay_max/udp"; do firewall-cmd --permanent --add-port="$item"; done
   firewall-cmd --reload
 fi
 printf 'Voice relay ports: UDP/TCP %s, TLS TCP %s, media UDP %s–%s. Allow these in any router or provider firewall too.\n' "$relay_port" "$((relay_port + 1))" "$relay_min" "$relay_max"
}
# Backup helpers are also exercised against isolated fixture directories.
backup() (
 backup_dir="$STATE/backups/$name"
 mkdir -p "$backup_dir"
 [ "$(readlink -f "$backup_dir")" = "$backup_dir" ] || die 'Backup directory must not use symbolic links'
 archive="$backup_dir/$(date -u +%Y%m%dT%H%M%SZ)-$$.tar.gz"
 [ ! -e "$archive" ] || die 'Backup already exists; retry in one second'
 partial="$archive.partial"
 cleanup_backup() { rm -f -- "$partial" "$partial.sha256"; }
 trap cleanup_backup EXIT
 trap 'exit 1' HUP INT TERM
 # Allow the uncompressed size plus 256 MiB of headroom. Incompressible uploads
 # must not turn an update into an ENOSPC outage.
 needed=$(du -sk --apparent-size "$dir/data" | awk '{print $1}')
 available=$(df -Pk "$backup_dir" | awk 'END {print $4}')
 [ "$available" -gt "$((needed + 262144))" ] || die 'Insufficient free space for a safe backup; free disk space before retrying'
 # Data and its storage key must be backed up together. This archive is private,
 # not encrypted; export it only through an encrypted backup destination.
 tar -C "$dir" -I 'gzip -1' -cf "$partial" data release.json
 tar -tzf "$partial" >/dev/null
 hash=$(sha256sum "$partial" | awk '{print $1}')
 printf '%s\n' "$hash" | grep -Eq '^[0-9a-f]{64}$' || die 'Failed to checksum backup'
 printf '%s\n' "$hash" >"$partial.sha256"
 chmod 600 "$partial" "$partial.sha256"
 mv -- "$partial" "$archive"
 mv -- "$partial.sha256" "$archive.sha256"
 if [ "${pin_backup:-0}" = 1 ]; then : >"$archive.keep"; fi
 printf 'Private backup: %s\n' "$archive"
)
prune_backups() (
 backup_dir="$STATE/backups/$name"
 [ -d "$backup_dir" ] || exit 0
 [ "$(readlink -f "$backup_dir")" = "$backup_dir" ] || die 'Backup directory must not use symbolic links'
 list=$(mktemp "$backup_dir/.retention.XXXXXX")
 trap 'rm -f -- "$list"' EXIT
 trap 'exit 1' HUP INT TERM
 # Only manager-generated names qualify. Named migration archives, links and
 # explicit .keep pins never count toward or get removed by this policy.
 for file in "$backup_dir"/*.tar "$backup_dir"/*.tar.gz; do
   [ -f "$file" ] && [ ! -L "$file" ] || continue
   [ ! -e "$file.keep" ] && [ ! -L "$file.keep" ] || continue
   base=${file##*/}
   printf '%s\n' "$base" | grep -Eq '^[0-9]{8}T[0-9]{6}Z-[0-9]+\.tar(\.gz)?$' || continue
   printf '%s\n' "$base"
 done | LC_ALL=C sort -r >"$list"
 count=0
 while IFS= read -r base; do
   count=$((count + 1)); [ "$count" -le 3 ] || break
   file="$backup_dir/$base"
   [ -f "$file.sha256" ] && [ ! -L "$file.sha256" ] || die "Retention skipped: checksum missing for $base"
   expected=$(cat "$file.sha256")
   printf '%s\n' "$expected" | grep -Eq '^[0-9a-f]{64}$' || die "Retention skipped: invalid checksum for $base"
   [ "$(sha256sum "$file" | awk '{print $1}')" = "$expected" ] || die "Retention skipped: checksum mismatch for $base"
   tar -tf "$file" >/dev/null || die "Retention skipped: unreadable archive $base"
 done <"$list"
 count=0
 while IFS= read -r base; do
   count=$((count + 1)); [ "$count" -gt 3 ] || continue
   file="$backup_dir/$base"
   [ -f "$file" ] && [ ! -L "$file" ] && [ ! -e "$file.keep" ] && [ ! -L "$file.keep" ] || continue
   rm -- "$file"
   rm -f -- "$file.sha256"
   printf 'Expired backup: %s\n' "$file"
 done <"$list"
)
# End backup helpers.
case $command in
 list) [ "$#" = 0 ] || die 'list takes no arguments'; for file in "$ETC"/instances/*.env; do [ -f "$file" ] || continue; name=${file##*/}; name=${name%.env}; printf '%s: ' "$name"; systemctl is-active "playeraudio@$name.service" || :; done;;
 create)
 [ "$#" = 5 ] || [ "$#" = 7 ] || die 'create requires NAME DOMAIN PORT COMMUNITY_NAME followed by --tls CERT KEY or --proxy'
 name=$1; domain=$2; port=$3; community=$4; valid_name "$name"
 mode=$5
 case $mode in --proxy) [ "$#" = 5 ] && command -v caddy >/dev/null && [ -f /etc/systemd/system/playeraudio-proxy.service ] || die 'Proxy mode requires Caddy and its installed service';; --tls) [ "$#" = 7 ] && [ -f "$6" ] && [ -f "$7" ] || die 'Direct TLS requires certificate and key files';; *) die 'Choose --tls CERT KEY or --proxy';; esac
 printf '%s' "$domain" | grep -Eq '^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$' || die 'Use a lowercase public DNS domain'
 case $port in ''|*[!0-9]*) die 'Invalid port';; esac
 [ "$port" -ge 1024 ] && [ "$port" -le 65532 ] || die 'Port must be 1024–65532 (two adjacent ports are reserved for voice)'
 [ ! -e "$ETC/instances/$name.env" ] && [ ! -e "$STATE/instances/$name" ] || die 'Instance already exists'
 for file in "$ETC"/instances/*.env; do
   [ -f "$file" ] || continue
   existing=$(sed -n 's/^PLAYERAUDIO_SERVER_PORT=//p' "$file")
   [ "$port" -gt "$((existing + 2))" ] || [ "$((port + 2))" -lt "$existing" ] || die 'Choose ports at least three apart for separate communities'
 done
 if [ "$mode" = --proxy ]; then for file in "$ETC"/sites/*.caddy; do [ -f "$file" ] || continue; grep -Fqx "$domain {" "$file" && die 'Proxy domain already assigned'; done; fi
 for candidate in "$port" "$((port + 1))" "$((port + 2))"; do
   ss -H -ltnu | awk '{print $5}' | grep -Eq ":$candidate$" && die 'A server or voice port is already listening'
 done
 [ -x "$ROOT/default/playeraudio-server" ] || die 'Install a verified release first'
 if [ "$mode" = --tls ]; then
   "$ROOT/default/playeraudio-server" check-tls --cert "$6" --key "$7"
   openssl x509 -in "$6" -checkhost "$domain" -noout >/dev/null || die 'Certificate does not cover the instance hostname'
 fi
 dir="$STATE/instances/$name"; mkdir -p "$dir/data"
 user="pa-$name"; id "$user" >/dev/null 2>&1 && die 'Instance operating-system user already exists'
 useradd --system --home-dir "$dir" --shell /usr/sbin/nologin "$user"
 "$ROOT/default/playeraudio-server" setup --config "$dir/data/server.json" --name "$community"
 cp "$ROOT/default/release.json" "$dir/release.json"
 ln -s "$(readlink -f "$ROOT/default")" "$dir/current"
 if [ "$mode" = --tls ]; then
   mkdir -p "$dir/data/tls"
   install -m 600 "$6" "$dir/data/tls/cert.pem"
   install -m 600 "$7" "$dir/data/tls/key.pem"
 fi
 chown -R "$user:$user" "$dir/data"
 chmod 711 "$STATE" "$STATE/instances" "$dir"
 host=127.0.0.1; [ "$mode" = --proxy ] || host=0.0.0.0
 printf 'PLAYERAUDIO_SERVER_CONFIG=%s/data/server.json\nPLAYERAUDIO_SERVER_HOST=%s\nPLAYERAUDIO_SERVER_PORT=%s\nPLAYERAUDIO_PUBLIC_HOST=%s\n' "$dir" "$host" "$port" "$domain" >"$ETC/instances/$name.env"
 if [ "$mode" = --tls ]; then
   printf 'PLAYERAUDIO_TLS_CERT=%s/data/tls/cert.pem\nPLAYERAUDIO_TLS_KEY=%s/data/tls/key.pem\n' "$dir" "$dir" >>"$ETC/instances/$name.env"
 else
 cat >"$ETC/sites/$name.caddy" <<EOF
$domain {
  @community path /health /socket /branding/* /expressions/* /platform/ownership /platform/presence/members /membership/leave /access /access/password /access/invite /integrations/webhooks /files /files/* /activity /events/public /soundboard /soundboard/*
  handle @community {
    reverse_proxy 127.0.0.1:$port
  }
  handle {
    respond 404
  }
  header X-Content-Type-Options nosniff
}
EOF
 chmod 644 "$ETC/sites/$name.caddy"
 fi
 systemctl enable --now "playeraudio@$name.service"
 voice_firewall "$dir/data/server.json" "$port"
 endpoint="https://$domain:$port"; if [ "$mode" = --proxy ]; then proxy_reload; endpoint="https://$domain"; fi
 printf 'Instance %s started at %s. Owner code: %s/data/setup-code.txt\nAdd this HTTPS endpoint in the client, then claim ownership with the private setup code.\n' "$name" "$endpoint" "$dir"
 ;;
 relay)
 [ "$#" = 1 ] || die 'relay requires NAME'; instance "$1"
 port=$(sed -n 's/^PLAYERAUDIO_SERVER_PORT=//p' "$ETC/instances/$name.env")
 # Keep a copy, then switch the relay on in the configuration; as the instance user (see as_instance).
 as_instance sh -c 'set -eu; umask 077; cd "$1"
   cp -p server.json "server-before-relay-$2.json"
   jq ".relay = ((.relay // {}) + {enabled:true})" server.json >server-relay.next
   mv -f server-relay.next server.json' sh "$dir/data" "$(date -u +%Y%m%dT%H%M%SZ)"
 voice_firewall "$dir/data/server.json" "$port"
 # Existing installed templates may predate the relay. Pion reads interface
 # information through netlink; grant this address family to this instance.
 mkdir -p "/etc/systemd/system/$unit.d"
 printf '[Service]\nRestrictAddressFamilies=AF_NETLINK\n' > "/etc/systemd/system/$unit.d/voice-relay.conf"
 systemctl daemon-reload
 systemctl restart "$unit"
 ;;
 certificates)
 [ "$#" = 3 ] || die 'certificates requires NAME CERT KEY'; instance "$1"
 [ -d "$dir/data/tls" ] || die 'Instance does not use direct TLS'
 # The pair is checked on copies in a directory only root can enter. Only then is it written into the
 # instance's directory, as the instance user (see as_instance). Server reload validates the pair again and
 # retains its active certificate on failure.
 work=$(mktemp -d "$STATE/certificates.XXXXXX"); trap 'rm -rf "$work"' EXIT
 install -m 600 "$2" "$work/cert.pem"
 install -m 600 "$3" "$work/key.pem"
 "$dir/current/playeraudio-server" check-tls --cert "$work/cert.pem" --key "$work/key.pem"
 domain=$(sed -n 's/^PLAYERAUDIO_PUBLIC_HOST=//p' "$ETC/instances/$name.env")
 openssl x509 -in "$work/cert.pem" -checkhost "$domain" -noout >/dev/null || die 'Certificate does not cover the instance hostname'
 openssl x509 -in "$work/cert.pem" -pubkey -noout >"$work/cert.public.pem"
 openssl pkey -pubin -in "$work/cert.public.pem" -outform DER -out "$work/cert.public.der"
 openssl pkey -in "$work/key.pem" -passin pass: -pubout -outform DER -out "$work/key.public.der"
 cmp -s "$work/cert.public.der" "$work/key.public.der" || die 'Certificate and private key do not match'
 # Root only supplies the bytes on standard input; the instance user creates the files.
 as_instance sh -c 'umask 077; cat >"$1/cert.next"' sh "$dir/data/tls" <"$work/cert.pem"
 as_instance sh -c 'umask 077; cat >"$1/key.next"' sh "$dir/data/tls" <"$work/key.pem"
 as_instance sh -c 'mv -f "$1/cert.next" "$1/cert.pem" && mv -f "$1/key.next" "$1/key.pem"' sh "$dir/data/tls"
 rm -rf "$work"; trap - EXIT
 systemctl kill --kill-who=main --signal=HUP "$unit"
 ;;
 start|stop|restart|status|logs)
 [ "$#" = 1 ] || die 'Expected one instance name'; instance "$1"
 case $command in logs) exec journalctl -u "$unit" -n 100 --no-pager;; *) exec systemctl "$command" "$unit";; esac;;
 backup)
 [ "$#" = 1 ] || { [ "$#" = 2 ] && [ "$2" = --keep ]; } || die 'Expected NAME [--keep]'; instance "$1"
 pin_backup=0; [ "$#" = 1 ] || pin_backup=1
 active=0; systemctl is-active --quiet "$unit" && active=1
 restore() { [ "$active" = 0 ] || systemctl start "$unit"; }; trap restore EXIT
 systemctl stop "$unit"; backup
 restore; trap - EXIT
 prune_backups
 ;;
 prune-backups)
 [ "$#" = 1 ] || die 'Expected one instance name'; instance "$1"
 prune_backups
 ;;
 update)
 [ "$#" = 2 ] || die 'update requires NAME HTTPS_MANIFEST_URL'; instance "$1"; url=$2
 target=$(jq -er '.target' "$dir/release.json"); sequence=$(jq -er '.sequence' "$dir/release.json")
 stage="$ROOT/releases/stage-$(date -u +%Y%m%dT%H%M%SZ)-$$"
 "$dir/current/playeraudio-server" stage-update --manifest-url "$url" --key "$ETC/release-key.hex" --target "$target" --minimum-sequence "$sequence" --destination "$stage"
 chmod 755 "$stage"
 old=$(readlink -f "$dir/current"); active=0; systemctl is-active --quiet "$unit" && active=1
 systemctl stop "$unit"
 # Back up while stopped, then authenticate the state with the candidate before
 # allowing it to serve writes. Do not automatically roll back data files.
 recover() { systemctl stop "$unit"; ln -s "$old" "$dir/recovery-$$"; mv -Tf "$dir/recovery-$$" "$dir/current"; install -m 600 "$old/release.json" "$dir/release-recovery.json"; mv -f "$dir/release-recovery.json" "$dir/release.json"; [ "$active" = 0 ] || systemctl start "$unit"; }
 trap recover EXIT
 backup
 if [ -f "$dir/data/community.enc" ]; then "$stage/playeraudio-server" check-store --config "$dir/data/server.json"; fi
 ln -s "$stage" "$dir/next-$$"; mv -Tf "$dir/next-$$" "$dir/current"
 if [ "$active" = 1 ]; then
   systemctl start "$unit"
   port=$(sed -n 's/^PLAYERAUDIO_SERVER_PORT=//p' "$ETC/instances/$name.env")
   expected=$(jq -er '.id' "$dir/data/server.json"); expected_version=$(jq -er '.version' "$stage/release.json"); tries=0
   health() {
     if grep -q '^PLAYERAUDIO_TLS_CERT=' "$ETC/instances/$name.env"; then
       domain=$(sed -n 's/^PLAYERAUDIO_PUBLIC_HOST=//p' "$ETC/instances/$name.env")
       curl --fail --silent --max-time 2 --resolve "$domain:$port:127.0.0.1" "https://$domain:$port/health"
     else curl --fail --silent --max-time 2 "http://127.0.0.1:$port/health"; fi
   }
   until health | jq -e --arg id "$expected" --arg version "$expected_version" '.status == "ok" and .id == $id and .protocol == 1 and .version == $version' >/dev/null; do
     tries=$((tries+1)); [ "$tries" -lt 15 ] || { systemctl stop "$unit"; die 'Candidate failed health checks; restoring previous executable'; }; sleep 1
   done
 fi
 install -m 600 "$stage/release.json" "$dir/release-next.json"
 mv -f "$dir/release-next.json" "$dir/release.json"
 trap - EXIT
 prune_backups
 printf 'Updated %s; previous executable retained at %s\n' "$name" "$old"
 ;;
 *) usage; exit 1;;
esac
