#! /bin/bash
# Copyright 1999-2008, Intel(R) Corporation, All Rights Reserved
# This script uinstalls Intel(R) compilers and related packages.


#Check if the USER is root
IS_USER_ROOT ()
{
   if [ "${USER}x" != "rootx" ] ; then
       if [ ! -w /dev ] ; then
            ROOT_USER=0
       else
            ROOT_USER=1
       fi
   else
          ROOT_USER=1
   fi
}

## Check whether RPM is present or not.
IS_RPM_PRESENT ()
{
    #Check if we can get a shared lock on rpm database
    rpm -q rpm &> /dev/null
    RPM_NOT_FOUND=$?
}


# Figure out the location of intel_sdp_products database.
GET_FLATFILE_DB_LOCATION ()
{
    if [ "$ROOT_USER" = 1 ]; then
         DB_DIR_PREFIX="/opt/intel"
    else
         DB_DIR_PREFIX=""
         DB_DIR_PREFIX="$(echo ~)/intel"
         if [ "$DB_DIR_PREFIX" = "/root" ] || [ "$DB_DIR_PREFIX" = "/" ] || [ "$DB_DIR_PREFIX" = "" ] || [ "$DB_DIR_PREFIX" = "/intel" ]; then
             DB_DIR_PREFIX="/opt/intel"
         fi
    fi

    if [ "$INTEL_SDP_PRODUCTS_DB" = "" ]; then
           INTEL_SDP_PRODUCTS_DB="$DB_DIR_PREFIX/intel_sdp_products.db"
    fi
}


## Is EP installed? If yes, then uninstall it.
GIVE_EP_UNINSTALL_CHOICE ()
{
    if [ -f "$SCRIPT_DIR/EPuninstall.sh" ]; then
        if [ -f "$DB_DIR_PREFIX/EclipseTags.cfg" ] &&  cat "$DB_DIR_PREFIX/EclipseTags.cfg"  | egrep -i -e "ECLIPSE" -e "JROCKIT" -e "CDT" &> /dev/null ; then  
    		if [ $DISPLAY_HEADER = "1" ] ; then
       			echo
       			echo "Which of the following would you like to uninstall?"
       			DISPLAY_HEADER=0 
    		fi
            	INDEX="$(($INDEX+1))"
	    	echo "$INDEX.    Uninstall Eclipse Package."
	    	EP_INSTALLED=1
	else
            	EP_INSTALLED=0
	fi
    else
         EP_INSTALLED=0
    fi 
}


UNINSTALL_ICCE_RPM_AND_ITS_DEPENDENCIES ()
{
	ISUBHE_RPM_DEPENDENCY=""
	ISUBHE_RPM_DEPENDENCY="$(rpm -qa | grep 'intel-isubhe101015')"
	rpm "$USER_ARGUMENTS" "$CHOSEN_RPM"
	RETURN_VAL=$?
	if [ -n "$ISUBHE_RPM_DEPENDENCY" ]; then
		rpm "$USER_ARGUMENTS" "$ISUBHE_RPM_DEPENDENCY"
		RETURN_VAL=$?
	fi
}


UNINSTALL_IDB_RPM_AND_ITS_DEPENDENCIES ()
{
	IDB_IDE_RPM_DEPENDENCY=""
	IDB_IDE_RPM_DEPENDENCY="$(rpm -qa | grep 'intel-idb_ide101015')"
	if [ -n "$IDB_IDE_RPM_DEPENDENCY" ]; then
		rpm "$USER_ARGUMENTS"  "$IDB_IDE_RPM_DEPENDENCY"
		RETURN_VAL=$?
	fi
	rpm "$USER_ARGUMENTS" "$CHOSEN_RPM"
	RETURN_VAL=$?
}

UNINSTALL_EIDB_RPM_AND_ITS_DEPENDENCIES ()
{
	EIDB_IDE_RPM_DEPENDENCY=""
	EIDB_IDE_RPM_DEPENDENCY="$(rpm -qa | grep 'intel-idb_ide101015')"
	if [ -n "$EIDB_IDE_RPM_DEPENDENCY" ]; then
		rpm "$USER_ARGUMENTS"  "$EIDB_IDE_RPM_DEPENDENCY"
		RETURN_VAL=$?
	fi
	rpm "$USER_ARGUMENTS" "$CHOSEN_RPM"
	RETURN_VAL=$?
}


