#!/bin/bash

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

if [ $# -eq 0 ]; then
echo "No release type passed."
exit 0
fi

if [[ $1 != "stable" && $1 != "nightly" ]]; then
  echo "Target release must be either stable or nightly"
  exit
fi

target_release=$1
smos=$(</etc/apt/sources.list.d/smos.list)
current_release="${smos##*/}"
current_release=($current_release)
current_release=${current_release[0]}

if [ $current_release == $target_release ]; then
  echo "Release is already" $target_release
  exit
fi

distro=$(lsb_release --codename | cut -f2)
packages="libindi1 libindi-data indi-* kstars-bleeding* phd2 ekoslive libstellarsolver* stellarmate* smoscore libsbig* libfli* libinovasdk* libnncam* libqsi* libricohcamerasdk* libstarshootg* libatik* libmicam* libpktriggercord libqhy* libfishcamp* libasi* libapogee* libtoupcam* libaltaircam* libkf5kdcraw* libraw* gwenview libgphoto* gphoto2 sane-utils colord kamera gvfs-backends libopencv-highguio* libopencv-videoio* libmallincam* libomegonprocam* libpigpiod* libplayerone* libsvbony*"

echo "Removing existing packages..."
apt-get -y remove $packages
echo "deb https://ppa.stellarmate.com/repos/apt/"$target_release $distro" main" > '/etc/apt/sources.list.d/smos.list'
echo "Updating new channel..."
apt-get update
echo "Installing new packages..."
apt-get -y -o Dpkg::Options::="--force-overwrite" -f install $packages
echo "Upgrading system..."
apt-get -y dist-upgrade
echo "All packages installed successfully"
