#!/bin/bash
set -e

# NetProtego POP Agent Updater
# Usage: ./update.sh [version] [channel]

VERSION=${1:-latest}
CHANNEL=${2:-latest}
BASE_URL="https://download.netprotego.com/pop"

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

echo "Updating NetProtego POP Agent..."

# Stop service
echo "Stopping service..."
systemctl stop netprotego-pop

# Backup
if [ -f /usr/local/bin/pop-agent ]; then
    mv /usr/local/bin/pop-agent /usr/local/bin/pop-agent.bak
fi

# Determine download URL
if [ "$CHANNEL" == "dev" ]; then
    DOWNLOAD_URL="$BASE_URL/unstable/latest/pop-agent"
elif [ "$VERSION" == "latest" ]; then
    DOWNLOAD_URL="$BASE_URL/stable/latest/pop-agent"
else
    DOWNLOAD_URL="$BASE_URL/stable/$VERSION/pop-agent"
fi

# Download new binary
echo "Downloading new version..."
curl -L -o /usr/local/bin/pop-agent "$DOWNLOAD_URL"
chmod +x /usr/local/bin/pop-agent

# Restart service
echo "Restarting service..."
systemctl start netprotego-pop

echo "Update complete."
systemctl status netprotego-pop --no-pager
