#!/bin/sh

# Post Installer for CorelDraw/Photopaint v9.0  
# Copyright 1999-2001 Corel Corporation

# Modified By: Andrew S - linux_tech66@corel.com 
# Version: v1.1   
# Date: 4/24/01 

# * v1.1.0 
# - Added a if statement to check if /etc/init.d is a sym link.  If it is its renamed to something else and fonttastic is installed.
# - Appended the uninstall script to this install script.
# - Changed the setup so that it would only export LC_ALL if the user is running Glibc v2.1.3
# - Added a subroutine to check for libsafe and give the user the option to disable it.
# - Modified the script so that it would check to see if draw9 was already installed or not.  


echo "Welcome to the Draw9 install/uninstall script"


i=0

while [ "$i" = 0 ] ; do

 echo ""
 echo "1 - Post Install"
 echo "2 - Uninstall"
 echo "3 - Exit"
 echo -n "Enter choice ->"
 read INSTALLUNINSTALL

 if [ "$INSTALLUNINSTALL" = 1 -o "$INSTALLUNINSTALL" = 2 -o "$INSTALLUNINSTALL" = 3 ]
  then
   i=1
  else
   echo "Invalid menu option: $INSTALLUNINSTALL"
 fi
done

if [ "$INSTALLUNINSTALL" = 3 ]
 then
  echo "Exiting..."
  exit
fi

if [ "$INSTALLUNINSTALL" = 1  ]
 then


# Unset LC_ALL so that perl does not complain or give warnings 
unset LC_ALL 

current=`pwd`
RPMPATH=/dists/redhat/i386
logfile=log.txt
DIR=/usr/lib

# Setup the logfile - if enabled 

echo "" > $logfile 
echo "Draw9 Logfile `date`" >> $logfile
echo "NOTE: Most of the error messages in this log file can be ignored." >> $logfile 

clear

# Creating the applink directory incase it does not exist.  

mkdir -p /usr/X11R6/share/applnk/Applications/CorelGraphics9


# Simple case statement to determine parameters passed to the setup script

case $* in
 ("--nodetect")
   CDAUTODETECT=NO
   FLAG=0
   ;;
esac


# CD-ROM Autodetection subroutine  

if [ "$CDAUTODETECT" = NO ]
 then 
  echo "Skipping CD Autodetection!!" 
 else 

  echo "The installer will attempt to autodetect your CD-ROM.  If this causes problems re-run the install"
  echo "with the --nodetect flag.  (e.g. ./install --nodetect)"

  # Stat all mounted filesystems first
  
  FLAG=0
  MOUNTPOINTS=`df | grep "/" | awk '{print $6}'`

  echo "Checking for Draw9/Photopaint CD"
  echo ""

  for i in $MOUNTPOINTS ; do
   if [ -f $i/remove-graphics9 ]
    then
     CDROM="$i$RPMPATH"
     MOUNTDIR="$i"
     FLAG=1
     echo "Checking $i...  Found"
   fi
  done
 
# If no mounted file systems contain the CD - try and mount any cd-rom devices found in /etc/fstab

    if [ "$FLAG" = 0 ]
     then
      MOUNTDEVICES=`cat /etc/fstab | grep iso9660 | awk '{ print $1 }'`
      if [ "$MOUNTDEVICES" != '' ]
       then
        mkdir -p /tmp/mnt
        for SINGLEDEVICE in $MOUNTDEVICES ; do
         echo -n "Checking $SINGLEDEVICE...  "
         mount $SINGLEDEVICE /tmp/mnt -t iso9660 2> /dev/null

         if [ -f /tmp/mnt/remove-graphics9 ]
          then
           echo "Found"
           CDROM="/tmp/mnt$RPMPATH"
           MOUNTDIR="/tmp/mnt"
           FLAG=1
          else
           umount -f /tmp/mnt 2> /dev/null
           echo "CD-ROM Not Found"
           FLAG=0
         fi
        done
       else
        # Check the obvious /dev/cdrom
        mkdir -p /tmp/mnt
        mount /dev/cdrom /tmp/mnt 2> /dev/null
         if [ -f /tmp/mnt/remove-graphics9 ]
          then
           echo "Checking /dev/cdrom...  Found"
           CDROM="/tmp/mnt$RPMPATH"
           MOUNTDIR="/tmp/mnt"
           FLAG=1
         else
          echo "CD-ROM Not Found"
          FLAG=0
        fi
      fi
    fi
  fi

 

