#!/bin/bash
set -e

# NetProtego CPE Agent Updater (Alpine Linux Support)

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

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

echo "Updating NetProtego CPE Agent..."

# Stop service
echo "Stopping service..."
rc-service netprotego-cpe stop || true

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

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

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

# Restart service
echo "Restarting service..."
rc-service netprotego-cpe start

echo "Update complete."
rc-service netprotego-cpe status
