#!/bin/bash

set -e

. /etc/os-release

if [ "${VERSION_CODENAME}" != "focal" ]; then
	echo "ERROR: This script is designed to run on Ubuntu focal (20.04)" >&2
	exit 1
fi

if [ $(id -u) != 0 ]; then
	echo "ERROR: This script must run as root" >&2
	exit 1
fi

if ! which do-release-upgrade >/dev/null 2>&1; then
	echo "ERROR: do-release-upgrade not found.  Please install ubuntu-release-upgrader-core" >&2
	exit 1
fi

flavors="aws azure hw iso kvm next vmware"

unset tnsr_config_flavor
for flavor in ${flavors}; do
	if dpkg -s tnsr-config-${flavor} >/dev/null 2>&1; then
		tnsr_config_flavor=${flavor}
		break
	fi
done

if [ -z "${tnsr_config_flavor}" ]; then
	echo "ERROR: Unable to identify installed tnsr-config flavor" >&2
	exit 1
fi

apt_config="/etc/apt/sources.list.d/tnsr-${tnsr_config_flavor}.list"

if [ ! -f ${apt_config} ]; then
	echo "ERROR: tnsr-config source list (${apt_config}) not found" >&2
	exit 1
fi

if [ -f /var/run/reboot-required.pkgs ]; then
	if [ $(cat /var/run/reboot-required.pkgs | wc -l) -gt 0 ]; then
		echo "You have not rebooted after updating.  Do it now and try again." >&2
		exit 1
	fi
fi

apt-get update
upgradable=$(apt list --upgradable 2>/dev/null | tail -n +2 | wc -l)

if [ ${upgradable} -gt 0 ]; then
	echo "Please install all available updates on current system and try again after that" >&2
	exit 1
fi

for f in /etc/apt/sources.list.d/*.list; do
	if [ "${f}" = "${apt_config}" ]; then
		cp ${f} ${f}.bak
		sed -i -e 's/20\.04/22.04/g; s/focal/22.04/g' ${apt_config}
	else
		mv ${f} ${f}.disabled
	fi
done

dpkg -P --force-all netgate-libyang

if dpkg -l | grep -q netgate-libyang; then
	  echo "ERROR: netgate-libyang was not removed" >&2
	exit 1
fi

echo 'DPkg::options { "--force-confdef"; "--force-confold"; }' > /etc/apt/apt.conf.d/tnsr-upgrade

do-release-upgrade -f DistUpgradeViewNonInteractive --allow-third-party -m server

rm -f /etc/apt/apt.conf.d/tnsr-upgrade
