#!/bin/sh
set -e
PATH="/usr/bin:/bin:/usr/sbin:/sbin"
export PATH

AFMP_HOME="/Library/Application Support/AFMP"
PLIST="/Library/LaunchDaemons/com.bepa.afmp.plist"
RUNTIME="$AFMP_HOME/runtime/application-server/AFMP-Application-Server"
DATA_DIR="$AFMP_HOME/storage"
PORT="8787"
LAN_ENABLED="0"
LAN_IP=""
BIND_HOST="127.0.0.1"
COMPUTER_NAME="$(scutil --get LocalHostName 2>/dev/null || hostname -s 2>/dev/null || echo localhost)"

mkdir -p "$AFMP_HOME/storage/database" "$AFMP_HOME/storage/logs"
chmod +x "$RUNTIME"

is_private_ipv4() {
    printf '%s\n' "$1" | awk -F. '
        NF == 4 && $1 ~ /^[0-9]+$/ && $2 ~ /^[0-9]+$/ && $3 ~ /^[0-9]+$/ && $4 ~ /^[0-9]+$/ &&
        $1 <= 255 && $2 <= 255 && $3 <= 255 && $4 <= 255 &&
        ($1 == 10 || ($1 == 172 && $2 >= 16 && $2 <= 31) || ($1 == 192 && $2 == 168)) { valid=1 }
        END { exit(valid ? 0 : 1) }
    '
}

DEFAULT_INTERFACE="$(route -n get default 2>/dev/null | awk '/interface:/{print $2; exit}')"
case "$DEFAULT_INTERFACE" in
    ""|lo*|utun*|awdl*|llw*|bridge*|vmnet*) DEFAULT_INTERFACE="" ;;
esac

if [ -n "$DEFAULT_INTERFACE" ]; then
    CANDIDATE_IP="$(ipconfig getifaddr "$DEFAULT_INTERFACE" 2>/dev/null || true)"
    if is_private_ipv4 "$CANDIDATE_IP"; then
        LAN_ENABLED="1"
        LAN_IP="$CANDIDATE_IP"
        BIND_HOST="0.0.0.0"
    fi
fi

# The macOS application firewall is process based. If it is enabled, add the
# bundled server before exposing the listener. A failed rule safely falls back
# to localhost rather than leaving an unapproved LAN listener behind.
FIREWALL_TOOL="/usr/libexec/ApplicationFirewall/socketfilterfw"
if [ "$LAN_ENABLED" = "1" ] && [ -x "$FIREWALL_TOOL" ] && "$FIREWALL_TOOL" --getglobalstate 2>/dev/null | grep -qi enabled; then
    if ! "$FIREWALL_TOOL" --add "$RUNTIME" >/dev/null 2>&1 || ! "$FIREWALL_TOOL" --unblockapp "$RUNTIME" >/dev/null 2>&1; then
        LAN_ENABLED="0"
        LAN_IP=""
        BIND_HOST="127.0.0.1"
        printf '%s\n' "AFMP could not add the macOS firewall permission and will use local-only access." >> "$DATA_DIR/logs/network-profile.log"
    fi
fi

"$RUNTIME" php-cli "$AFMP_HOME/app/Console/configure_onprem.php" \
    "--platform=macos" \
    "--install-dir=$AFMP_HOME" \
    "--data-dir=$DATA_DIR" \
    "--host=$BIND_HOST" \
    "--port=$PORT" \
    "--lan-enabled=$LAN_ENABLED" \
    "--lan-ip=$LAN_IP" \
    "--computer-name=$COMPUTER_NAME" \
    "--cloud-auth-url=https://app.bepa-se.com/sso/authorize"

"$RUNTIME" php-cli "$AFMP_HOME/app/Console/bootstrap_sqlite.php"

if launchctl print system/com.bepa.afmp >/dev/null 2>&1; then
    launchctl bootout system "$PLIST" || true
fi

launchctl bootstrap system "$PLIST"
launchctl enable system/com.bepa.afmp
launchctl kickstart -k system/com.bepa.afmp

printf '%s LAN=%s interface=%s ip=%s bind=%s port=%s\n' \
    "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$LAN_ENABLED" "${DEFAULT_INTERFACE:-none}" "${LAN_IP:-none}" "$BIND_HOST" "$PORT" \
    >> "$DATA_DIR/logs/network-profile.log"

# Installer.app runs this script as root. Open the branded completion page in
# the logged-in user's GUI session when possible; installation remains valid if
# no interactive user is present (for example an MDM deployment).
CONSOLE_USER="$(stat -f '%Su' /dev/console 2>/dev/null || true)"
if [ -n "$CONSOLE_USER" ] && [ "$CONSOLE_USER" != "root" ] && [ "$CONSOLE_USER" != "loginwindow" ]; then
    CONSOLE_UID="$(id -u "$CONSOLE_USER" 2>/dev/null || true)"
    if [ -n "$CONSOLE_UID" ]; then
        launchctl asuser "$CONSOLE_UID" sudo -u "$CONSOLE_USER" open "$AFMP_HOME/OnPrem-Status.html" >/dev/null 2>&1 || true
    fi
fi

exit 0
