#!/bin/sh
#
# Copyright 2006, 2007 by
# Manuel Carrasco
#
# This file is part of the LookXP project, and may only be used, modified,
# and distributed under the terms of the LookXP project license,
# LICENSE.TXT.  By continuing to use, modify, or distribute this file you
# indicate that you have read the license and understand and accept it
# fully.
#
#             http://lxp.sourceforge.net
#
#  This script installs or uninstalls the LXP environment.
#
#  Manuel_Carrasco@users.sourceforge.net (Aug 2006)
#
# 0.1-19    Support for Red hat enterprise 4 && CenTOs 4.4, fixed imlib2, fixed tryUndupportedDistr.
# 0.1-18    Fixes in rpm + deb distr.
# 0.1-16    Support for .deb distributions, added SetupVarsUrl
# 0.2-1     changed icewm packages to lxp-icewm
# 0.2-1c    added --verbose, fixed download lxp-icewm when lxp-icewm-gnome2 selected

SetupVersion="0.2-1c 1171195165"
SetupVarsUrl="http://lxp.sourceforge.net/files/lxp-last-pakages.txt"

# default answers 
UNINST_PREV=y
UNINST_ALL=2
INSTALL_NEW=y
INSTALL_XFE=y
INSTALL_GNOME2=n
INSTALL_XDIALOG=y
INSTALL_XOSVIEW=y
INSTALL_IMLIB=y
INSTALL_IMLIB2=y
DELETE_UNLOADED=n
USE_CACHED=y
YES=y
NO=y
doPrompt=y
#
DBG_WGET=n

# Cache folder for downloaded files
DCACHE=/var/cache/LXP

# Determine what echo version has this shell
E=`echo -en X`
[ "$E" = X ] && Echo="echo -e" || Echo="echo "

# Initialize global variables
LNX=""; DEB=""; pkgCache="";