# Prompt the user to enter in a mount directory if the CDROM could not be found. 

if [ "$FLAG" = 0 ] 
 then
  echo "" 
  echo "Please enter directory where the Draw9 CD is mounted" 
  echo -n "(e.g. /mnt/cdrom) ->" 
  read CDROM
  CDROM=$CDROM$RPMPATH
  if [ "$CDROM" = '' ]
   then
    echo "Ok, using default directory /mnt/cdrom."
    CDROM=/mnt/cdrom$RPMPATH
  fi
fi 



# Make sure CD appears to be there

if [ ! -d "$CDROM" ]
 then
  echo "Unable to find RPM directory on CD. Check that the CD is mounted and"
  echo "the correct path was specified and run the script again."
  exit 1
fi


# Check the system to ensure that Draw/Photopaint has already been installed. 

echo -n "Checking for Draw9/Photopaint install..  "

graphcheck=`rpm -qa | grep -c graphics9-common`

if [ "$graphcheck" = 1 ] 
 then 
  echo "Found" 
 else 
  echo "Not Found" 
  echo "Would you like to run the Draw9/Photopaint install??"
  
    
  echo -n "[Y/N] -->"
  read choice  
  if [ "$choice" = y -o "$choice" = Y ] 
   then 
    echo "NOTE: Ensure that you rerun this script once the Draw9/Photopaint install is complete!!" 
    echo "Press any key to continue..."
    read anykey
    exec $MOUNTDIR/install 
   else 
    echo "Aborting installation.  Draw/Photopaint must be installed before proceeding with this post installation script" 
    exit 1
  fi 
 
fi 






RPMPATH=$CDROM

# Determine whether system uses glibc 2.0 or 2.1

if [ -f /lib/libc.so.6 ]
 then
   GLIBC=`strings /lib/libc.so.6 | grep "GNU C Library" | awk '{print $7}' | cut -c 1-3`
   if [ ! -f /usr/bin/strings ]
    then 
     echo "Strings does not appear to exist on your machine - asuming that you have Glibc v2.1" 
     GLIBC=2.1 
   fi
   if [ $GLIBC != "2.0" -a $GLIBC != "2.1" ]
    then
     GLIBC="2.1"
   fi
 else
   echo "Library file /lib/libc.so.6 not found. Unable to determine C library version."
   exit 1
fi

 if [ -f /usr/lib/libncurses.so.4 ] || [ -f /lib/libncurses.so.4 ]
    then
     rpm -Uvh $RPMPATH/wine-graphics9-glibc-${GLIBC}-*.rpm $bsdinit_flags
      else

     # If not, check to see if libncurses.so.5 exists and create a symbolic link to libncurses.so.4

     if [ -f /usr/lib/libncurses.so.5 ]
      then
       echo "Creating Symbolic link between /usr/lib/libncurses.so.5 and /usr/lib/libncurses.so.4"
       ln -s /usr/lib/libncurses.so.5 /usr/lib/libncurses.so.4
       rpm -Uvh $RPMPATH/wine-graphics9-glibc-${GLIBC}-*.rpm --force --nodeps 
        elif [ -f /lib/libncurses.so.5 ]
         then
          echo "Creating Symbolic link between /lib/libncurses.so.5 and /lib/libncurses.so.4"
          ln -s /lib/libncurses.so.5 /lib/libncurses.so.4
          rpm -Uvh $RPMPATH/wine-graphics9-glibc-${GLIBC}-*.rpm --force --nodeps 
         else
          echo "libncurses was not found. Installing anyway.  You will have problems!!!"
          rpm -Uvh $RPMPATH/wine-graphics9-glibc-${GLIBC}-*.rpm --force --nodeps              
     fi
 fi

  
if test -L /etc/init.d
 then
  mv /etc/init.d /tmp
  rpm -Uvh $RPMPATH/fonttastic-glibc-${GLIBC}-*.rpm --force $bsdinit_flags $bsdinit_fontastic 2> /dev/null
  mv /tmp/init.d /etc
 else
  rpm -Uvh $RPMPATH/fonttastic-glibc-${GLIBC}-*.rpm --force $bsdinit_flags $bsdinit_fontastic 2> /dev/null
fi