UNINSTALL_ICC_RPM_AND_ITS_DEPENDENCIES ()
{
	ICC_IDE_RPM_DEPENDENCY=""
	ISUBH_RPM_DEPENDENCY=""
	ICC_IDE_RPM_DEPENDENCY="$(rpm -qa | grep 'intel-icc_ide101015')"
	ISUBH_RPM_DEPENDENCY="$(rpm -qa | grep 'intel-isubh101015')"
	if [ -n "$ICC_IDE_RPM_DEPENDENCY" ]; then
		rpm "$USER_ARGUMENTS"  "$ICC_IDE_RPM_DEPENDENCY"
		RETURN_VAL=$?
	fi
	rpm "$USER_ARGUMENTS" "$CHOSEN_RPM"
	RETURN_VAL=$?
	if [ -n "$ISUBH_RPM_DEPENDENCY" ]; then
		rpm "$USER_ARGUMENTS" "$ISUBH_RPM_DEPENDENCY"
		RETURN_VAL=$?
	fi
}

# Remove chosen RPM.
DO_RPM_UNINSTALL ()
{
    INDEX=0
    DISPLAY_HEADER=0  
    for INSTALLED_RPM in $@ ; do
     	DISPLAY_HEADER=1
    done
    
    if [ $DISPLAY_HEADER = "1" ] ; then
       echo
       echo "Which of the following would you like to uninstall?"
       DISPLAY_HEADER=0 
    fi

    for INSTALLED_RPM in $@ ; do
        INDEX="$(($INDEX+1))"
	echo -n "$INDEX.   "
	rpm -qi "$INSTALLED_RPM" | grep Summary | cut -d: -f2-3
    done
    GIVE_EP_UNINSTALL_CHOICE
    MAX_INDEX=$INDEX
    if [ $MAX_INDEX -ge 1 ] &> /dev/null ; then
    	echo "x.    Exit"
    	echo -n "Please make a selection   :   "
	REPEAT_LOOP=1
        while [ "$REPEAT_LOOP" = "1" ]
	do
    		read CHOSEN_INDEX &> /dev/null
    		if [ "$CHOSEN_INDEX" = x ] &>/dev/null ; then
			echo "Exiting..."
			exit 0
    		elif [ $CHOSEN_INDEX -ge 1 ] &> /dev/null && [ $CHOSEN_INDEX -eq $MAX_INDEX ] &> /dev/null && [ $EP_INSTALLED = "1" ] &> /dev/null ; then
			"$SCRIPT_DIR/EPuninstall.sh"
			REPEAT_LOOP=0
    		elif [ $CHOSEN_INDEX -ge 1 ] &> /dev/null && [ $CHOSEN_INDEX -le $MAX_INDEX ] &> /dev/null ; then
			REPEAT_LOOP=0
			CHOSEN_RPM="$(echo $INSTALLED_RPM_LIST | cut -d' ' -f"$CHOSEN_INDEX")"
			CHOSEN_FULL_NAME="$(rpm -qi $CHOSEN_RPM | grep Summary | cut -d: -f2-3)"
			DEFAULT_ARGUMENTS='-e'
			echo
			echo -n "What RPM options do you want to use to "
			echo -n "uninstall$CHOSEN_FULL_NAME [$DEFAULT_ARGUMENTS]?   :   "
			read USER_ARGUMENTS &> /dev/null
			if [ -z "$USER_ARGUMENTS" ] &> /dev/null ; then
	    			USER_ARGUMENTS="$DEFAULT_ARGUMENTS"
			fi
			echo -n "Uninstalling $CHOSEN_FULL_NAME..."
			
			if echo  "$CHOSEN_RPM" | egrep -e 'intel-icc101015' &> /dev/null; then
        			UNINSTALL_DOC_LINKS
			fi
			if echo  "$CHOSEN_RPM" | grep -i 'intel-icc101015' &> /dev/null; then
				UNINSTALL_ICC_RPM_AND_ITS_DEPENDENCIES
			elif echo  "$CHOSEN_RPM" | grep -i 'intel-icce101015' &> /dev/null; then
				UNINSTALL_ICCE_RPM_AND_ITS_DEPENDENCIES
			elif echo  "$CHOSEN_RPM" | grep -i 'intel-iidb101015' &> /dev/null; then
				UNINSTALL_IDB_RPM_AND_ITS_DEPENDENCIES
			elif echo  "$CHOSEN_RPM" | grep -i 'intel-eidb101015' &> /dev/null; then
				UNINSTALL_EIDB_RPM_AND_ITS_DEPENDENCIES
			else
				rpm "$USER_ARGUMENTS" "$CHOSEN_RPM"
				RETURN_VAL=$?
			fi
			if [ "$RETURN_VAL" = 0 ]; then
	    			echo "  Successful."
			else
	    			echo "  Unsuccessful."
			fi
    		else
			REPEAT_LOOP=1
			echo
			echo "Inappropriate Choice. Try 1 - $MAX_INDEX, or x."
    			echo -n "Which would you like to uninstall?   :   "
    		fi
        done
     fi
}