## usage function
Usage() {
   cat <<EOF
     Usage: $0  "[--help|--default]"
       --help     this message
       --default  install LXP without prompting user, use default options
       --verbose  show wget progress
EOF
}
## exit function
exitError() {
   $Echo "++ Error:\n\n     ${@} \n\n"
   $Echo ""
   exit 2
}
## ask the user for a question 
askFor()
{
        command="$Echo -n \$$2"
        value=`eval "$command"`
        [ -z "$value" ] && value=`$Echo "$2" | awk '{print $1}'`
        t=""
        while [ -z "$t" ]
        do
                $Echo "\n\n>>> $1\c"
                [ -n "$3" ] && $Echo " ($3)\c"
                [ -n "$value" ] && $Echo " [$value]: \c" || $Echo " : \c"
                if [ "$doPrompt" = n ]; then
                      t="$value" && $Echo "$t"
                else
                      read t
                      [ -z "$t" -a -n "$value" ] && t="$value" 
                fi
                h=""
                if [ -n "$3" ]
                then
                        for i in $3
                        do
                                [ "$t" = $i ] && h=ok
                        done
                fi
                [ -z "$h" ] && t=""
        done
        [ $t = none ] && t=""
        eval "$2=$t"
        $Echo ""
}
## functions to search for installed packages/binaries
cacheInstalledPackages() {
   $Echo "++ Searching for installed packages ... \c " 
   [ -n "$RPM" ] && pkgCache=`rpm -qa | sed -e 's#-[0-9].*$##g'`
   [ -n "$DEB" ] && pkgCache=`dpkg -l | grep "^ii" | awk '{print $2}'`
   $Echo "OK"
}
isInstalled() {
   case $1 in
    exe)    
        H=`which $2 2>/dev/null`
        [ -n "$H" -a -x "$H" ] && return 0 || return 1
        ;;
    pkg)
        [ -z "$pkgCache" ] && cacheInstalledPackages
        H=`$Echo "$pkgCache" | grep "^$2$"`
        [ -n "$H" ] && return 0 || return 1
        ;;
   esac
   return 1
}
## Determine if current user has root privilegies
isRoot() {
   ID=`id | sed -e 's#^.*uid=##' -e 's#[^0-9].*$##g'`
   if [ -z "$ID" -o "$ID" -ne 0 ]
   then
    exitError "\n\n    !!! Sorry, but you must be root in order to install packages in your system. !!!"
   fi
}
## Messages 
IniMessage() {
   clear
   cat <<EOF
 **************************************************************************
 *                                                 [$SetupVersion]
 * Installation/Uninstallation of LookXP 
 *
 *       http://lxp.sourceforge.net
 *
 * LXP and all its components are GPL Software
 *
 **************************************************************************

EOF
}
EndInstallMessage() {
 cat << EOF

 **************************************************************************
 * LookXP packages has been installed sucesfully, 
 * now you will can login into your computer choosing the LookXP session
 *
 * Have Fun!
 *
 *                 LXP team: http://lxp.sourceforge.net
 **************************************************************************

EOF
}
EndUnInstallMessage() {
 cat << EOF

 **************************************************************************
 * LookXP packages has been removed from your system
 * Thank you for try LXP
 *
 *                 LXP team: http://lxp.sourceforge.net
 **************************************************************************

EOF
}
exitUnsupported() {
  cat <<EOF

 **************************************************************************
 *  !! This distribution is unsupported for lxp-setup script !!
 **************************************************************************

EOF
  exit
}
## inform that this rpm/deb distribution is unsupported and ask user if he/she wants to continue
tryUnsupportedDistr () {
       FORCE=n
       askFor "This Linux distributin is unsupported but is a deb/rpm distribution\n    Do you try to install LXP" FORCE "y n"
       [ "$FORCE" != y ] && exitError "unsupported version"
       B1=`ls -l /etc/*-release`
       B2=`cat /etc/*-release`
cat <<EOF

!!! if the installation go fine, please email me with the following information !!!

++++++++++ CUT HERE
To:      <manuel_carrasco@users.sourceforge.net>
Subject: LXP 0.1 in unsuported linux RPM=$RPM DEB=$DEB

--------------------------------------------------------------
$B1
--------------------------------------------------------------
$B2
--------------------------------------------------------------

++++++++++ END CUT

EOF
}
## function to check that a package is installed, if not it ask user to install it from fedora/debian repositories
checkPackage() {
   package=$1; msg="$2"

   $Echo "++ Checking if $package is installed ... \c "
   isInstalled pkg $package  && $Echo OK && return 0
   $Echo ERROR

   [ -n "$RPM" -a -z "$YUM" ] && return 1

   askFor "$msg" INSTALL_LIB "y n"
   [ "$INSTALL_LIB" != y ] && return
#   [ "$INSTALL_LIB" != y ] && cat << EOF
# **************************************************************************
# *  !! It is necesary to install $package before install lxp-icewm
# *
# *  please install it in 
# *       ie. rpm systems: yum install $package
# *       ie. deb systems: apt-get install $package
# *
# **************************************************************************
#EOF
   [ -n "$RPM" ] && $YUM $package
   [ -n "$DEB" ] && apt-get install $package
   cacheInstalledPackages
   isInstalled pkg $package  && return 0

  cat <<EOF
 **************************************************************************
 *  !! unable to install $package, try to install it manually
 **************************************************************************
EOF
   return 1
}
## 
tryImLib() {
  msg="It is necesary to install imlib before install lxp-icewm\nDo you want to try installing it now? "
  [ -n "$RPM" ] && lib=imlib || lib=imlib11
  INSTALL_LIB=y
  checkPackage $lib "$msg"
  isInstalled pkg $lib  || exit
  return 0
}
tryImLib2() {
  msg="It is necesary to install imlib2 before install the optional package idesk\nDo you want to try installing it now? "
  [ -n "$RPM" ] && lib=imlib2 || lib=libimlib2
  INSTALL_LIB=n
  checkPackage $lib "$msg"
  return $?
}
tryXmlParser() {
  msg="It is necesary to install perl-xmlparser in order to use lxp-menu-generator script\nDo you want to try installing it now? "
  [ -n "$RPM" ] && lib=perl-XML-Parser || lib=libxml-parser-perl
  checkPackage $lib "$msg"
  return $?
}
## function to determine which distribution is this
testLinuxVersion() {
    isInstalled exe dpkg && DEB=y
    ## some debian dists has rpm binary installed
    [ "$DEB" != y ] && isInstalled exe rpm && RPM=y

    [ "$DEB" != y -a "$RPM" != y ] && exitUnsupported

    if [ -n "$RPM" ]
    then
	RH=`cat /etc/redhat-release 2>/dev/null | grep -i "Red Hat" | awk '{print $7}'`
        CE=`cat /etc/redhat-release 2>/dev/null | grep -i "CentOS"  | awk '{print $3}'`
        FC=`cat /etc/redhat-release 2>/dev/null | grep -i "Fedora Core" | awk '{print $4}'`
        SS=`cat /etc/SuSE-release 2>/dev/null | grep "^VERSION" | awk '{print $3}'`
        case $CE in
          4.4)     YUM="up2date --install"; LNX="fedora"; return;;
        esac
        case $RH in
	      4)	   YUM="up2date --install"; LNX="fedora"; return;;
	    esac
        case $FC in
          3|4|5)   YUM="yum install";     LNX="fedora"; return;;
        esac
        case $SS in
          10.1|10) LNX="suse"; return;;
        esac
    fi
    if [ -n "$DEB" ]
    then
	if [ -f "/etc/lsb-release" ]
	then
            . /etc/lsb-release
            V=`$Echo "$DISTRIB_RELEASE" | cut -d "." -f1`
            case "$DISTRIB_ID" in
		    *buntu)
			    LNX=ubuntu; [ "$V" -ge 6 ] && return ;;
		    *ebian)
			    LNX=debian; [ "$V" -ge 4 ] && return ;;
	    esac
	fi
    fi
    tryUnsupportedDistr
}
## download a file from sourceforge or lxp site
download() {
   isInstalled exe wget || exitError "can not find wget command"
   [ ! -d $DCACHE ] && mkdir $DCACHE 
   [ ! -d $DCACHE ] && exitError "can not create $DCACHE"
   cd $DCACHE || exitError "can not chdir to $DCACHE"
   [ -z "$2" -o -f "$2" ] && return
   ## [ "$1" = sourceforge ] && url="http://prdownloads.sourceforge.net/lxp/$2?use_mirror=switch" || url="$1"
   [ "$1" = sourceforge ] && url="http://switch.dl.sourceforge.net/sourceforge/lxp/$2" || url="$1"
   tries=3
   i=0
   while [ $i -lt $tries ]
   do
       i=$(($i + 1))
       $Echo "++ Downloading: $2 ... \c" >&2
       # $Echo "$url \c" >&2
       if [ "$DBG_WGET" = y ]
       then
	  $Echo "\n\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >&2
          wget "$url"  >&2
	  $Echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" >&2
          $Echo "++ Downloaded: $2 ... \c" >&2
       else
          E=`wget "$url" 2>&1`
       fi
       [ -f "$2" ] && i=$tries || $Echo Error
   done
   [ ! -f "$2" ] && exitError "$2 Not downloaded"
   $Echo OK
}
## uninstall a package using rpm or dpkg
unInstall() {
   [ -z "$1" ] && return
   if isInstalled pkg $1 
   then
       $Echo "++ Uninstalling: $1 ..." >&2
       [ -n "$RPM" ] && cmd="rpm -e $1"
       [ -n "$DEB" ] && cmd="dpkg -r $1"
       [ -z "$cmd" ] && return
       # $Echo MCM $cmd
       H=`$cmd 2>&1`
       if [ $? = 0 ] 
       then
          pkgCache=`$Echo "$pkgCache" | grep -v "^$1$"`
       elif [ -z "$2" ]
       then
          exitError "Can not uninstall $1\n$H"
       fi
   fi
}
## install a package using rpm of dpkg
Install() {
   [ -z "$1"   ] && return
   [ ! -f "$1" ] && return
   n=`basename $1 | sed -e 's#-[0-9].*$##g'`
   [ -z "$n"   ] && return
   isInstalled pkg $n && return
   $Echo "++ Installing $n from $1 ..." >&2
   [ -n "$RPM" ] && cmd="rpm -i $1"
   [ -n "$DEB" ] && cmd="dpkg -i $1"
   [ -z "$cmd" ] && return
   E=`$cmd 2>&1`
   [ $? != 0 ] && rm -f $1 && exitError "Can not install $1: $E"
   pkgCache=`$Echo "$pkgCache\n$n"`
}
#####
uninstLXP() {
   for package in $UNINST_LXP_PKG
   do
       unInstall $package
   done
}
uninstOther() {
   for package in $UNINST_OTH_PKG
   do
       unInstall $package
   done
}

