#!/bin/bash
set -euo pipefail

# DEBUG=1  # Enable for testing
DEBUG=0 # Clear installation

# Paths
TARGET_DIR="/Library/Application Support/SafeDNS"
TARGET_FILE="$TARGET_DIR/config.plist"
STATUS_FILE="/Library/Group Containers/group.com.safedns.agent.macos.enterprise/MDMStatus.txt"
LOG_FILE="/var/log/safedns-installer.log"

# AuthKey
AUTH_KEY="Enter here your AuthKey"

# Device name
DEVICE_NAME=$(scutil --get ComputerName 2>/dev/null || hostname)

# Profile version
PROFILE_VERSION=$(date '+%Y.%m.%d')

# DoH test settings 
UPSTREAM_MODE="udp" 
STRICT_ENCRYPTED_DNS="false"
DOH_ENDPOINT="https://doh.safedns.com/dns-query"
DOT_HOST="doh.safedns.com"
DOT_PORT="853"

# Logging helpers
log_file() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') [$1] $2" >> "$LOG_FILE"
}

log_info() { echo "== $1"; log_file "INFO" "$1"; }
log_ok()   { echo "✔  $1"; log_file "OK" "$1"; }
log_warn() { echo "⚠  $1"; log_file "WARN" "$1"; }
log_err()  { echo "✘  $1"; log_file "ERR" "$1"; }

log_info "Starting SafeDNS configuration plist creation"

# Ensure target directory exists
mkdir -p "$TARGET_DIR"
chown root:wheel "$TARGET_DIR"
chmod 755 "$TARGET_DIR"
log_ok "Directory prepared: $TARGET_DIR"

# Validate mode
case "$UPSTREAM_MODE" in
    auto|udp|doh|dot)
        log_ok "Upstream mode validated: $UPSTREAM_MODE"
        ;;
    *)
        log_err "Invalid UPSTREAM_MODE: $UPSTREAM_MODE"
        exit 1
        ;;
esac

case "$STRICT_ENCRYPTED_DNS" in
    true|false)
        log_ok "Strict encrypted DNS validated: $STRICT_ENCRYPTED_DNS"
        ;;
    *)
        log_err "Invalid STRICT_ENCRYPTED_DNS value: $STRICT_ENCRYPTED_DNS"
        exit 1
        ;;
esac

# Write plist
printf '%s\n' "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
    <key>AuthKeyBase64</key>
    <string>$AUTH_KEY</string>
    <key>deviceName</key>
    <string>$DEVICE_NAME</string>
    <key>profileVersion</key>
    <string>$PROFILE_VERSION</string>
    <key>UpstreamMode</key>
    <string>$UPSTREAM_MODE</string>
    <key>StrictEncryptedDNS</key>
    <$STRICT_ENCRYPTED_DNS/>
    <key>DoHEndpoint</key>
    <string>$DOH_ENDPOINT</string>
    <key>DoTHost</key>
    <string>$DOT_HOST</string>
    <key>DoTPort</key>
    <integer>$DOT_PORT</integer>
    <key>CaptivePortalHandling</key>
    <string>enabled</string>
    <key>BridgeUnifiedLogsToFile</key>
    <true/>
    <key>BridgeIntervalMinutes</key>
    <integer>5</integer>
    <key>BridgeSubsystem</key>
    <string>com.safedns.agent.SafeDNSMacProxy</string>
    <key>BridgeLogFileName</key>
    <string>safedns-unified.log</string>
    <key>BridgeMaxFileSizeBytes</key>
    <integer>5242880</integer>
    <key>BridgeMaxFiles</key>
    <integer>5</integer>
    <key>BridgeInitialLookbackSeconds</key>
    <integer>3000</integer>
</dict>
</plist>" > "$TARGET_FILE"

chown root:wheel "$TARGET_FILE"
chmod 644 "$TARGET_FILE"  # ONLY for testing
log_ok "config.plist written to $TARGET_FILE"
log_ok "Configured UpstreamMode=$UPSTREAM_MODE"
log_ok "Configured StrictEncryptedDNS=$STRICT_ENCRYPTED_DNS"
log_ok "Configured DoHEndpoint=$DOH_ENDPOINT"
log_ok "Configured DoTHost=$DOT_HOST"
log_ok "Configured DoTPort=$DOT_PORT"

# Validate and write status
if plutil -lint "$TARGET_FILE" >/dev/null 2>&1; then
    mkdir -p "$(dirname "$STATUS_FILE")"
    {
        echo "Product: SafeDNS"
        echo "Action: install"
        echo "Status: install_completed"
        echo "DeviceName: $DEVICE_NAME"
        echo "ProfileVersion: $PROFILE_VERSION"
        echo "Timestamp: $(date '+%Y-%m-%d %H:%M:%S')"
        echo "LogFile: $LOG_FILE"
        echo "UpstreamMode: $UPSTREAM_MODE"
        echo "StrictEncryptedDNS: $STRICT_ENCRYPTED_DNS"
        echo "DoHEndpoint: $DOH_ENDPOINT"
        echo "DoTHost: $DOT_HOST"
        echo "DoTPort: $DOT_PORT"
    } > "$STATUS_FILE"
    log_ok "SafeDNS config.plist created successfully"
    log_ok "Install status written to $STATUS_FILE"
else
    mkdir -p "$(dirname "$STATUS_FILE")"
    {
        echo "Product: SafeDNS"
        echo "Action: install"
        echo "Status: install_failed"
        echo "DeviceName: $DEVICE_NAME"
        echo "ProfileVersion: $PROFILE_VERSION"
        echo "Timestamp: $(date '+%Y-%m-%d %H:%M:%S')"
        echo "LogFile: $LOG_FILE"
        echo "UpstreamMode: $UPSTREAM_MODE"
        echo "StrictEncryptedDNS: $STRICT_ENCRYPTED_DNS"
        echo "DoHEndpoint: $DOH_ENDPOINT"
        echo "DoTHost: $DOT_HOST"
        echo "DoTPort: $DOT_PORT"
    } > "$STATUS_FILE"
    log_err "Invalid config.plist format"
    exit 1
fi

log_ok "SafeDNS install script completed"