echo "Copying application links to the proper directory" 
echo "NOTE: In order for the application icons to show up the window manager must be restarted" 
cp -rf /usr/X11R6/share/applnk/Applications/CorelGraphics9 /opt/kde/share/applnk/ 2>> $logfile 

 # Ensure that LC_ALL is set to EN

  lc_all=`strings /lib/libc.so.6 | grep "GNU C Library" | awk '{print $7}' | cut -c 1-5`


  if [ "$lc_all" = 2.1.3 ]
   then
    echo 'Your running Glibc v2.1.3 - Setting LC_ALL=en' >> $logfile
    echo 'Adding LC_ALL=en to /etc/profile' >> $logfile
    echo 'export LC_ALL=en' >> /etc/profile
    echo 'YOU MUST REBOOT YOUR COMPUTER BEFORE STARTING DRAW9'
   fi

  # Libsafe causes wine to seg fault...

   libsafe=`set | grep -c libsafe`

   if [ "$libsafe" = 1 ]
    then
     echo "WARNING: It appears that you have libsafe installed on your system."
     echo "Please ensure that it is disabled while running Draw9."
     echo "Press any key to continue ...."
     read anykey
   fi


# And finally - to unmount the CDROM from /tmp/mnt ( only if it was not detected as a mounted FS )  

# Fontastic has to be killed first otherwise it wont eject 

killall fontfs 2> /dev/null 
umount -f /tmp/mnt 2> /dev/null  
rmdir /tmp/mnt 2> /dev/null

else


# uninstaller for Graphics 9
# Copyright 1999-2000 Corel Corporation

# Original Author: M Dickson.
# Ongoing Authors: <recorded in CVS>
# $Id: remove-graphics9,v 1.6 2000/06/22 19:24:36 albertd Exp $

# Thanks to:
#	J Aston for the disk space detection
#	A denHaan for feedback and help with dpkg and apt-get
#	D Meisenheimer for showing me how cool unattended ftp can be
#	J Tranter for an easier way of determining the c library
#	C Gorman for a more stable way of determining the c library 
#	C James for giving me a kick in the pants
#	K Wong and his team for finding all the "undesired features"
#-----------------------------------------------------------------------
# Caveats
#	Eterm seems not to like the way I clear lines
#	the grep on the filename for rpm is a bit globbish
#------------------------------------------------------------------------

#------------------------------------------------------------------------
currentVersion="0.9"
#------------------------------------------------------------------------
#------G L O B A L   V A R I A B L E S-----------------------------------
	# A listing of all the packages in beta 1.
betaOnePackageList="graphics graphics9-help-draw graphics9-help-paint \
	graphics9-help-techsupport libwine-dev-gfx9 libwine-dev-gfx9 \
	wine-gfx9 wine-tools-gfx9 libwine-gfx9 wine-doc-gfx9"

	# A listing of all the packages in beta 2
betaTwoPackageList="graphics9-draw graphics9-help-common \
	graphics9-help-draw graphics9-help-paint graphics9-help-techsupport \
	graphics9-help-writingtools graphics9-paint graphics9-common \
	libwine-dev-graphics9 wine-graphics9 wine-tools-graphics9 \
	libwine-graphics9 wine-doc-graphics9 "

	# the amalgamated list
fullPkgRemoveList="$betaOnePackageList $betaTwoPackageList"

	# How many packages are listed above?
	# 13beta2 + 10beta1
numPkgs=23

	# these are the packages that have a glibc version attached
libcDepList="wine-graphics9 libwine-dev-graphics9 libwine-graphics9 fonttastic \
	wine-tools-graphics9 libwine-dev-gfx9 libwine-dev-gfx9 libwine-gfx9 \
	wine-gfx9 wine-tools-gfx9 "

	# rpm or dpkg?
type=none;

	# this gets set to dontRemoveIfWPO2000List if wpo2000 is not installed.
alsoRemove=" ";

	# these files should not be removed if WPO2000 is also on the system.
dontRemoveIfWPO2000List=" libaps-dev fonttastic wpo2000-fonts-core "

	# How many files are listed above?
dontRemoveNum=3;

	# This flag indicates whether a whack of directories should be removed.
	# Set to 0 (no) by defualt, only reset to 1 if wpo2000 is not found
cleanSystem=0;

	# These two turn bold text on and off