uninstallPrevIcewm(){
  isInstalled pkg icewm || return
  UNINSTALL_ICEWM=y
  msg="It is necesary to uninstall icewm previously installed before install lxp-icewm\nDo you want to try uninstalling it now? " 
  askFor "$msg" UNINSTALL_ICEWM "y n"
  [ "$UNINSTALL_ICEWM" != y ] && exit
  for i in $UNINST_INCOMP_PKG
  do
	unInstall $i
  done
  cacheInstalledPackages
  isInstalled pkg icewm || return
}

downloadAll() {
   if [ "$INSTALL_GNOME2" = y ]
   then
     [ -n "$RPM" ] && download sourceforge "$FILE_Icewm"
     download sourceforge "$FILE_Icewm_Gnome2"
   else
     download sourceforge "$FILE_Icewm"
   fi
   download sourceforge    "$FILE_Icewm_Themes_LXP"
   download sourceforge    "$FILE_Icewm_l10n"

   [ -n "$RPM" ] && isInstalled pkg imlib2    && download sourceforge  "$FILE_Idesk"
   [ -n "$DEB" ] && isInstalled pkg libimlib2 && download sourceforge  "$FILE_Idesk"

   download sourceforge    "$FILE_lXP"
   if [ "$INSTALL_XFE" = y ] 
   then
      download sourceforge    "$FILE_Xfe"
      isInstalled pkg fox || download "$URL_Fox"     "$FILE_Fox"
   fi
   if [ "$INSTALL_XDIALOG" = y ]
   then
      isInstalled pkg Xdialog || download "$URL_Xdialog" "$FILE_Xdialog"
   fi
   if [ "$INSTALL_XOSVIEW" = y ]
   then
      isInstalled pkg xosview || download "$URL_Xosview" "$FILE_Xosview"
   fi
}
CleanOldUserConfiguration() {
    U=`getent passwd | cut -d ":" -f1,6 2>/dev/null`
    ulist=""; plist="";
    N=0;
    for i in $U
    do
        user=`$Echo $i | cut -d ":" -f1`
        path=`$Echo $i | cut -d ":" -f2`
        [ "$path" != / -a "$path" != /root -a -f "$path/.icewm/rightbar" ] && ulist="$ulist $user" && plist="$plist $path" && N=$(($N + 1))
    done
    if [ "$N" -gt 0 ]
    then
        askFor "These users used LookXP previously:\n\n$ulist\n\n>> Do you want to move their configuration files in order to use a fresh configuration?" NO "y n"
        if [ "$NO" = "y" ]
        then
            D=`date '+%Y-%m-%d'`
            for i in $plist
            do
                  [ -d "$i/.icewm" ] && mv $i/.icewm $i/.icewm.bk.$D
            done
        fi
    fi
}


