#!/usr/bin/env bash

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)

# Define log file path in the same directory as the script
LOG_FILE="$SCRIPT_DIR/agent-update.log"

# Clear the log file at the start
> "$LOG_FILE"

# Attempt to redirect both stdout and stderr to the log file
if ! exec > >(tee -a "$LOG_FILE") 2>&1; then
    echo "Warning: Failed to set up logging to $LOG_FILE" >&2
fi

isOSX=0
if [[ ("$OSTYPE" == "darwin"*) ]]; then
    isOSX=1
fi

svc=0

if [ $isOSX -eq 1 ]; then
    # --- macOS DAEMON vs AGENT DETECTION ---
    if [ -f /Library/LaunchDaemons/com.ispy.agent.dvr.plist ]; then
        svc=0
        echo "Service is installed as a System Daemon on macOS"
        MAC_PLIST_PATH="/Library/LaunchDaemons/com.ispy.agent.dvr.plist"
        MAC_DOMAIN="system"
    elif [ -f ~/Library/LaunchAgents/com.ispy.agent.dvr.plist ]; then
        svc=0
        echo "Service is installed as a User Agent on macOS"
        MAC_PLIST_PATH="$HOME/Library/LaunchAgents/com.ispy.agent.dvr.plist"
        MAC_DOMAIN="gui/$(id -u)"
    else
        svc=1
        echo "Service not installed on macOS (Defaulting to User Agent for paths)"
        MAC_PLIST_PATH="$HOME/Library/LaunchAgents/com.ispy.agent.dvr.plist"
        MAC_DOMAIN="gui/$(id -u)"
    fi
else
    echo "Setting UDP Buffer size defaults"
    sysctl -w net.core.rmem_max=16777216 || true
    sysctl -w net.core.rmem_default=8388608 || true

    # Check if the coturn service is active
    if systemctl is-active --quiet coturn; then
        echo "Coturn is running. Stopping the service..."
        systemctl stop coturn
        echo "Coturn service stopped."

        echo "Disabling coturn service... (using inbuilt turn server)"
        systemctl disable coturn
        echo "Coturn service disabled."
    else
        echo "Coturn service is not running."
    fi

    if systemctl is-enabled --quiet AgentDVR.service; then
        svc=0
        echo "Service found on Linux"
    else
        svc=1
        echo "Service not found on Linux"
    fi
fi

# ---------------------------------------------------------
# UPDATE LOGIC FORK
# ---------------------------------------------------------
if [ "$1" == "-update" ]; then
    if [ -f AgentDVR.zip ]; then
        echo "Installing update"

        if [ $isOSX -eq 1 ]; then
            # --- MAC UPDATE PATH (Safe Bundle Replacement) ---
            echo "Extracting macOS App Bundle..."
            # Unzip to a temporary directory in the "Garage"
            unzip -q -o AgentDVR.zip -d AgentUpdateTemp
            rm -f AgentDVR.zip

            # Delete the old signed bundle completely
            echo "Removing old AgentService.app..."
            rm -rf "AgentService.app"

            # Move the newly downloaded, freshly signed bundle into place
            echo "Installing new AgentService.app..."
            mv AgentUpdateTemp/AgentService.app .
            rm -rf AgentUpdateTemp

            echo "Restoring execution permissions..."
            chmod +x "AgentService.app/Contents/MacOS/Agent"
            chmod +x "AgentService.app/Contents/MacOS/TURN/turnserver" 2>/dev/null || true
            find . -name "*.sh" -exec chmod +x {} \;
            
            # --- MIGRATION MAGIC: Rewrite the LaunchAgent/Daemon Plist ---
            echo "Updating macOS Launch configuration..."
            
            AGENT_PATH="$SCRIPT_DIR/AgentService.app/Contents/MacOS/Agent"
            DYLD_LIB_DIR="$SCRIPT_DIR/AgentService.app/Contents/MacOS"
            DYLD_LIBRARY_PATH="$SCRIPT_DIR/ffmpeg7/lib:$DYLD_LIB_DIR/ffmpeg7/lib:$DYLD_LIB_DIR:/usr/local/lib:/opt/homebrew/lib"
            LOGS_DIR="$HOME/Library/Logs"

            # Overwrite the old plist with the new Thick Bundle paths
            cat <<EOF > "$MAC_PLIST_PATH"
