#!/bin/bash

# CompArt Assistencia Remota - Instalador Mac
# Configura o RustDesk com o servidor da CompArt Systems

SERVER="116.203.52.248"
KEY="zVb4+91030NUGfXgmm33k+zQ0+ak9o2DBzBIZjk8xv8="
API_URL="https://admin.compartsystems.pt/api/clients?secret=cs-remote-2026-xK9mP"
CONFIG_DIR="$HOME/Library/Preferences/org.rustdesk.RustDesk"
CONFIG_FILE="$CONFIG_DIR/RustDesk2.toml"

echo "============================================"
echo "  CompArt Assistencia Remota - Instalacao"
echo "============================================"
echo ""

# Check if RustDesk is installed
if [ ! -d "/Applications/RustDesk.app" ]; then
    echo "[ERRO] RustDesk nao encontrado em /Applications/"
    echo "Por favor:"
    echo "1. Abra o ficheiro .dmg que descarregou"
    echo "2. Arraste o RustDesk para a pasta Aplicacoes"
    echo "3. Execute este script novamente"
    echo ""
    read -p "Pressione Enter para sair..."
    exit 1
fi

echo "[OK] RustDesk encontrado em /Applications/"
echo ""

# Create config directory
mkdir -p "$CONFIG_DIR"

# Write RustDesk config
echo "Escrevendo configuracao..."
cat > "$CONFIG_FILE" << EOF
[options]
custom-rendezvous-server = "${SERVER}"
key = "${KEY}"
EOF

# Also write to system-level config if possible
SYS_CONFIG="/Library/Preferences/org.rustdesk.RustDesk/RustDesk2.toml"
sudo mkdir -p /Library/Preferences/org.rustdesk.RustDesk 2>/dev/null
sudo tee "$SYS_CONFIG" > /dev/null << EOF
[options]
custom-rendezvous-server = "${SERVER}"
key = "${KEY}"
EOF
sudo chmod 444 "$SYS_CONFIG" 2>/dev/null

# Set permissions
chmod 444 "$CONFIG_FILE"

echo "[OK] Configuracao escrita com sucesso!"
echo ""

# Kill RustDesk if running
echo "A reiniciar RustDesk..."
pkill -x RustDesk 2>/dev/null
sleep 2

# Open RustDesk
open /Applications/RustDesk.app
sleep 5

# Try to get RustDesk ID
echo "A obter ID RustDesk..."
RUSTDESK_ID=$(/Applications/RustDesk.app/Contents/MacOS/RustDesk --get-id 2>/dev/null | head -1 | tr -d '[:space:]')

if [ -z "$RUSTDESK_ID" ] || [ ${#RUSTDESK_ID} -lt 6 ]; then
    sleep 3
    RUSTDESK_ID=$(/Applications/RustDesk.app/Contents/MacOS/RustDesk --get-id 2>/dev/null | head -1 | tr -d '[:space:]')
fi

# Report ID to server
if [ -n "$RUSTDESK_ID" ] && [ ${#RUSTDESK_ID} -ge 6 ]; then
    HOSTNAME=$(scutil --get ComputerName 2>/dev/null || echo "Mac")
    echo "A registar assistencia (ID: $RUSTDESK_ID)..."
    curl -s -X POST "$API_URL" \
        -H "Content-Type: application/json" \
        -d "{\"rustdesk_id\": \"$RUSTDESK_ID\", \"hostname\": \"$HOSTNAME\"}" > /dev/null 2>&1

    # Save ID for heartbeat
    mkdir -p /usr/local/share/compart 2>/dev/null
    echo "$RUSTDESK_ID" > /usr/local/share/compart/rustdesk_id.txt 2>/dev/null

    # Create LaunchAgent for heartbeat (every 5 min)
    LAUNCH_AGENT="$HOME/Library/LaunchAgents/com.compart.heartbeat.plist"
    cat > "$LAUNCH_AGENT" << PLIST
<?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.compart.heartbeat</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>-c</string>
        <string>ID=\$(cat /usr/local/share/compart/rustdesk_id.txt 2>/dev/null); if echo "\$ID" | grep -qE '^[0-9]{6,}$'; then curl -s -X POST "$API_URL" -H "Content-Type: application/json" -d "{\\\"rustdesk_id\\\": \\\"\$ID\\\", \\\"hostname\\\": \\\"$(scutil --get ComputerName 2>/dev/null || echo Mac)\\\"}" > /dev/null 2>&1; fi</string>
    </array>
    <key>StartInterval</key>
    <integer>300</integer>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
PLIST
    launchctl load "$LAUNCH_AGENT" 2>/dev/null
fi

echo ""
echo "============================================"
echo "  Instalacao concluida com sucesso!"
echo "============================================"
echo ""
if [ -n "$RUSTDESK_ID" ] && [ ${#RUSTDESK_ID} -ge 6 ]; then
    echo "O seu ID RustDesk: $RUSTDESK_ID"
    echo ""
fi
echo "Partilhe o seu ID e palavra-passe com o"
echo "tecnico da CompArt para receber assistencia."
echo ""
echo "Telefone/WhatsApp: +351 933 946 917"
echo "Website: www.compartsystems.pt"
echo ""

read -p "Pressione Enter para fechar..."