getLastSetupVars() {
    SFILE=`basename $SetupVarsUrl`
    [ -f $DCACHE/$SFILE ] && rm -f $DCACHE/$SFILE
    download $SetupVarsUrl $SFILE
    . $DCACHE/$SFILE || exitError "Can not load last file releases vars"
    if [ "$DEB" = y ]
    then
		FILE_Icewm=$DEBLAST_ICE
		FILE_Icewm_Gnome2=$DEBLAST_ICE_G2
		FILE_Idesk=$DEBLAST_IDESK
		FILE_Xfe=$DEBLAST_XFE
		FILE_lXP=$DEBLAST_LXP
		FILE_Fox=$DEBLAST_FOX
		[ -z "$FILE_Fox" ] && FILE_Xfe=""
		#UNINST_LXP_PKG="lxp lxp-icewm lxp-idesk lxp-xfe"
		#UNINST_INCOMP_PKG="icewm icewm-gnome-support icepref icewm-themes iceme icewm-common"
		UNINST_LXP_PKG="lxp lxp-icewm lxp-idesk lxp-xfe"
		UNINST_INCOMP_PKG="lxp lxp-icewm"
		UNINST_OTH_PKG="fox"
		URL_Fox="sourceforge"
    elif [ "$RPM" = y ]
    then
		[ "$LNX" = suse   ] && FILE_Icewm=$RPMLAST_ICE_SU
		[ "$LNX" = fedora -o -z "$LNX" ] && FILE_Icewm=$RPMLAST_ICE_FC
		FILE_Icewm_Themes_LXP=$RPMLAST_TH
		FILE_Icewm_Gnome2=$RPMLAST_G2
		FILE_Icewm_l10n=$RPMLAST_L10N
		FILE_Idesk=$RPMLAST_IDESK
		FILE_Xfe=$RPMLAST_XFE
		FILE_lXP=$RPMLAST_LXP
		FILE_Fox=$RPMLAST_FOX
		FILE_Xdialog=$RPMLAST_XDIALOG
		FILE_Xosview=$RPMLAST_XOSVIEW
		[ -z "$FILE_Fox" ] && FILE_Xfe=""
		URL_Fox="http://lxp.sourceforge.net/files/thirdrpms/${FILE_Fox}"
		URL_Xdialog="http://lxp.sourceforge.net/files/thirdrpms/${FILE_Xdialog}"
		URL_Xosview="http://lxp.sourceforge.net/files/thirdrpms/${FILE_Xosview}"
		# UNINST_LXP_PKG="lxp icewm-l10n icewm-menu-gnome2 icewm-themes icewm-themes-LookXP icewm idesk xfe"
		UNINST_LXP_PKG="lxp lxp-icewm-l10n lxp-icewm-menu-gnome2 icewm-themes-LookXP idesk xfe"
                #UNINST_INCOMP_PKG="icewm-l10n icewm-menu-gnome2 icewm-themes icewm idesk xfe"
		UNINST_INCOMP_PKG="lxp lxp-icewm-l10n lxp-icewm-menu-gnome2 lxp-icewm idesk xfe"
		UNINST_OTH_PKG="xosview Xdialog fox-devel fox"
    else
		exitUnsupported
    fi
}

