#!/bin/bash
set -e

# NetProtego POP Agent Installer
# Usage: ./install.sh [version] [channel]
# channel: latest or dev (default: latest)

VERSION=${1:-latest}
CHANNEL=${2:-latest} # 'latest' implies production latest, 'dev' implies dev-latest
BASE_URL="https://download.netprotego.com/pop"

if [ "$EUID" -ne 0 ]; then 
  echo "Please run as root"
  exit 1
fi

echo "Installing NetProtego POP Agent ($VERSION)..."

# Determine download URL
if [ "$CHANNEL" == "dev" ]; then
    DOWNLOAD_URL="$BASE_URL/unstable/latest/pop-agent"
    SERVICE_URL="$BASE_URL/unstable/latest/netprotego-pop.service"
elif [ "$VERSION" == "latest" ]; then
    DOWNLOAD_URL="$BASE_URL/stable/latest/pop-agent"
    SERVICE_URL="$BASE_URL/stable/latest/netprotego-pop.service"
else
    # Specific version: Binary from version folder, Service from latest (as version folder only has binaries)
    DOWNLOAD_URL="$BASE_URL/stable/$VERSION/pop-agent"
    SERVICE_URL="$BASE_URL/stable/latest/netprotego-pop.service"
fi

echo "Downloading from $DOWNLOAD_URL..."

# Download Binary
curl -L -o /usr/local/bin/pop-agent "$DOWNLOAD_URL"
chmod +x /usr/local/bin/pop-agent

# Download Service File
curl -L -o /etc/systemd/system/netprotego-pop.service "$SERVICE_URL"

# Reload and Start
systemctl daemon-reload
systemctl enable netprotego-pop
systemctl restart netprotego-pop

echo "Installation complete. Service started."
systemctl status netprotego-pop --no-pager
