#!/bin/bash
set -e

FEDORA_VERSION=$(rpm -q --qf '%{version}' fedora-release)
TARGET_VERSION=$((FEDORA_VERSION + 1))

function pause() {
   read -p "Hit Enter to continue or Ctrl + C to cancel."
}

function continue_or_skip() {
   echo -e $1
   echo "This step is highly recomended, but can be safely skipped."
   ANSWER='XXX'
   while [ "$ANSWER" != "" -a "$ANSWER" != "S" ] ; do
     read -p "Hit Enter to continue, Ctrl + C to cancel or S + Enter to skip. " ANSWER
     ANSWER=$(echo $ANSWER | tr "[:lower:]" "[:upper:]")
   done
}

function install_deps() {
  # TODO add -q to all yum and create some kind of progress metter
  # but now be verbose
  rpm -q rpmconf >/dev/null || yum install -y rpmconf
  rpm -q yum-utils >/dev/null || yum install -y yum-utils
}

function upgrade_before_upgrade() {
  continue_or_skip "\nGoing to run 'yum upgrade' before upgrading."
  if [ "$ANSWER" != "S" ] ; then
    yum upgrade
  fi
}

function rpmconf_before_upgrade() {
  continue_or_skip "\nGoing to resolve old .rpmsave and .rpmnew files before upgrading."
  if [ "$ANSWER" != "S" ] ; then
    rpmconf -fvimdiff -a
  fi
}

function import_keys() {
  rpm --import /usr/share/fedora-upgrade/keys/RPM-GPG-KEY-fedora-$TARGET_VERSION-primary
  if [ -f /etc/yum.repos.d/rpmfusion-free.repo ]; then
    rpm --import /usr/share/fedora-upgrade/keys/RPM-GPG-KEY-rpmfusion-free-fedora-$TARGET_VERSION
  fi
  if [ -f /etc/yum.repos.d/rpmfusion-nonfree.repo ]; then
    rpm --import /usr/share/fedora-upgrade/keys/RPM-GPG-KEY-rpmfusion-nonfree-fedora-$TARGET_VERSION
  fi
}

function install_base() {
  continue_or_skip "\nGoing to install missing packages from group 'Minimal Install'"
  if [ "$ANSWER" != "S" ] ; then
    yum groupupdate 'Minimal Install'
  fi
}

function rpmconf_after_upgrade() {
  continue_or_skip "\nGoing to resolve .rpmsave and .rpmnew files after upgrade."
  if [ "$ANSWER" != "S" ] ; then
    rpmconf -fvimdiff -a
    rpmconf --clean
  fi
}

function reset_service_priorities() {
  continue_or_skip "\nGoing to reset priorities of services."
  if [ "$ANSWER" != "S" ] ; then
    ( cd /etc/rc.d/init.d;
      for f in *; do
        [ -x $f ] && /sbin/chkconfig $f resetpriorities || :
      done # TODO - the same for systemd unit files
    )
  fi
}

function unwanted_packages() {
  LAST=$1
  continue_or_skip "\nThere can be some packages which are now orphan, do you want to see them?"
  RESULT=0
  for i in $(seq 10 $LAST); do
    rpm -qa | grep fc$i && RESULT=1
  done
  if [ 0$RESULT -eq 1 ]; then
    echo "These packages are very probably orphan. You may want to remove them."
  fi
}

function is_prerelease() {
  # will print string "--enablerepo=updates-testing" if this is prerelease, "" otherwise
  local RELEASE=$1
  if yumdownloader --disablerepo=* --enablerepo=fedora --releasever=19 fedora-release --urls | tail -n 1 | wget -q -i - -O - | rpm2cpio | cpio -i --quiet --to-stdout - ./etc/yum.repos.d/fedora-updates-testing.repo | grep 'enabled=1' >/dev/null; then
    echo "--enablerepo=updates-testing"
  else
    echo ""
  fi
}