RPM_BASED_UNINSTALL_CHOICES ()
{
    echo
    echo "Querying the RPM database for Intel(R) Compiler 10.1.015 and related software development products ..."
    while INSTALLED_RPM_LIST="$(rpm -qa | egrep 'intel-[ie](cc|idb|subh|cce|idbe)101015' | grep -v 'isubh' | grep -v 'icc_ide' | sort)" && [ -n "$INSTALLED_RPM_LIST" ] ; do
      	echo
    	DO_RPM_UNINSTALL $INSTALLED_RPM_LIST
    done
   
    ## This special call is required if all compiler components have 
    ## been uninstalled but EP has not been uninstalled yet.
    DO_RPM_UNINSTALL
    echo
    echo "RPM reports that no additional Intel(R) C/C++ 10.1.015 Compilers or related products are installed."
    echo
    if [ -f "$INTEL_SDP_PRODUCTS_DB" ]; then
	VAR="$(cat $INTEL_SDP_PRODUCTS_DB | egrep '<:')"
	if [ -n "$VAR" ]; then
    		echo
		echo "However, the uninstallation program has detected at least one instance"
		echo "of Intel(R) Compilers and related products that were installed without using RPM."
		echo "You can uninstall them by invoking the uninstall.sh script for that product version."
    		echo
    		echo
	fi
    fi
    	
}


UNINSTALL_DOC_LINKS ()
{
    local link_dir
    local link_path
    link_dir='/usr/share/doc'
    if echo "$CHOSEN_RPM" | grep 'icc101015' > /dev/null ; then
        link_path="$link_dir/intel-icc100-readme.txt"
    else
        link_path="$link_dir/intel-readme.txt"
    fi
    if [ -f "$link_path" ] ; then
        rm -f "$link_path"
    fi
}

###
###                                                                                                                 
## Main routine for flat file based Uninstallation.
NON_RPM_BASED_UNINSTALLATION ()
{
	#clear
        if [ -f "$INTEL_SDP_PRODUCTS_DB" ]; then
		while VAR="$(cat $INTEL_SDP_PRODUCTS_DB | egrep '<:')" && [ -n "$VAR" ]; 
		do
    			DISPLAY_NON_RPM_MENU
		done
        	DISPLAY_NON_RPM_MENU
	else
		if [ "$ROOT_USER" = 0 ] ; then
			echo "The uninstallation program did not find any instance of Intel(R) Compiler"
			echo "installed by this($USER) non root user."
			echo
			echo "If you performed any installation using root, you must become root"
			echo "to do the uninstallation."
			echo
			echo
		fi
		exit
	fi
}

REMOVE_EMPTY_DIRS ()
{
    local rootnodes="$@"
    local childnodes=''
    if [ -n "$rootnodes" ] ; then
        # find empty directories
        childnodes=$(find $rootnodes -empty -type d 2>&1)
        # if find returns an error
        if (($?)) ; then
            # display error messages
            echo -e "$childnodes" | \
                grep 'find:' | sed s@'^'@'REMOVE_EMPTY_DIRS: '@g
            # strip error messages from list of empty directories
            childnodes=$(echo "$childnodes" | grep -v 'find:')
        fi
        if [ -n "$childnodes" ] ; then
            # remove empty directories
            rmdir -p $childnodes > /dev/null 2>&1
        fi
    fi
}

