#!/bin/bash
set -e

# NetProtego CPE Agent Installer (Alpine Linux Support)
# Usage: ./install.sh [version] [channel]

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 "Installing NetProtego CPE Agent ($VERSION)..."

# Determine download URL
if [ "$CHANNEL" == "dev" ]; then
    DOWNLOAD_URL="$BASE_URL/unstable/latest/cpe-agent"
    SERVICE_URL="$BASE_URL/unstable/latest/netprotego-cpe.init"
elif [ "$VERSION" == "latest" ]; then
    DOWNLOAD_URL="$BASE_URL/stable/latest/cpe-agent"
    SERVICE_URL="$BASE_URL/stable/latest/netprotego-cpe.init"
else
    # Specific version: Binary from version folder, Service from latest
    DOWNLOAD_URL="$BASE_URL/stable/$VERSION/cpe-agent"
    SERVICE_URL="$BASE_URL/stable/latest/netprotego-cpe.init"
fi

echo "Downloading from $DOWNLOAD_URL..."

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

# Install OpenRC Init Script
echo "Installing OpenRC init script..."
curl -L -o /etc/init.d/netprotego-cpe "$SERVICE_URL"
chmod +x /etc/init.d/netprotego-cpe

# Add to default runlevel and start
rc-update add netprotego-cpe default
rc-service netprotego-cpe restart

echo "Installation complete. Service started."
rc-service netprotego-cpe status
