#!/bin/bash
# Run on alpine-be as root after syncing backend tree.
set -euo pipefail

ROOT="${1:-/var/www/localhost/htdocs/apps/app/androidcast_project/android_cast/examples/crash_reporter/backend}"
CFG="$ROOT/config/config.php"
SUDOERS_DST="/etc/sudoers.d/androidcast-wg"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [[ ! -f "$CFG" ]]; then
  echo "Missing $CFG" >&2
  exit 1
fi

php81 -r '
$path = $argv[1];
$c = require $path;
if (!is_array($c)) { fwrite(STDERR, "config.php must return array\n"); exit(1); }
if (isset($c["remote_access"]) && is_array($c["remote_access"]) && ($c["remote_access"]["wg_server_public_key"] ?? "") !== "") {
    echo "remote_access already configured\n";
    exit(0);
}
$c["remote_access"] = array_merge($c["remote_access"] ?? [], [
    "wg_endpoint" => "ra.apps.f0xx.org:45340",
    "wg_server_public_key" => "EV2nnwHH7xe3jA5J46Rjtl8ao+ybZinibKg2Hy83GBw=",
    "wg_interface" => "wg0",
    "wg_server_allowed_ips" => "172.200.2.1/32",
    "wg_client_ip_prefix" => "172.200.2.",
    "wg_client_ip_min" => 10,
    "wg_client_ip_max" => 250,
    "wg_set_prefix" => "sudo -n ",
    "provision_peers" => true,
    "require_wg_tools" => true,
    "session_ttl_s" => 3600,
    "min_poll_interval_s" => 45,
]);
$export = var_export($c, true);
file_put_contents($path, "<?php\nreturn " . $export . ";\n");
echo "Wrote remote_access into config.php\n";
' "$CFG"

install -m 440 "$SCRIPT_DIR/alpine-be-sudoers-wg" "$SUDOERS_DST"
visudo -cf "$SUDOERS_DST"
echo "Installed $SUDOERS_DST"

rc-service php-fpm81 restart 2>/dev/null || rc-service php-fpm restart 2>/dev/null || true
echo "Restarted PHP-FPM"