#################################################
#################################################
#################################################
#################################################
#### MAIN ####
case $1 in
    --default)         doPrompt=n ;;
    --cleanuserconf)   CleanOldUserConfiguration && exit;;
    --verbose)         DBG_WGET=y ;;
    ?*)                Usage ;;
esac

IniMessage

isRoot

askFor "This script will install/uninstall LXP components in your system. Do you want to continue? " YES "y n"
[ "$YES" != y ] && exitError "Process cancelled by the user. Bye"

testLinuxVersion

getLastSetupVars

### If lxp is already installed, ask the user if he wants to uninstall all
if isInstalled pkg lxp 
then 
    askFor " LXP is already installed, do you want to uninstall it" UNINST_PREV "y n"
    [ "$UNINST_PREV" != y ] && exitError "Can not install a newer version without uninstaling the previous one"
    uninstLXP
    OTHER=""
    for package in Xdialog xosview fox
    do
       isInstalled pkg $package && OTHER="$OTHER $package"
    done
    if [ -z "$OTHER" ]
    then
       askFor "Do you want to install latest LXP version" INSTALL_NEW "y n"
       [ "$INSTALL_NEW" != y ] && exit
    else
       askFor \
          " Now, what do you prefer?:\n  1.- Install the latest LXP version\n  2.- Continue uninstalling other packages: $OTHER\n  3.- Exit\t\t" \
          UNINST_ALL "1 2 3"
       [ "$UNINST_ALL" = 3 ] && EndUnInstallMessage && exit
       [ "$UNINST_ALL" = 2 ] && uninstOther && EndUnInstallMessage && exit
    fi