UNINSTALL_NON_RPM () 
{
    PROD="$1"
    PACKAGEID="$(echo $PROD | cut -d':' -f2)"
    RPMNAME="$(echo $PROD | cut -d':' -f3)"
    LOCATION="$(echo $PROD | cut -d':' -f4)"
    FILE="$(echo $PROD | cut -d':' -f5)"
   
    if [ "$DEFAULT_MODE" != 1 ]; then
        echo "Uninstalling $RPMNAME" 
        echo "Removing files ..."
    fi
   
    if [ ! -f "$FILE" ]; then
	echo 
	echo
	echo " !!! Error !!!"
	echo "Uninstallation cannot continue for this component"
	echo "Missing $FILE"
	echo 
	echo
	return
    fi
    while read VAR;  do
        if [ ! -d "$VAR" ]; then
            rm -f "$VAR"
        fi
    done < $FILE
    rm -f $FILE
    
    if [ "$DEFAULT_MODE" != 1 ]; then
        echo "Removing only EMPTY directories ..."
    fi
    REMOVE_EMPTY_DIRS "$LOCATION"

    M_PROD=$(echo $PROD | sed s@'/'@'\\/'@g)            
        sed "/$M_PROD/D" $INTEL_SDP_PRODUCTS_DB > $INTEL_SDP_PRODUCTS_DB.new

    mv "$INTEL_SDP_PRODUCTS_DB" "$INTEL_SDP_PRODUCTS_DB.old"
    mv "$INTEL_SDP_PRODUCTS_DB.new" "$INTEL_SDP_PRODUCTS_DB"
    #echo
}


DISPLAY_NON_RPM_MENU () 
{
    	INSTALLED_PRODS=""
	INSTALLED_EP_PRODS=""
        INSTALLED_PRODS="$(cat $INTEL_SDP_PRODUCTS_DB | egrep '<:' | grep $THIS_PACKAGEID)"
	if [ -f "$DB_DIR_PREFIX/EclipseTags.cfg" ] ; then
	   INSTALLED_EP_PRODS="$(cat $DB_DIR_PREFIX/EclipseTags.cfg  | egrep -i -e 'ECLIPSE' -e 'JROCKIT' -e 'CDT')" 
    	fi
	INDEX=0
    	DISPLAY_HEADER=0 
       
	if [ "$INSTALLED_PRODS" = "" ] && [ "$INSTALLED_EP_PRODS" = ""  ] ; then
                if [ "$DEFAULT_MODE" != 1 ]; then
		    echo
		    echo
	   	    echo "The uninstallation program could not find Intel(R) Compilers"
		    echo -n "or related products installed"
		    if [ "$ROOT_USER" = 0 ] ; then
	                echo " by this($USER) non root user."
		        echo
		        echo "This could be because they have already been uninstalled."
		        echo
		        echo "If you installed any products as root user, you must become root and"
		        echo "and execute $SCRIPT again."	
		        echo
		    else
			    echo "."
			    echo 
		            echo "This could be because they have already been uninstalled."
		    fi
		fi
		exit
	fi
 
	if [ -f "$SCRIPT_DIR/EPuninstall.sh" ]; then
        	if [ -f "$DB_DIR_PREFIX/EclipseTags.cfg" ] &&  cat "$DB_DIR_PREFIX/EclipseTags.cfg"  | egrep -i -e "ECLIPSE" -e "JROCKIT" -e "CDT" &> /dev/null ; then
			DISPLAY_HEADER=1
		fi
	fi

        if [ -n "$INSTALLED_PRODS" ]; then
		DISPLAY_HEADER=1
        fi

    	if [ "$DISPLAY_HEADER" = 1 ] ; then
       		echo
       		echo "Which of the following would you like to uninstall?"
       		DISPLAY_HEADER=0 
    	fi
	#echo
	#if [ -n "$INSTALLED_PRODS" ]; then
	#   let "INDEX += 1"
	#   echo "$INDEX.    Uninstall All"
	#   UNINSTALL_ALL_CHOICE=1 	
	#fi
    	for PROD in $INSTALLED_PRODS; do
        	PACKAGEID="$(echo $PROD | cut -d':' -f2)"
        	RPMNAME="$(echo $PROD | cut -d':' -f3)"
        	LOCATION="$(echo $PROD | cut -d':' -f4)"
        	LOG_FILE="$(echo $PROD | cut -d':' -f5)"
        	UPDATE_DISPLAY_VARIABLES 
       	 	let "INDEX += 1"
        	echo "$INDEX.    $DISPLAY_NAME, Version $VERSION ($LOCATION)"
    	done
        GIVE_EP_UNINSTALL_CHOICE
    	MAX_INDEX=$INDEX 
        if [ "$MAX_INDEX" = 0 ]; then
		TINI_SCRIPT
        fi
    	echo "x.    Exit"
    	echo
    	echo -n "Please type a selection:    "
    	REPEAT_LOOP=1
    	while [ "$REPEAT_LOOP" = "1" ]; do
    		read CHOICE
        	REPEAT_LOOP=0
    		if [ "$CHOICE" = "x" ]; then
        		echo
        		echo
        		echo "Exiting uninstallation ..."   
        		exit
    		fi
    		if [ -n $CHOICE ] && [ $CHOICE -gt 0 ] &> /dev/null && [ $CHOICE -lt $(($INDEX+1)) ]; then
        		echo
    		else
			REPEAT_LOOP=1
        		echo
        		echo
        		echo "Inappropriate Choice. Try 1 - $INDEX, or x."
    			echo -n "Please type a selection:    "
    		fi
	done

         
    INDEX=0
    if [ $CHOICE -ge 1 ] && [ $CHOICE -eq $MAX_INDEX ] && [ $EP_INSTALLED = "1" ]; then
		"$SCRIPT_DIR/EPuninstall.sh"
    else
    	for PROD in $INSTALLED_PRODS; do
        	let "INDEX += 1"
        	#if [ "$CHOICE" = "0" ]; then
        	#    UNINSTALL_ALL_NON_RPM
        	#    TINI_SCRIPT
        	#fi
		if [ "$INDEX" = "$CHOICE" ]; then
        	    UNINSTALL_NON_RPM "$PROD"
        	fi
    	done
    fi	
}

