#!/bin/bash

#RHELUP_CONFIG="/var/lib/system-upgrade/upgrade.conf"
RHELUP_CONFIG="/root/preupgrade/upgrade.conf"
RPM_QA="centos7_rpm_qa.log"
CENTOSSIGNED_PKGS="rpm_centossigned.log"
RPM_ERASE="rpm -e --nodeps"

function remove_package {
    rpm -q $1
    if [ $? -eq 0 ]; then
        $RPM_ERASE $1
    fi
}
echo "Remove preupgrade-assistant package"
remove_package preupgrade-assistant-contents-users
remove_package preupgrade-assistant-contents
remove_package preupgrade-assistant-ui
remove_package preupgrade-assistant

rpm -qa | grep "el6" > $RPM_QA 2>/dev/null
# First we remove all debug-info packages and 32multilib packages automatically
echo "Remove all debuginfo and 32bit multilib packages ..."
for line in `cat $RPM_QA`; do
    NAME=`rpm -q --qf '%{NAME}' $line`
    # Check for debuginfo packages
    echo "$NAME" | grep "debuginfo" 1>/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "Package $NAME will be uninstalled."
        $RPM_ERASE $NAME
        continue
    fi
    # check for 32bit multilib packages
    ARCH=`rpm -q --qf '%{NAME}' $line`
    echo "$ARCH" | grep "i{356}86" 1>/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "32bit multilib package $NAME will be uninstalled."
        $RPM_ERASE $NAME
        continue
    fi
done
echo "Remove all debuginfo and 32bit multilib packages done"
cat $RHELUP_CONFIG
if [ ! -f "$RHELUP_CONFIG" ]; then
    echo "redhat-upgrade-tool config file $RHELUP_CONFIG was not found on system."
    echo "No CentOS 6 packages will be deleted."
    exit 0
fi

if [ ! -f "$CENTOSSIGNED_PKGS" ]; then
    echo "File with CentOS signed packages is missing."
    echo "No CentOS 6 packages will be deleted."
    exit 0
fi

#Check whether $RHELUP_CONFIG contains rows
#[postupgrade]
#cleanup = True

#NEW_LINE=`sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' -e 's/[[:space:]]*$//g' < $RHELUP_CONFIG`
#RESULT=`echo "$NEW_LINE" | sed -r '/^\[postupgrade\]$/ {
#N
#/^cleanup=.*/ {
#/^cleanup=True$/p
#}
#}'`

grep '[postupgrade]' $RHELUP_CONFIG 1>/dev/null 2>&1
if [ $? -ne 0 ]; then
   echo "redhat-upgrade-tool-cli was not called with option --cleanup."
   exit 0
fi
grep '^cleanup[[:space:]]*=[[:space:]]*True' $RHELUP_CONFIG 1>/dev/null 2>&1
if [ $? -ne 0 ]; then
   echo "redhat-upgrade-tool-cli was not called with option --cleanup."
   exit 0
fi
for line in `cat $RPM_QA`; do
    NAME=`rpm -q --qf '%{NAME}' $line`
    grep $NAME $CENTOSSIGNED_PKGS 2>/dev/null 1>/dev/null
    if [ $? -ne 0 ]; then
       echo "The $NAME package is not signed by CentOS and will not be erased."
    else
       $RPM_ERASE $NAME
    fi
done
exit 0