fi

files=""
### imlib is mandatory
tryImLib
### imlib is optional in order to install idesk
tryImLib2 && files="$files $FILE_Idesk"
### Previous versions of icewm must be uninstalled
uninstallPrevIcewm

### Ask for aditional software (not mandatory for LXP)
if test -z "$FILE_Xdialog" || isInstalled exe Xdialog || isInstalled exe zenity || isInstalled exe kdialog
then
   :
else
   askFor "Do you want to install Xdialog utilitiy" INSTALL_XDIALOG "y n"
   [ "$INSTALL_XDIALOG" = y ] && files="$files $FILE_Xdialog"
fi

if test -z "$FILE_Xosview" || isInstalled exe xosview
then
   :
else
   askFor "Do you want to install xosview utility" INSTALL_XOSVIEW "y n"
   [ "$INSTALL_XOSVIEW" = y ] && files="$files $FILE_Xosview"
fi

if test -z "$FILE_Fox" || test -z "$FILE_Xfe" || isInstalled pkg xfe
then
   :
else
   askFor "Do you want to install Xfe file manager" INSTALL_XFE "y n"
   [ "$INSTALL_XFE" = y ]   && files="$files $FILE_Fox $FILE_Xfe"
fi

### Determine what packages to install
askFor "Do you want to install icewm-menu-gnome2 " INSTALL_GNOME2 "y n"
if [ "$INSTALL_GNOME2" = y ]
then
    [ -n "$RPM" ] && files="$files $FILE_Icewm $FILE_Icewm_Gnome2"
    [ -n "$DEB" ] && files="$files $FILE_Icewm_Gnome2"
else
    files="$files $FILE_Icewm"
fi
files="$files $FILE_Icewm_Themes_LXP $FILE_Icewm_l10n $FILE_lXP"


### Ask user for deleting or using already downloaded files
nf=0; for i in `echo $files | tr " " "\n" | sort | uniq`; do [ -f "$DCACHE/$i" ] && $Echo "++ File: $i already downloaded " && nf=$(($nf + 1)); done
if [ $nf -gt 0 ]
then
    askFor "There are $nf files already downloaded. Do you want to use them? " USE_CACHED "y n"
    if [ "$USE_CACHED" = n ] 
    then
         for i in $files; do [ -f "$DCACHE/$i" ] && $Echo "++ Deleting: $i" && rm -f "$DCACHE/$i"; done
    fi
fi

### Download all necesary packages from sourceforge or lxp web site
downloadAll

### Install all selected packages
message="The following packages will be installed:\n"
for file in $files
do
    [ -f "$DCACHE/$file" ] && ifiles="$ifiles $file" && message="$message\n   $file"
done

askFor "$message\n\n Do you want to delete these files from cache after installation? " DELETE_UNLOADED "y n"

for file in $ifiles
do
    Install "$DCACHE/$file"
    [ "$DELETE_UNLOADED" = y ] && $Echo "++ Deleting: $DCACHE/$file" && rm -f $DCACHE/$file
done

### Remove old configuration of users
CleanOldUserConfiguration


EndInstallMessage
