#!/bin/bash
set -e

REPO="https://repo.mspmanage.cloud"
VERSION="latest"

detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        echo "$ID"
    else
        echo "unknown"
    fi
}

OS=$(detect_os)

case "$OS" in
    rocky|rhel|almalinux|centos|fedora)
        echo "[INFO] Detected RPM-based system"
        ARCH=$(uname -m)
        URL="$REPO/rpm/mspmanage-agent-$VERSION.$ARCH.rpm"
        echo "[INFO] Downloading $URL"
        curl -fsSL -o /tmp/mspmanage-agent.rpm "$URL"
        rpm -ivh /tmp/mspmanage-agent.rpm
        rm /tmp/mspmanage-agent.rpm
        ;;
    ubuntu|debian)
        echo "[INFO] Detected DEB-based system"
        ARCH=$(dpkg --print-architecture)
        URL="$REPO/deb/mspmanage-agent-${VERSION}_${ARCH}.deb"
        echo "[INFO] Downloading $URL"
        curl -fsSL -o /tmp/mspmanage-agent.deb "$URL"
        dpkg -i /tmp/mspmanage-agent.deb
        rm /tmp/mspmanage-agent.deb
        ;;
    *)
        echo "[ERROR] Unsupported OS: $OS"
        echo "Download manually from $REPO"
        exit 1
        ;;
esac

echo "[INFO] Installation complete"
echo "[INFO] Copy config: cp /etc/mspmanage/agent.conf.example /etc/mspmanage/agent.conf"
echo "[INFO] Edit config: /etc/mspmanage/agent.conf"
echo "[INFO] Start service: systemctl enable --now mspmanage-agent"