UNINSTALL_ALL_RPM ()
{
    local UNINSTALL_ALL_RPM_LOG=/tmp/.$$.uninstall.log

    if [ "$VERBOSE_MODE" = 1 ]; then 
        echo "UNINSTALL_ALL_RPM()"
    fi
    rpm -e `rpm -qa | grep -e 'intel-' | grep -e '101015-10.1.015'` > /dev/null 2> $UNINSTALL_ALL_RPM_LOG
    RESULT=$?

    if [ "$RESULT" != 0 ]; then
        echo "$0: ERROR in UNINSTALL_ALL_RPM" >&2
        cat $UNINSTALL_ALL_RPM_LOG >&2
        exit 1
    else
        exit 0
    fi
    
}

UNINSTALL_ALL_NON_RPM ()
{
    INDEX=1
    INSTALLED_PRODS=""
    INSTALLED_PRODS="$(cat $INTEL_SDP_PRODUCTS_DB | egrep '<:' | grep $THIS_PACKAGEID)"
    for PROD in $INSTALLED_PRODS; do
        PACKAGEID="$(echo $PROD | cut -d':' -f2)"
        RPMNAME="$(echo $PROD | cut -d':' -f3)"
        LOCATION="$(echo $PROD | cut -d':' -f4)"
        LOG_FILE="$(echo $PROD | cut -d':' -f5)"
        UPDATE_DISPLAY_VARIABLES
        let "INDEX += 1"
    done
    let "INDEX -= 1"
                                                                                                                             
    for PROD in $INSTALLED_PRODS; do
        if [ "$VERBOSE_MODE" = "1" ]; then 
            echo "---------------------------------------------"
            echo "uninstalling $PROD from list $INSTALLED_PRODS"
            echo "---------------------------------------------"
        fi
        UNINSTALL_NON_RPM $PROD
    done
}


