#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
if [[ ${EUID} -ne 0 ]]; then echo 'Run with sudo on the FreePBX server.' >&2; exit 1; fi
if ! command -v fwconsole >/dev/null 2>&1; then echo 'This does not appear to be a FreePBX installation.' >&2; exit 1; fi
if ! command -v php >/dev/null 2>&1; then echo 'PHP CLI is required.' >&2; exit 1; fi
if [[ ! -f pbx-config.json ]]; then echo 'Missing configuration.' >&2; exit 1; fi
printf '\nPBX Launchpad installer: %s\n' "${1:---dry-run}"
echo 'IMPORTANT: Back up your PBX in the FreePBX Backup & Restore module first.'
echo 'This package never modifies trunks, inbound routes, or the FreePBX database directly.'
echo 'Email transport, IVR menus, and DID destinations require manual completion.'
echo
if [[ -z "${PBX_URL:-}" ]]; then read -rp 'FreePBX HTTPS base URL (e.g. https://pbx.example.com): ' PBX_URL; fi
if [[ -z "${PBX_API_CLIENT_ID:-}" ]]; then read -rp 'FreePBX OAuth client ID: ' PBX_API_CLIENT_ID; fi
if [[ -z "${PBX_API_CLIENT_SECRET:-}" ]]; then read -srp 'FreePBX OAuth client secret: ' PBX_API_CLIENT_SECRET; echo; fi
export PBX_URL PBX_API_CLIENT_ID PBX_API_CLIENT_SECRET
umask 077
php apply.php "${1:---dry-run}"
