#!/bin/bash
# PNetLab v5 (Bionic/Focal) Upgrade Script
# This script upgrades an existing v4 installation to v5.
# If v4 is not found, it installs it first.
# Mirror: pnetlab-mirrors.labhub.eu.org

set -e

GREEN='\033[32m'
RED='\033[31m'
NO_COLOR='\033[0m'

# Check OS version
OS_VER=$(lsb_release -rs)
if [ "$OS_VER" != "18.04" ] && [ "$OS_VER" != "20.04" ]; then
    echo -e "${RED}This upgrade is for Ubuntu 18.04 or 20.04 only. Found: $OS_VER${NO_COLOR}"
    exit 1
fi

# Determine Suite based on OS
SUITE="bionic"
[ "$OS_VER" == "20.04" ] && SUITE="focal"

# Step 1: Ensure PNetLab v4 (Base) is installed
if ! dpkg -l | grep -q pnetlab; then
    echo -e "${GREEN}PNetLab not found. Installing base first...${NO_COLOR}"
    
    # Configure Mirror
    wget -qO- https://pnetlab-mirrors.labhub.eu.org/pubkey.asc | gpg --dearmor | sudo tee /usr/share/keyrings/pnetlab-archive-keyring.gpg > /dev/null
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/pnetlab-archive-keyring.gpg] https://pnetlab-mirrors.labhub.eu.org/ bionic/" | sudo tee /etc/apt/sources.list.d/pnetlab.list
    
    sudo apt-get update
    sudo apt-get install -y pnetlab
fi

# Step 2: Perform v5 Upgrade
URL_PNET_UPGRADE=https://pnetlab-mirrors.labhub.eu.org/bionic/5.3.13.zip

echo -e "${GREEN}Backing up labs from /opt/unetlab/labs/ ...${NO_COLOR}"
sudo tar -czvf /root/labs-$(date +%Y%m%d%H%M).tgz /opt/unetlab/labs/ || echo "Backup failed, continuing..."

echo -e "${GREEN}Downloading v5 upgrade package...${NO_COLOR}"
rm -f 5.3.13.zip*
wget --content-disposition -q --show-progress $URL_PNET_UPGRADE

echo -e "${GREEN}Extracting and applying upgrade...${NO_COLOR}"
sudo rm -rf ./upgrade
unzip -o 5.3.13.zip -d ./upgrade >/dev/null
sudo chmod 755 -R upgrade
find upgrade -type f -print0 | xargs -0 dos2unix 2>&1 >/dev/null || true
sudo ./upgrade/upgrade

echo -e "${GREEN}PNetLab v5 upgrade complete!${NO_COLOR}"
