#!/bin/bash
# InventoryPlus ServiceAgent - macOS Installer Script

set -e

echo "==================================================="
echo "  Installing InventoryPlus ServiceAgent on macOS"
echo "==================================================="

APP_DIR="/Library/Application Support/InventoryPlus/ServiceAgent"
PLIST_DST="/Library/LaunchDaemons/com.inventoryplus.serviceagent.plist"

# Detect Architecture
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ];  then
    SRC_DIR="./arm64"
    echo "Detected Apple Silicon (M1/M2/M3/M4)"
else
    SRC_DIR="./x64"
    echo "Detected Intel Mac"
fi

# 1. Stop existing service if running
if sudo launchctl list | grep -q "com.inventoryplus.serviceagent"; then
    echo "Stopping existing ServiceAgent daemon..."
    sudo launchctl unload "$PLIST_DST" 2>/dev/null || true
fi

# 2. Copy application files
echo "Installing application files to $APP_DIR..."
sudo mkdir -p "$APP_DIR"
sudo mkdir -p "$APP_DIR/logs"
sudo cp -R $SRC_DIR/* "$APP_DIR/"
sudo chmod +x "$APP_DIR/ServiceAgent"

# 3. Configure HTTPS Certificate Trust
echo "Configuring HTTPS certificate trust..."
dotnet dev-certs https --trust 2>/dev/null || true

# 4. Register & Start launchd Background Daemon
echo "Registering background daemon service..."
sudo cp ./com.inventoryplus.serviceagent.plist "$PLIST_DST"
sudo chown root:wheel "$PLIST_DST"
sudo chmod 644 "$PLIST_DST"
sudo launchctl load -w "$PLIST_DST"

echo "==================================================="
echo "  InventoryPlus ServiceAgent Installed Successfully!"
echo "  Service Status: Active (Runs automatically on boot)"
echo "==================================================="
