#!/bin/bash

DISTRO=`cat /etc/*-release | grep -w "NAME=" | awk '{print $1}' | cut -d '"' -f2`
VERSION=`cat /etc/*-release | grep "VERSION_ID=" | awk '{print $1}' | cut -d '"' -f2`
if [[ $DISTRO =~ .*"Ubuntu".* ]]
then
   pubkey_check=`gpg --list-keys`
   if [[ ${pubkey_check} == *"DSG Manageability Linux"* ]]; then
     echo "Removing Public key...." 
     gpg --batch --yes --delete-key "DSG Manageability Linux"
     echo "Public key removed...." 
   fi
else
   pubkey_check=`rpm -q gpg-pubkey --qf '%{NAME}-%{VERSION}-%{RELEASE}\t%{SUMMARY}\n'`
   if [[ ${pubkey_check} == *"DSG Manageability Linux"* ]]; then
     echo "Removing Public key...."
     pubkey=`rpm -q gpg-pubkey --qf '%{NAME}-%{VERSION}-%{RELEASE}\t%{SUMMARY}\n' | grep "DSG Manageability Linux" | awk '{print $1}'`	
     rpm -e ${pubkey}
     echo "Public key removed...."
   fi
fi
if [[ $DISTRO =~ .*"Red".* ]]
then
   if [[ $VERSION < 9 ]]
   then
      VERSION=8
   else
      VERSION=9
   fi
   UTIL_NAME=`find RHEL/RHEL${VERSION} -name *.rpm | awk -F "/" '{print $3}' | awk -F "-" '{print $1}'`
   rpm -e ${UTIL_NAME}

elif [[ $DISTRO =~ .*"Cent".* ]]
then 
   if [[ $VERSION < 8 ]]
   then
      VERSION=7
   else
      VERSION=8
   fi
   UTIL_NAME=`find RHEL/RHEL${VERSION} -name *.rpm | awk -F "/" '{print $3}' | awk -F "-" '{print $1}'`
   rpm -e ${UTIL_NAME}

elif [[ $DISTRO =~ .*"Ubuntu".* ]]
then
   if [[ $VERSION < 22 ]]
   then
      VERSION=20
   else
      VERSION=22
   fi
   UTIL_NAME=`find UBUNTU/UBUNTU${VERSION} -name *.deb | awk -F "/" '{print $3}' | awk -F "-" '{print $1}'`
   dpkg -r $UTIL_NAME
elif [[ $DISTRO =~ .*"SLES".* ]]
then
   if [[ $VERSION < 15 ]]
   then
      VERSION=12
   else
      VERSION=15
   fi
   UTIL_NAME=`find SLES/SLES${VERSION} -name *.rpm | awk -F "/" '{print $3}' | awk -F "-" '{print $1}'`
   rpm -e $UTIL_NAME

elif [[ $DISTRO =~ .*"SLED".* ]]
then
   if [[ $VERSION < 15 ]]
   then
      VERSION=12
   else
      VERSION=15
   fi
   UTIL_NAME=`find SLES/SLES${VERSION} -name *.rpm | awk -F "/" '{print $3}' | awk -F "-" '{print $1}'`
   rpm -e $UTIL_NAME

else
   echo "OS is not supported"
fi

if [ $? = 0 ]
then
   echo "$UTIL_NAME is uninstalled successfully" 
else
   echo "$UTIL_NAME may not be installed" 
fi