if [ 0$FEDORA_VERSION -eq 17 ]; then
  echo "Going to upgrade your Fedora to version 18."
  echo "You may want to read Release Notes:"
  echo "  http://docs.fedoraproject.org/release-notes/"
  echo "Warning: This is unofficial upgrade tool. Official tool is 'fedup'."
  echo "         While author of fedora-upgrade thinks fedora-upgrade is better, it is"
  echo "         not officially tested by FedoraQA."
  pause

  # upgrade to latest due BZ 844167
  yum upgrade selinux-policy -y >/dev/null

  install_deps
  upgrade_before_upgrade
  rpmconf_before_upgrade

  if [ -f /etc/sysconfig/desktop ]; then
    . /etc/sysconfig/desktop
    if [ "$DISPLAYMANAGER" = GNOME ]; then
      preferred=gdm
    elif [ "$DISPLAYMANAGER" = KDE ]; then
      preferred=kdm
    elif [ "$DISPLAYMANAGER" = XDM ]; then
      preferred=xdm
    elif [ -n "$DISPLAYMANAGER" ]; then
      # TODO - some heuristics?
      true
    fi
  fi

  import_keys

  yum update -q yum
  yum clean -q dbcache rpmdb plugins metadata
  yum --releasever=18 --disableplugin=presto distro-sync
  rpm --rebuilddb

  install_base
  # TODO call package-cleanup --orphans or yum list extras and ask to remove it
  # but the list has a lot of false negatives

  rpmconf_after_upgrade
  reset_service_priorities

  # https://fedoraproject.org/wiki/Features/DisplayManagerRework
  if [ -n "$preferred" ]; then
    systemctl enable --force ${preferred}.service
  else
    echo
    echo Could not determine your display manager
    echo If you are using display manager, you have to run manualy:
    echo systemctl enable --force your-display-manager.service
    echo
  fi

  unwanted_packages 17

  echo
  echo You sucessfullly upgraded to Fedora 18.
  echo Reboot is strongly suggested.
elif [ 0$FEDORA_VERSION -eq 18 ]; then
  echo "Going to upgrade your Fedora to version 19."
  echo "You may want to read Release Notes:"
  echo "  http://docs.fedoraproject.org/release-notes/"
  pause

  if [ "$DISPLAY" != "" ]; then
    cat << WARNING
It seems you are running upgrade from XWindows. You should switch to VT,
because session information will be lost during upgrade and it may lead
to unpredictable things.
See https://bugzilla.redhat.com/show_bug.cgi?id=962983
WARNING
    pause
  fi

  install_deps
  upgrade_before_upgrade
  rpmconf_before_upgrade
  import_keys

  yum update -q yum
  yum clean -q dbcache rpmdb plugins metadata
  enable_updates=$(is_prerelease 19)
  yum --releasever=19 --disableplugin=presto $enable_updates distro-sync

  install_base

  rpmconf_after_upgrade
  reset_service_priorities
  unwanted_packages 18

  echo
  echo You sucessfullly upgraded to Fedora 19.
  echo Reboot is strongly suggested.
elif [ 0$FEDORA_VERSION -eq 19 ]; then
  echo "Going to upgrade your Fedora to version 20."
  echo "You may want to read Release Notes:"
  echo "  http://docs.fedoraproject.org/release-notes/"
  pause

  install_deps
  upgrade_before_upgrade
  rpmconf_before_upgrade
  import_keys

  yum update -q yum
  yum clean -q dbcache rpmdb plugins metadata
  enable_updates=$(is_prerelease 20)
  yum --releasever=20 --disableplugin=presto $enable_updates distro-sync

  install_base

  rpmconf_after_upgrade
  reset_service_priorities
  unwanted_packages 19

  echo
  echo You sucessfullly upgraded to Fedora 20.
  echo Reboot is strongly suggested.
elif [ 0$FEDORA_VERSION -eq 20 ]; then
  echo "Going to upgrade your Fedora to rawhide."
  echo "Fedora 20 is currently under development."
  echo "Are you sure?"
  pause

  install_deps
  rpmconf_before_upgrade

  yum update -q yum
  yum clean -q dbcache rpmdb plugins metadata
  yum --releasever=rawhide --disableplugin=presto distro-sync --nogpgcheck

  install_base

  rpmconf_after_upgrade
  reset_service_priorities

  echo
  echo You sucessfullly upgraded to Fedora 20.
  echo Reboot is strongly suggested.
else
  echo Upgrading from version $FEDORA_VERSION is not supported.
  exit 1
fi