bon="\33[1m"
boff="\33[0m"

	# Error Strings
	# Each error condition is given a string here.  Then, when
	#  error() is used, the correct string is printed.
error2="You must be root to install this software."
error3="No package manager found."
error4="libc6 is not installed."
error8="This is not a Linux system!"
error13="Only libc6 versions 2.0 and 2.1 are supported.  Neither are installed."
error99="Unknown error has occured.  Please call Albert at x5318"

	# realias echo to handle special characters, which it doesn't
	#  do by default
ECHO="echo -e"

currentUID=""
#---------------------------------------------------------------------------
#-----F U N C T I O N S-----------------------------------------------------
# clearLine
clearLine ()
	{
	clearCount=80;
	if [ ! -z "$1" ] ; then
		clearCount=$1;
	fi
	clearStatus=`expr $clearCount \> 0`
#	while [ $clearStatus -eq 1 ] ; do
#		echo -en "\b \b"
#		clearCount=`expr $clearCount - 1`
#		clearStatus=`expr $clearCount \> 0`
#	done
	while [ $clearCount -gt 0 ] ; do
		echo -en "\b \b"
		clearCount=`expr $clearCount - 1`
	done
	}


#---------------------------------------------------------------------------
#generic error handler. Takes 1 required and 1 optional arguement
# First arguement is a number, corresponding to an error message as listed
#  above.
# Second arguement is one of:
#	blank : nothing happens
#	usage : usage message gets printed out
#	text  : the supplied text gets printed out  
error ()
	{
	t=error$1
	eval $ECHO "\${bon}*****\\\nERROR\${boff}\\\n\$$t"
	if [ ! -z  "$2" ] ; then
		if [ $2 = "usage" ] ; then 
			$ECHO $usage ; 
		fi
	else
		eval $ECHO "$2";
	fi
	exit 1
	} 

#-----------------------------------------------------------------------------
# Performs all the required system checks:
#	user is root
#	system is Linux
#	libc6 is installed
#	a package manager is installed
# If any of these fail, the whole script fails.
systemChecks ()
	{
	$ECHO "${bon}Beginning System Checks:${boff}"
	#-----Check for Linux system---------
	$ECHO -n "  Checking for a Linux system..."
	if [ ! `uname -s | egrep -e "inux"` ] ; then
		error 8 '`uname -s` was found';
	fi
	$ECHO " OK Found one.  Whew!! ;)"

	#-----Check for root---------
#	$ECHO -n "  Checking for root UID..."
#	id | egrep "root" > /dev/null 2>/dev/null;
#	if [ "$?" != 0 ]; then
#		error 2
#	fi
#	$ECHO " OK (Current user is root)"
	
	#-----Check for WPO2000---------------
	$ECHO -n "  Checking for WPO2000...";
	if [ -f /usr/lib/corel/bin/wpolauncher ] || [ -d /usr/lib/corel/wpo ] ; then
		$ECHO "found. $dontRemoveIfWPO2000List will not be removed."
	else
		alsoRemove=$dontRemoveIfWPO2000List;
		numPkgs=`expr $numPkgs + $dontRemoveNum` ;
		cleanSystem=1;
		$ECHO "not found."
	fi
	
	#-----Check for Package Manager-------
	$ECHO -n "  Checking for package manager...";
	
	dpkg -h > /dev/null 2>/dev/null;
	if [ $? -eq 0 ] ; then
		type=dpkg;
	else
		rpm -v > /dev/null 2>/dev/null;
		if [ $? -eq 0 ] ; then
			type=rpm;
		fi
	fi
	if [ $type = "none" ] ; then
		error 3
	fi

	$ECHO " OK (found $type at `which $type`)";

	#-----Check for correct libc ------
	$ECHO -n "  Checking for proper C library..."
	if [ -f /lib/libc.so.6 ] ; then
		versionNumber=`strings /lib/libc.so.6 | grep "GNU C Library" | awk '{print $7}' | cut -c 1-3`;
		if [ $versionNumber != "2.0" -a $versionNumber != "2.1" ] ; then 
                      versionNumber=2.1
		else 
			libcVer="glibc-$versionNumber";
			$ECHO " OK (found $libcVer)";
		fi
	else
		error 4
	fi


	$ECHO "  System checks passed."
	}

