#!/bin/bash

#Preupgrade assistant performs system upgradability assessment
#and gathers information required for successful operating system upgrade.
#Copyright (C) 2013 Red Hat Inc.
#Petr Stodulka <pstodulk@redhat.com>
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
. /usr/share/preupgrade/common.sh
COMPONENT="distribution"
#END GENERATED SECTION

[ -f versions ] || {
  log_error "SystemVersion" "File 'versions' not found!"
  exit $RESULT_ERROR
}

QUERY_FORMAT="%{NAME}-%{VERSION}-%{RELEASE}\n"
ERROR_MSG="For right migration you need latest release of RHEL6 system. Please, update
your system to the last RHEL6 release and then run preupgrade-assistant again."
rm -f solution.txt
touch solution.txt

# check if the system is the last version release RHEL-6.x
# first line in versions!
rhel_version=$(cat /etc/redhat-release | sed -r "s/[a-zA-Z ]+([0-9.]+).*/\1/")
rhel_latest=$(cat versions | head -n 1 | grep "#\s*release:" | grep -oE "6\.[0-9][0-9]?")
[ -n "$rhel_latest" ] || {
  log_error "SystemVersion" "wrong file format: versions"
  exit $RESULT_ERROR
}

[ "$rhel_version" != "$rhel_latest" ] && {
  log_extreme_risk "This is not latest RHEL6 release!"
  exit $RESULT_FAIL
}

# check NVR some of the core packages
while read line; do
  echo $line | grep -q "^\s*#"
  [ $? -eq 0 ] && continue # comment lines
  [ -n "$line" ] || continue # empty line

  pkgname=$(echo $line | cut -d "=" -f 1 | sed -e "s/^\s*//" -e "s/\s*$//")
  pkg_nvr=$(echo $line | cut -d "=" -f 2 | sed -e "s/^\s*//" -e "s/\s*$//")

  # head because of multilib pkgs..you know.. x86_64 and i686 versions installed at once...
  pkg_nvr_installed=$(rpm -q --qf "${QUERY_FORMAT}" $pkgname | head -n 1)
  [ $? -ne 0 ] && {
    log_error "rpm" "package $pkgname is not installed or some else problem with rpm utility!"
    exit $RESULT_ERROR
  }

  ./rpmdev-vercmp "$pkg_nvr" "$pkg_nvr_installed" > /dev/null
  status=$?
  [ $status -ne 0 ] && [ $status -ne 11 ] && [ $status -ne 12 ] && {
    log_error "SystemVersion" "rpm versions can't be compared"
    exit $RESULT_ERROR
  }

  [ $status -eq 11 ] && {
    log_extreme_risk "This is not latest RHEL6 release!"
    echo "$ERROR_MSG" >> solution.txt
    exit $RESULT_FAIL
  }
done < versions

exit $RESULT_PASS
