#!/bin/bash

echo "This is an upgrade script for CentOS/Fedora."
echo "WARNING: Use with caution!"
echo "Press ENTER to continue or CTRL+C to stop."

read enter

ARCH=`uname -i`
ARGS="$@"

upgrade_centos() {
  CENTOS_RELEASE=`rpm -E %rhel`
  if [ "$CENTOS_RELEASE" = "6" ]; then
    yum install --enablerepo=upg -y \
      redhat-upgrade-tool preupgrade-assistant-contents
    rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
    UPG=`preupg -l`
    preupg -s $UPG
    echo "Press ENTER to upgrade or CTRL+C to stop."
    read enter
    centos-upgrade-tool-cli --network 7 \
      --instrepo=http://ftp.upjs.sk/pub/centos/7/os/$ARCH/
  else
    echo "Unknown CentOS version [$CENTOS_RELEASE]!"
    exit 2
  fi
}

dnf_upgrade() {
  rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-$FEDORA_NEXT-$ARCH
  dnf upgrade $ARGS
  dnf clean all
  dnf --releasever=$FEDORA_NEXT --setopt=deltarpm=false distro-sync $ARGS
}

upgrade_fedora() {
  FEDORA_RELEASE=`rpm -E %fedora`
  FEDORA_NEXT=$((FEDORA_RELEASE+1))
  if [ "$FEDORA_RELEASE" = "22" ]; then
    dnf_upgrade
  else
    echo "Unknown Fedora release [$FEDORA_RELEASE]!"
    exit 2
  fi
}

if [ -z "$STY" -a -z "$TMUX" ]; then
  echo "Please run this script under screen or tmux."
  exit 1
fi

if [ -f /etc/centos-release ]; then
  upgrade_centos
elif [ -f /etc/fedora-release ]; then
  upgrade_fedora
fi