#-----------------------------------------------------------------------------
# Remove the packages from your system.  Very brute force and unoptomized.
# Also removes the directories /usr/lib/corel, /var/lib/corel and 
# /usr/doc/wpohelpfiles
removePackages ()
	{
	$ECHO "${bon}Removing Corel Graphics 9, $numPkgs packages to check.${boff}"
	$ECHO  "  Removal Progress:"
	num=$numPkgs;
	if [ $type = "rpm" ] ; then
		for pkg in $fullPkgRemoveList $alsoRemove; do
#			$ECHO -n "."
			for test in $libcDepList ; do
				if [ $test = $pkg ] ; then
#					echo -n "$pkg ->";
					pkg="$pkg-$libcVer";
#					echo "$pkg"
				fi
			done;
#			clearLine
			$ECHO -n "\n    Checking for #${num}: ${bon}$pkg${boff}..."
 			$type -qa | grep "^$pkg"  > /dev/null 2>&1
			if [ "$?" -eq 0 ] ; then
				$ECHO -n "Found. Removing it."
				$type $REMOVE $pkg > /dev/null 2>&1
			fi
			num=`expr $num - 1`;
#		$ECHO "";
		done
	else
		for pkg in  $fullPkgRemoveList $alsoRemove; do
			for test in $libcDepList ; do
				if [ $test = $pkg ] ; then
#					echo -n "$pkg ->";
					pkg="$pkg-$libcVer";
#					echo "$pkg"
				fi
			done;
			$ECHO -n "."
#			$ECHO "$pkg"
#			clearLine
			$ECHO -n "\n    Removing #${num}: ${bon}$pkg${boff} if installed."
			$type $REMOVE $pkg $pkg > /dev/null 2>&1
			num=`expr $num - 1`;
		done
	fi
#	clearLine
	$ECHO "\n  Package removal complete.";

	if [ -n "$BRUTALLY_REMOVE_GRAPHICS9" ]
	then
		$ECHO -n "  Cleaning up leftover directories..."	
		rm -rf /usr/lib/corel/wine-graphics9
		if [ $cleanSystem -eq 1 ] ; then
			rm -rf /usr/lib/corel
			rm -rf /var/lib/corel
			rm -rf /usr/doc/wpohelpfiles
			rm -rf /etc/fonttastic
			$ECHO "done."
			sleep 1;
		fi
	fi
#	clearLine
	$ECHO "Corel Graphics Application removal complete."
	}


#
#-----------------------------------------------------------------------------
# get the current username based on the UID
checkUID () 
	{
	grep "^[^:]*:[^:]*:$1" /etc/passwd | cut -f1 -d:
	}

#==============================================================================
#=====S C R I P T   S T A R T==================================================
clear
$ECHO "remove-graphics9 v$currentVersion\n"
$ECHO "This script will remove all Corel Graphics 9 packages from this system."
	#-----Check for root---------
currentUID=$(checkUID $(id -u))

if [ $currentUID != "root" ] ; then
	$ECHO "\n  ****************************************************"
	$ECHO "  * You will require the root password to complete   *"
	$ECHO "  * the removal of the Corel Graphics Suite.  If you *"
	$ECHO "  * don't know the root password, hit ctrl-c now to  *"
	$ECHO "  * cancel this script.                              *"
	$ECHO "  ****************************************************\n"
	$ECHO "\n  Please enter the root password at the prompt."
	while ! xterm -e su root -c "$0" ; do
		clearLine
		$ECHO -n "Incorrect password.  Try again? (y/n) >"
		read response;
		if [ $response != "y" ] && [ $response != "Y" ]  ; then
			clearLine
			$ECHO "Please try again when you know the root password."
			exit;
		fi
		clearLine
		$ECHO "\n  Please enter the root password at the prompt."
		done
	exit;
fi

$ECHO "hit <ctrl-c> now to abort."
for i in 5 4 3 2 1 ; do
	$ECHO -n "$i "
	sleep 1
done;
clearLine 10
$ECHO "Onward..."

	#perform all system checks
systemChecks;

if [ $type = "rpm" ] ; then
	REMOVE="-e --allmatches --nodeps";
elif [ $type = "dpkg" ] ; then
	REMOVE="--purge --ignore-depends"
fi

removePackages;

if [ -x /usr/bin/update-menus ] ; then /usr/bin/update-menus ; fi

$ECHO "\n\n${bon}All Done!${boff}\n"

exit;

fi