<?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>Label</key>
    <string>com.ispy.agent.dvr</string>
    <key>ProcessType</key>
    <string>Interactive</string>
    <key>Nice</key>
    <integer>-10</integer>
    <key>LowPriorityIO</key>
    <false/>
    <key>ProgramArguments</key>
    <array>
        <string>$AGENT_PATH</string>
    </array>
    <key>NSHighResolutionCapable</key>
    <string>True</string>
    <key>EnvironmentVariables</key>
    <dict>
        <key>PATH</key>
        <string>/usr/bin:/bin:/usr/sbin:/sbin</string>
        <key>DYLD_LIBRARY_PATH</key>
        <string>$DYLD_LIBRARY_PATH</string>
    </dict>
    <key>RunAtLoad</key><true/>
    <key>KeepAlive</key><true/>
    <key>StandardOutPath</key><string>$LOGS_DIR/agentdvr.log</string>
    <key>StandardErrorPath</key><string>$LOGS_DIR/agentdvr.error.log</string>
    <key>WorkingDirectory</key><string>$SCRIPT_DIR</string> 
</dict>
</plist>
EOF
            
            # Clean up the old legacy binary so it doesn't cause confusion later
            rm -f "$SCRIPT_DIR/Agent"

        else
            # --- LINUX UPDATE PATH (Legacy Raw Extraction) ---
            unzip -o AgentDVR.zip
            rm -f AgentDVR.zip

            chmod +x "$SCRIPT_DIR/Agent"
            find . -name "*.sh" -exec chmod +x {} \;
            chmod +x "$SCRIPT_DIR/TURN/turnserver"
        fi
    else
        echo "Update file not found. Use the web portal to update Agent"
    fi
fi

# Install plugins
if [ "$1" == "-plugins" ]; then 
    if [ -d "Plugins/$2" ]; then
        cd Plugins
        cd "$2"
        if [ -f plugin.zip ]; then
            unzip -o plugin.zip
            echo "Unzipped"
            rm -f plugin.zip
            echo "Removed archive"
            
            # If on Mac, downloaded plugins might get quarantined by Gatekeeper. 
            # We silently strip the quarantine flag recursively so they load properly.
            if [ $isOSX -eq 1 ]; then
                xattr -rc . 2>/dev/null || true
            fi
            cd ..
        else
            echo "Plugin archive not found"
        fi
        cd ..
    else
        echo "Plugins directory not found or incorrect path: Plugins/$2"
        exit 1
    fi
fi

# =========================================================
# ASYNCHRONOUS RESTART BLOCK
# =========================================================
if [ $isOSX -eq 1 ]; then
    echo "Queueing macOS service reload in the background..."
    nohup bash -c "
        sleep 4
        launchctl bootout \"$MAC_DOMAIN\" \"$MAC_PLIST_PATH\" 2>/dev/null || launchctl unload \"$MAC_PLIST_PATH\" 2>/dev/null
        sleep 1
        launchctl bootstrap \"$MAC_DOMAIN\" \"$MAC_PLIST_PATH\" 2>/dev/null || launchctl load \"$MAC_PLIST_PATH\" 2>/dev/null
        
        if [ \$? -ne 0 ]; then
            \"$SCRIPT_DIR/AgentService.app/Contents/MacOS/Agent\" &
        fi
    " >/dev/null 2>&1 &

    echo "macOS update staged successfully. Exiting script to allow graceful app shutdown."
    exit 0
else
    if [ $svc -eq 0 ]; then
        echo "Queueing Agent service restart on Linux..."
        systemctl --no-block restart AgentDVR.service
        
        echo "Linux update staged successfully. Exiting script to allow graceful app shutdown."
        exit 0
    else
        echo "Service not found, starting Agent manually on Linux in background..."
        nohup "$SCRIPT_DIR/Agent" >/dev/null 2>&1 &
        exit 0
    fi
fi