#!/bin/bash
set -e

trap 'echo "=========================================\n  ❌ Error: installation did not complete successfully.\n  Check the messages above for details.\n========================================="' ERR

# Check if the installer is running as administrator (root)
if [ "$EUID" -ne 0 ]; then
  echo "⚠️  Please run the installer as administrator:"
  echo "sudo ./install.sh"
  exit 1
fi

echo "========================================="
echo "  Installing CipherLAN for Linux..."
echo "========================================="

# 1. Stop and uninstall the previous service if it exists
if [ -f /opt/CipherLAN/cipherlan-daemon ]; then
    echo "[*] Stopping previous CipherLAN service..."
    /opt/CipherLAN/cipherlan-daemon stop 2>/dev/null || true
    /opt/CipherLAN/cipherlan-daemon uninstall 2>/dev/null || true
fi

# 2. Create the application folder
echo "[*] Copying files to /opt/CipherLAN..."
mkdir -p /opt/CipherLAN
cp cipherlan /opt/CipherLAN/
cp cipherlan-daemon /opt/CipherLAN/
cp assets/icon.png /opt/CipherLAN/ 2>/dev/null || cp assets/icon.ico /opt/CipherLAN/

# 3. Set execute permissions
echo "[*] Setting execute permissions..."
chmod +x /opt/CipherLAN/cipherlan
chmod +x /opt/CipherLAN/cipherlan-daemon

# 4. Install and start the service
echo "[*] Installing and starting the background service..."
/opt/CipherLAN/cipherlan-daemon install
/opt/CipherLAN/cipherlan-daemon start

# 5. Create the Linux desktop launcher
echo "[*] Creating desktop launcher..."
cp CipherLAN.desktop /usr/share/applications/
chmod 644 /usr/share/applications/CipherLAN.desktop

echo "========================================="
echo "  ✅ CipherLAN installation finished."
echo "  Check that everything is working before you use it."
echo "  If any error occurred, review the messages above."
echo "========================================="