UPDATE_DISPLAY_VARIABLES ()
{
   PRODUCT=$(echo "$RPMNAME" | grep -o -E '(icc|idb)')
   VERSION=$(echo "$RPMNAME" | cut -d'-' -f3)
   ARCH=$(echo "$RPMNAME" | grep -o -E '(i386|ia64|em64t)')
   if echo "$PACKAGEID" | grep -E '<:l_[cf]c_b' > /dev/null ; then
           beta=' Beta'
   fi

   case "$PRODUCT" in
   icc )
        signon="Intel(R) C++ Compiler"
   ;;
   idb )
        signon="Intel(R) Debugger"
   ;;
   * )
        continue 
   ;;
   esac
   
   case "$ARCH" in
   i386 )
         signon="$signon for applications running on IA-32"
   ;;
   ia64 )
         signon="$signon for applications running on IA-64"
   ;;
   em64t )
         signon="$signon for applications running on Intel(R) 64"
   ;;
   * )
         continue ;;
   esac
   DISPLAY_NAME="$signon"
}


PROCESS_ARGS ()
{
    # --default  and --verbose added added
   if [ "$VERBOSE_MODE" = 1 ]; then echo "PROCESS_ARGS() - SCRIPT_ARGS=$SCRIPT_ARGS"; fi

    for THIS_ARG in $SCRIPT_ARGS
    do
        if [ "$VERBOSE_MODE" = 1 ]; then echo "PROCESS_ARGS() - THIS_ARG=$THIS_ARG"; fi
        case "$THIS_ARG" in
            --nonrpm )
                NONRPM_SWITCH=1
	        ;;
            --default )
                DEFAULT_MODE=1
	        ;;
            --verbose )
                VERBOSE_MODE=1
	        ;;
            --debug )
                DEBUG_MODE=1
		echo "DEBUG mode enabled"
	        ;;
            * )
                echo "Unknown option \'$SCRIPT_ARGS\'";
                echo
                echo
	       exit 1;;
            esac
    done
}


TINI_SCRIPT ()
{
    exit
}

####
# ----------------------------------------------------
# Uninstallation Starts here.
#-----------------------------------------------------
####

#clear
SCRIPT="$0"
SCRIPT_ARGS="$@"
ARGS_NUM="$#"
SCRIPT_DIR="$(dirname $SCRIPT)"

if [ "$SCRIPT_DIR" = "." ]; then
    SCRIPT_DIR="$(pwd)"
else
    cd $SCRIPT_DIR
    SCRIPT_DIR="$(pwd)"
fi

NONRPM_SWITCH=0
DEFAULT_MODE=0
VERBOSE_MODE=0
DEBUG_MODE=0
INTEL_SDP_PRODUCTS_DB=""
THIS_PACKAGEID=l_cc_p_10.1.015
## determine whether user is root or not.
PROCESS_ARGS
IS_USER_ROOT
IS_RPM_PRESENT
GET_FLATFILE_DB_LOCATION

# if DEFAULT_MODE then remove everything without noise unless error occurs
if [ "$DEFAULT_MODE" = 1 ] ; then
    if [ "$ROOT_USER" = 0 ] ; then
       if [ "$VERBOSE_MODE" = 1 ]; then 
           echo "non-RPM default mode"
           echo "executing UNINSTALL_ALL_NON_RPM"
       fi
       UNINSTALL_ALL_NON_RPM 
       exit 0
    elif  [ ! "$RPM_NOT_FOUND" = 0 ] || [ "$NONRPM_SWITCH" = 1 ]; then
       if [ "$VERBOSE_MODE" = 1 ]; then 
           echo "non-RPM default mode"
           echo "executing UNINSTALL_ALL_NON_RPM"
       fi
       UNINSTALL_ALL_NON_RPM 
       exit 0
    else 
       if [ "$VERBOSE_MODE" = 1 ]; then echo "RPM default mode"; fi
       UNINSTALL_ALL_RPM 
       exit 0
    fi 
    if [ "$VERBOSE_MODE" = 1 ]; then
        echo "uninstall -  default mode - exiting"
    fi
    exit 0
fi    



## If user is not root, perform uninstallation by querying the flat file database.
if [ "$ROOT_USER" = 0 ] ; then
	NON_RPM_BASED_UNINSTALLATION
else
	if  [ ! "$RPM_NOT_FOUND" = 0 ] || [ "$NONRPM_SWITCH" = 1 ]; then
		NON_RPM_BASED_UNINSTALLATION
	else
		RPM_BASED_UNINSTALL_CHOICES
	fi
fi

