#!/bin/bash

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

function show_welcome {
  FROM=$1
  TO=$2
  clear;
  echo "Neptune Upgrade Script";
  echo "-----------------------------";
  echo "This will upgrade $FROM to $TO."; 
  echo -e "\033[1mPlease make sure to have a working internet connection, enough free space and a plugged in power cord on your laptop\033[0m"; 
  echo ""; 
  echo "Press any key to continue or CTRL+C to abort" ; 
  read FOO
  echo "Upgrade process starts...";
}

function create_sourceslist_backup {
  # Create Backup in case anything goes wrong
  find /etc/apt/sources.list.d/ -exec cp {}{,.bak} \;
  cp /etc/apt/sources.list{,.bak}
}


function change_repo_component {
  OLD=$1
  NEW=$2
  REPOLIST=$3
  if [ -n $OLD ] && [ -n $REPOLIST ]; then
    sed -i -e "s/$OLD/$NEW/" $REPOLIST
  fi
}

function remove_repo_component {
  COMP=$1
  REPOLIST=$2
  change_repo_component "$COMP" "" "$REPOLIST" 
}

function prepare_repos {
  # Add main repo
  echo "deb https://download.neptuneos.com/repos/neptune5/repo-kde/ stretch main" > /etc/apt/sources.list.d/neptune.list

  # Add Neptune gpg key
  wget https://neptuneos.com/files/NeptuneOS/Files/neptune.gpg.key -O /tmp/neptune.key
  apt-key add /tmp/neptune.key
}

function upgrade_packages {
  # Manual upgrade packages and remove older ones if necessary
  apt-get update
  apt-get remove kde-l10n-*
  apt-get install -y -f apt-transport-https
}

function update_system {
  apt-get update
  apt-get dist-upgrade -y -f -o Dpkg::Options::="--force-confnew"

  # Make sure everything is consistent
  apt-get install -y -f -o Dpkg::Options::="--force-confnew" -o Dpkg::Options::="--force-overwrite"

  # Just to be sure everything is up to date
  apt-get dist-upgrade -y -f -o Dpkg::Options::="--force-confnew" -o Dpkg::Options::="--force-overwrite"

  echo " ";
  echo "Upgrade finished. Please reboot.";
}

check_root
show_welcome "KDE Plasma 5.8 LTS" "KDE PLasma 5.12 LTS"
create_sourceslist_backup
upgrade_packages
prepare_repos
update_system
