#!/bin/sh

VERSION="sw-mgr v0.105.0 - 20091105"
help() {
    cat <<EOD
Usage: `basename $0` [OPTION]
   OPTIONS
   -------
   --force|-f                         Force installation/removal
   --override-lock                    Override the locks in the caches
   --help|-h                          Display this help
   --debug                            Enable debug output
   --install|-i <release number>      Install the selected release
   --validate|-V <release number>     Install and test the selected release
   --update|-u                        Update the selected release
   --test <release number>            Test the selected release
   --remove|-r  <release number>      Remove the selected release
   --manage|-M  <release number>      Manage the selected release
   --kit-cache|-k <URL>               Use URL as cache to download the kit
   --dbrelease <dbrel version>        Install the <dbrel version> DB release
   --ddm-setup <path>                 Full path to the DDM setup file
   --ddm-site <sitename>              DDM site name
   --goc-name <GOC site name>         GOC site name
   --cleanup|-C                       Delete the destination dirs
   --check                            Executes the pre-install checks
   --add-tags                         Add one or more tags
   --dump-tags <file>                 Dump the tags in <file>
   --force-tags                       Force the publishing of the tags
   --install-compiler                 Install the compiler
   --extra-tag                        Use an extra, unique tag suffix
   --tag-file <filename>              Use <filename> to store the tags
                                      (only for OSG)
   --extra-pkg <pkg>                  Install the extra package <pkg>
   --disk-free <PHYS>:<LOG>           Requires at least <PHYS> bytes free
                                      in the physical install area and
                                      <LOG> bytes free in the logical
                                      install area (default: $MINDF)
   --min-install-size <size in bytes> minimum installation size in bytes
                                      (default: $MININSTALLSIZE)
   --grid-name|-G <grid name>         Declare that you are using the
                                      <grid name> grid (default: $GRIDNAME)
   --host|-H <hostname>               Use <hostname> for tagging activities
   --reinstall                        Reinstall the selected release
   --reinstall-clean                  Clean the old install when reinstalling
   --no-tag                           Don't manage tags after testing
   --no-opt                           Don't use the optimization tag
   --no-compat-patch                  Exclude compatibility patches
   --post-siteinfo                    Post site info to $POSTSITEURL
   --pacball                          Use pacballs instead of snapshots
   --pacball-repo <URL>               Web repository for the pacballs
   --poolcond-topdir <path>           Top directory to store the poolcond files
   --poolcond-pattern <path>          Dataset patterns to generate the poolcond PFC
   --remove-tags                      Remove one or more tags
   --remove-snap|-R <release number>  Remove the snapshot for <release number>
   --replicate                        Replicate the installation files
   --require-compiler                 Require that the release compiler is present
   --require-shfs|-S                  Require that the install area is a shared fs
   --require-prj <project name>       Require <project name> to be installed
   --dest <path>                      Install the release in <path>
   --local-config <path>              Use <path> to store the local configuration files
   --logical|-l <path>                Install or manage the main logical release from <path>
   --package <package name>           Use the package <package name>
   --pacman-ver|-m <version>          Use pacman <version>
   --pretend-platform <platform>      Force pacman to assume using <platform>
   --no-cache|-n                      Don't create a snapshot for this release
   --no-version                       Don't use the version when getting packages
   --use-grid                         Use the Grid SEs to hold the snapshots
   --release-only|-o                  Pack only the release, no compiler or KV
   --physical <path>|-p               Install or manage the main physical release from <path>
   --project <project name>|-P        Use project <project name>
   --project-type <type>|-T           Use project type <type>
                                      <type> = release   -> production releases
                                      <type> = bugfix    -> bugfix nightlies
                                      <type> = dev       -> dev nightlies
                                      <type> = p1nightly -> point1 nightlies
                                      <type> = patch     -> production patches
                                      <type> = p1patch   -> point1 patches
                                      <type> = t0patch   -> Tier0 patches
                                      <type> = eventview -> PAT/EventView patches
   --project-opt <option>|-O          Use optimization <option>
                                      <option> = opt -> optimized mode
                                      <option> = dbg -> debug mode
   --site-config <path>               Use <path> to store the site configuration
   --snap|-s <release number>         Create a snapshot for the selected release
   --snapname <snapshot name>         Use <snapshot name> for the snapshot
                                      file name
   --snapdir <path>                   Create the snapshots in <path>
   --create-dvd|-c                    Create a DVD image with the local releases
   --write-dvd|-w <image name>        Create the DVD image <image name>
   --dir|-d <installation directory>  Use <installation directory>
                                      for the installation
   --release-ver|-v <release version> Set the release version (default: ${RELVER})
   --target|-t <arch>                 Use <arch> architecture for installing
   --tthreads <n>                     Use <n> test threads (default: ${TESTTHR})
   --temp-cache                       Use a temporary cache to install
   --vo <VO name>                     VO name (default: ${TAGVO})
   --tags <TAG1,TAG2,TAG3,...>        Tag names, separated by commas
   --query|-q                         Query the available (local) releases
   --quiet|-Q                         Disable verbose output
   --xml|-x <file name>               Generate an XML report of the installation
   --kvpost                           Post the test results to the GKV portal
   --kv-cache <cache>                 Use the <cache> KitValidation cache
   --kv-conf <URL>                    Use <URL> to get the KV configuration
   --kv-disable <testlist>            Disable the selected KV tests
   --kv-enable <testlist>             Enable the selected KV tests
   --kv-keep                          Keep the test results
   --kvpost-tag <tag>                 Use <tag> when posting to GKV
   --release-setup <path>             Setup from the most recent release <path>
                                      when required
   --setup-latest <path>              Setup the latest release from <path>
                                      at the beginning of the task
   --setenv <v1=val,v2=val,...>       Set the value of v1=val, v2=val, ...
                                      in the installation setup scripts
   --set-frontier                     Set the FRONTIER_SERVER in AtlasSite,
                                      if \$ATLAS_FRONTIER_CONF is found
   --validation-exe <file>            Use <file> to validate the installation

$VERSION
Alessandro De Salvo <Alessandro.DeSalvo@roma1.infn.it>
EOD
}


msgOut() {
   MSGTYPE="$1"
   MSGTEXT="$2"
   MSGDATE="`date +"%Y-%m-%d %H:%M:%S"`"
   [ "$QUIET" == "" ] && echo "[$MSGDATE] SWMGR> ${MSGTYPE}: ${MSGTEXT}"
   [ "$XMLFILE" != "" ] && xml add "    <swmgr type=\"$MSGTYPE\" datetime=\"$MSGDATE\">${MSGTEXT}</swmgr>"
   sync
   return 0
}


xml() {
   XMLCMD="${1}"
   XMLSTR="${2}"
   if [ "$XMLFILE" != "" ] ; then
       if [ "$XMLCMD" == "add" ] ; then
           echo $XMLSTR >> $XMLFILE
       fi
       if [ "$XMLCMD" == "open" ] ; then
           echo "<?xml version="1.0" encoding="UTF-8"?>" > $XMLFILE
           echo "<install>" >> $XMLFILE
       fi
       if [ "$XMLCMD" == "close" ] ; then
           echo "</install>" >> $XMLFILE
       fi
   fi
}

getFSType() {
    MOUNTPOINT="${1}"
    MOUNTPOINTFS="`df -T -P ${MOUNTPOINT} | tail -n 1 | awk '{print $2}'`"
    if [ "$MOUNTPOINTFS" == "fuse" ] ; then
      MOUNTPOINTFS="`df -T -P ${MOUNTPOINT} | tail -n 1 | awk '{print $1}' | cut -d# -f 1`"
    fi
    echo $MOUNTPOINTFS
    return 0
}

getDiskFree() {
    MOUNTPOINT="${1}"
    MOUNTPOINTFS="`getFSType ${MOUNTPOINT}`"
    # Temporary hack for bad sites
    SKIPDOMAIN="lrz-muenchen.de grid.lrz-muenchen.de"
    skip=0
    if [ "$TAGHOST" != "" ] ; then
        for item in $SKIPDOMAIN ; do
            [ "$item" == "`echo $TAGHOST | cut -d '.' -f 2-`" ] && skip=1
        done
    fi
    # Get the available space
    if [ $skip -eq 0 ] ; then
        if [ "$MOUNTPOINTFS" == "afs" ] ; then
            MOUNTPOINTDF="`fs listquota ${MOUNTPOINT} | tail -n 1 | awk '{print $2-$3}'`"
        else
            MOUNTPOINTDF="`df -k -P ${MOUNTPOINT} | tail -n 1 | awk '{print $4}'`"
        fi
    else
        # Return an high value for bad sites
        MOUNTPOINTDF=20000000
    fi
    [ "$MOUNTPOINTDF" == "" ] && MOUNTPOINTDF=0
    echo $MOUNTPOINTDF
    return 0
}

isSharedFS() {
    MOUNTPOINT="${1}"
    FSTYPE="`getFSType ${MOUNTPOINT}`"
    [ "$FSTYPE" == "afs" -o "$FSTYPE" == "nfs" -o "$FSTYPE" == "nfs4" -o "$FSTYPE" == "gpfs" -o "$FSTYPE" == "panfs" -o "$FSTYPE" == "lustre" -o "$FSTYPE" == "glusterfs" -o "$FSTYPE" == "none" -o "$FSTYPE" == "-" ] && echo "yes" || echo "no"
}

swareaInfo() {
    MOUNTPOINT="${1}"
    MPINFO="`df -T -P ${MOUNTPOINT} | tail -n 1`"
    MPAREA="`echo ${MPINFO} | awk '{print $1}'`"
    # Quick fix for AFS
    #[ "$MPAREA" == "AFS" ] && MPAREA="$MOUNTPOINT"
    MPFS="`echo ${MPINFO} | awk '{print $2}'`"
    MPAVAIL="`echo ${MPINFO} | awk '{print $4}'`"
    MPCAPACITY="`echo ${MPINFO} | awk '{print $5}'`"
    MPMP="`echo ${MPINFO} | awk '{print $7}'`"
    echo "swarea=${MPAREA}&fstype=${MPFS}&mountpoint=${MPMP}&capacity=${MPCAPACITY}&available=${MPAVAIL}"
    return 0
}

getSWarea() {
    MOUNTPOINT="${1}"
    MPINFO="`df -T -P ${MOUNTPOINT} | tail -n 1`"
    MPAREA="`echo ${MPINFO} | awk '{print $1}'`"
    echo "${MPAREA}"
    return 0
}

showSiteInfo() {
    msgOut INFO "======================="
    msgOut INFO "Resource info"
    msgOut INFO "Timestamp:  `date`"
    msgOut INFO "Running as: `whoami`"
    msgOut INFO "            `id`"
    msgOut INFO "Running on: `uname -a`"
    [ "`which lsb_release 2> /dev/null`" != "" ] && msgOut INFO "`lsb_release -d`"
    msgOut INFO "======================="
}

isInstalled() {
    # Check if ${ATLASRELEASE} is installed, using pacman
    iires=0
    if [ "`which pacman 2>/dev/null`" != "" ] ; then
        cd ${RELLOC}
        INSTPKG="`pacman -l ${ATLASRELEASE} | grep "^\[\*\].*${ATLASRELEASE}" | awk '{print $2}'`"
        [ "$INSTPKG" == "$ATLASRELEASE" ] && iires=1
    else
        iires=2
    fi
    return $iires
}

isAFSpath() {
    [ "`echo $1 | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] && echo "yes"
    return 0
}

getROpath() {
    RWPATH="$1"
    # Check if we are running in AFS
    if [ "`isAFSpath $RWPATH`" == "yes" ] ; then
        echo $RWPATH | sed 's#^/afs/\.*\(.*\)#/afs/\1#g'
    else
        echo $RWPATH
    fi
    return 0
}

getRWpath() {
    ROPATH="$1"
    # Check if we are running in AFS
    if [ "`isAFSpath $ROPATH`" == "yes" ] ; then
        # Check if we are already in the rw path 
        if [ "`echo $ROPATH | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
            echo $ROPATH | sed 's#^/afs/\(.*\)#/afs/.\1#g'
            return 0
        fi
    fi
    echo $ROPATH
    return 0
}

isAFSmountpoint() {
    fs lsmount $1 2>/dev/null
    return $?
}

findAFSmount() {
    AFSDIR="$1"
    while [ 1 ] ; do
        MP="`fs lsmount $AFSDIR 2>/dev/null`"
        if [ $? -eq 0 ] ; then
            echo $AFSDIR
            return 0
        else
            AFSDIR="`dirname $AFSDIR`"
        fi
        [ "$AFSDIR" == "/" -o "$AFSDIR" == "." ] && return 1
    done
}

checkSite() {
    msgOut INFO "Site checks started on `date`"
    let checkrc=0
    RELSHAREDFS="`isSharedFS $RELLOC`"
    RELDF="`getDiskFree ${RELLOC}`"
    isInstalled
    ISINSTALLED=$?
    if [ $ISINSTALLED -eq 0 ] ; then
        if [ "$RELDF" == "" -o $RELDF -lt $MINRELDF ] ; then
            msgOut ERROR "You don't have enough space in $RELLOC (actual=$RELDF, min=$MINRELDF)"
            let checkrc=100
        fi
    else
        msgOut INFO "The software you are installing is already present, ignoring the free space requirements for $RELLOC (actual=$RELDF, min=$MINRELDF)"
    fi
    if [ "$RELSHAREDFS" == "no" -a "$REQSHAREDFS" == "yes" ] ; then
        msgOut ERROR "The directory $RELLOC is not in a shared filesystem"
        msgOut INFO "`df -T -P ${RELLOC} | tail -n 1`"
        let checkrc=110
    fi
    if [ "$PRJTYPE" != "patch" -a "$PRJTYPE" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "$PRJTYPE" != "eventview" ] ; then
        SWSHAREDFS="`isSharedFS $SWLOC`"
        SWDF="`getDiskFree ${SWLOC}`"
        if [ $ISINSTALLED -eq 0 ] ; then
            if [ "$SWDF" == "" -o $SWDF -lt $MINSWDF ] ; then
                msgOut ERROR "You don't have enough space in $SWLOC (actual=$SWDF, min=$MINSWDF)"
                let checkrc=100
            fi
        else
            msgOut INFO "The software you are installing is already present, ignoring the free space requirements for $SWLOC (actual=$SWDF, min=$MINSWDF)"
        fi
        if [ "$SWSHAREDFS" == "no" -a "$REQSHAREDFS" == "yes" ] ; then
            msgOut ERROR "The directory $SWLOC is not in a shared filesystem"
            msgOut INFO "`df -T -P ${SWLOC} | tail -n 1`"
            let checkrc=110
        fi
    fi
    TDSHAREDFS="`isSharedFS $TOPDIR`"
    TDDF="`getDiskFree ${TOPDIR}`"
    if [ "$TDDF" == "" -o $TDDF -lt $MINTDDF ] ; then
        msgOut ERROR "You don't have enough space in $TOPDIR (actual=$TDDF, min=$MINTDDF)"
        TOPDIR=/tmp/tmp.atlas.install.$$
        TDDF="`getDiskFree /tmp`"
        SNAPDIR="${TOPDIR}/`basename ${SNAPDIR}`"
        msgOut INFO  "Trying to use ${TOPDIR}..."
        if [ "$TDDF" == "" -o $TDDF -lt $MINTDDF ] ; then
            msgOut ERROR "You don't have enough space in $TOPDIR (actual=$TDDF, min=$MINTDDF)"
            if [ "$VO_ATLAS_SW_DIR" != "" ] ; then
                TOPDIR=$VO_ATLAS_SW_DIR/tmp.atlas.install.$$
                TDDF="`getDiskFree ${VO_ATLAS_SW_DIR}`"
                SNAPDIR="${TOPDIR}/`basename ${SNAPDIR}`"
                msgOut INFO  "Trying to use ${TOPDIR}..."
                if [ "$TDDF" == "" -o $TDDF -lt $MINTDDF ] ; then
                    msgOut ERROR "You don't have enough space in $TOPDIR (actual=$TDDF, min=$MINTDDF)"
                    let checkrc=100
                else
                    msgOut INFO  "${TOPDIR} disk free OK"
                fi
            else
                msgOut ERROR "You don't seem to have VO_ATLAS_SW_DIR set. Giving up."
                let checkrc=100
            fi
        else
            msgOut INFO  "${TOPDIR} disk free OK"
        fi
    fi
    if [ ! -d ${TOPDIR} -a $checkrc -eq 0 ] ; then
        mkdir -p ${TOPDIR}
        \find $TOPDIR -maxdepth 1 -type d ! -perm -a+rx -exec chmod a+rx {} \;
        if [ $? -eq 0 ] ; then
            msgOut INFO  "Using ${TOPDIR} as temporary storage"
        else
            let checkrc=101
            msgOut ERROR "Cannot create the directory ${TOPDIR}"
        fi
    fi

    if [ $checkrc -eq 0 ] ; then
        msgOut INFO "Physical Area location:            $RELLOC"
        msgOut INFO "Physical Area details:             `\ls -ld $RELLOC`"
        [ "$SWLOC" != "$RELLOC" ] && \
        msgOut INFO "Logical Area location:             $SWLOC"
        msgOut INFO "Temporary Area location:           $TOPDIR"
        msgOut INFO "Available space in Physical Area:  $RELDF bytes"
        [ "$SWLOC" != "$RELLOC" ] && \
        msgOut INFO "Available space in Logical Area:   $SWDF bytes"
        msgOut INFO "Available space in Temporary Area: $TDDF bytes"
        msgOut INFO "System pre-checks OK"
    else
        msgOut INFO "System pre-checks FAILED"
    fi
    if [ "$POSTSITEINFO" == "yes" -a "$TAGHOST" != "" ] ; then
        SWAREAINFO="`swareaInfo $RELLOC`"
        wget -qO - --post-data="cename=${TAGHOST}&${SWAREAINFO}" ${POSTSITEURL}
        if [ $? -eq 0 ] ; then
            msgOut INFO "Site info posted successfully: ${SWAREAINFO}"
        else
            msgOut INFO "Failed to post site info: ${SWAREAINFO}"
        fi
    fi

    return $checkrc
}


getCloseReplica() {
    SOURCE="${1}"
    LCG_LR="`which lcg-lr 2>/dev/null`"
    if [ "$LCG_LR" != "" ] ; then
        $LCG_LR --vo $TAGVO ${SOURCE} 2>/dev/null | grep ${CLOSESE} | tail -n 1
    fi
}


getGridFile() {
    DEFSOURCE="lfn:${1}"
    SOURCE="${DEFSOURCE}"
    REPDEST="install/lcg/`basename ${1}`"
    DEST="file:${2}"
    LCG_CP="`which lcg-cp 2>/dev/null`"
    LCG_LR="`which lcg-lr 2>/dev/null`"
    LCG_LG="`which lcg-lg 2>/dev/null`"
    LCG_REP="`which lcg-rep 2>/dev/null`"
    GUID=""
    let getrc=0
    if [ "$LCG_LG" != "" ] ; then
        GUID="`$LCG_LG --vo $TAGVO ${SOURCE} 2>/dev/null`"
        if [ "$GUID" == "" ] ; then
            msgOut INFO "${SOURCE} not found in the Grid"
            let getrc=80
        else
            msgOut INFO "${SOURCE} OK"
            if [ "$CLOSESE" != "" ] ; then
                if [ "$LCG_LR" != "" ] ; then
                    CLOSE_REPLICA="`getCloseReplica ${SOURCE}`"
                    if [ "$CLOSE_REPLICA" != "" ] ; then
                        SOURCE="$CLOSE_REPLICA"
                    else
                        if [ "$GRIDREPLICA" == "yes" ] ; then
                            if [ "$LCG_REP" != "" ] ; then
                                msgOut INFO "Replicating installation files"
                                msgOut INFO "$LCG_REP --vo ${TAGVO} -d ${CLOSESE} -P ${REPDEST} ${SOURCE}"
                                $LCG_REP --vo ${TAGVO} -d ${CLOSESE} -P ${REPDEST} ${SOURCE}
                                [ $? -ne 0 ] && msgOut WARNING "Replication failed"
                                CLOSE_REPLICA="`getCloseReplica ${SOURCE}`"
                                [ "$CLOSE_REPLICA" != "" ] && SOURCE="$CLOSE_REPLICA"
                            else
                                msgOut WARNING "lcg-rep not found"
                                let getrc=70
                            fi
                        fi
                    fi
                else
                    msgOut WARNING "lcg-lr not found"
                    let getrc=70
                fi
            fi
            if [ "$LCG_CP" != "" ] ; then
                msgOut INFO  "Copying the file using ${SOURCE}"
                msgOut INFO  "Destination is ${DEST}"
                msgOut INFO  "LCG_GFAL_INFOSYS=${LCG_GFAL_INFOSYS}"
                msgOut INFO  "LFC_HOST=${LFC_HOST}"
                LCG_CP_VER="`$LCG_CP --version 2>/dev/null | grep ^lcg_util | cut -d'-' -f 2 | awk -F'.' '{for (i=1;i<=NF;i++) printf "%02d",$i;}'`"
                if [ $LCG_CP_VER -le 10600 ] ; then
                    LCG_CP_TIMEOUT="-t 1800"
                else
                    LCG_CP_TIMEOUT="--connect-timeout 1800 --sendreceive-timeout 1800"
                fi
                $LCG_CP $LCG_CP_TIMEOUT -v --vo ${TAGVO} ${SOURCE} ${DEST}
                if [ $? -ne 0 ] ; then
                    msgOut WARNING "Cannot get the file from the grid using ${SOURCE}"
                    msgOut INFO  "Trying using ${DEFSOURCE}"
                    $LCG_CP $LCG_CP_TIMEOUT -v --vo ${TAGVO} ${DEFSOURCE} ${DEST}
                    if [ $? -ne 0 ] ; then
                        msgOut WARNING "Cannot get the file from the grid using ${DEFSOURCE}"
                        let getrc=80
                    fi
                else
                    msgOut INFO  "Copy OK"
                fi
            else
                msgOut WARNING "lcg-cp not found"
                let getrc=70
            fi
        fi
    else
        msgOut WARNING "lcg-lg not found"
        let getrc=70
    fi
    return $getrc
}

putGridFile() {
    SOURCE="${1}"
    LFN="${2}"
    DESTPATH="install/lcg/`basename $SOURCE`"
    LCG_LG="`which lcg-lg`"
    LCG_CR="`which lcg-cr`"
    GUID=""
    putrc=0
    if [ "$LCG_LG" != "" ] ; then
        GUID="`lcg-lg --vo ${TAGVO} lfn:${LFN} 2>/dev/null`"
        if [ "$GUID" != "" ] ; then
            msgOut WARNING "${LFN} already present in the Grid"
            putrc=90
        fi
    fi
    if [ $putrc -eq 0 ] ; then
        if [ "$LCG_CR" != "" ] ; then
            msgOut INFO "Registering ${SOURCE} in the Grid"
            msgOut INFO "Using LFN ${LFN}"
            [ "$CLOSESE" != "" ] && CLOSESE_OPT="-d $CLOSESE"
            msgOut INFO "CMD: lcg-cr --vo ${TAGVO} -l ${LFN} -P ${DESTPATH} file:${SOURCE} ${CLOSESE_OPT}"
            lcg-cr --vo ${TAGVO} -l ${LFN} -P ${DESTPATH} file:${SOURCE} ${CLOSESE_OPT}
            putrc=$?
            [ $putrc -ne 0 ] && msgOut WARNING "Registration failed"
        else
            msgOut WARNING "lcg-cr not found"
            putrc=70
        fi
    fi
    return $putrc
}

setupDev() {
    SETUP_OPT="${1}"
    LASTCWD=$PWD
    REQFILE=$PWD/cmthome/requirements
    TESTAREA=$PWD/testarea
    msgOut INFO "Creating requirements file ${REQFILE}"
    [ ! -d "`dirname ${REQFILE}`" ] && mkdir -p "`dirname ${REQFILE}`"
    [ ! -d "${TESTAREA}" ] && mkdir -p "${TESTAREA}"
    rm -f ${REQFILE}
    cat > ${REQFILE} <<EORF
set CMTSITE ${CMTSITE}
set SITEROOT ${SITEROOT}
macro ATLAS_DIST_AREA ${SITEROOT}
apply_tag projectArea
macro SITE_PROJECT_AREA ${SITEROOT}
macro EXTERNAL_PROJECT_AREA ${SITEROOT}
apply_tag setup
apply_tag simpleTest
macro ATLAS_TEST_AREA ${TESTAREA}
EORF

    if [ "$PRJTYPE" == "eventview" ] ; then
        cat >> ${REQFILE} <<EORF
macro ATLAS_GROUP_AREA "`dirname ${SWPHYS}`"
EORF
    fi
    cat >> ${REQFILE} <<EORF
use AtlasLogin AtlasLogin-* \$(ATLAS_DIST_AREA)
set CMTCONFIG ${CMTCONFIG}
set DBRELEASE_INSTALLED  $DBRELEASE_INSTALLED
EORF
    crfrc=$?
    if [ $crfrc -eq 0 ] ; then
        msgOut INFO "`cat ${REQFILE}`"
        msgOut INFO "Configuring CMT"
        cd `dirname $REQFILE`
        cmt config
        let crfrc=$crfrc+$?
        if [ $crfrc -eq 0 ] ; then
            msgOut INFO "CMT configuration successful"
            msgOut INFO "Setting up the release from $PWD"
            msgOut INFO "source setup.sh $SETUP_OPT"
            source setup.sh $SETUP_OPT
            msgOut INFO "GroupArea=$GroupArea"
            msgOut INFO "JOBOPTSEARCHPATH=$JOBOPTSEARCHPATH"
        else
            msgOut ERROR "Error during CMT configuration"
        fi
        cd $LASTCWD
    else
        msgOut ERROR "Cannot create ${REQFILE}"
    fi
    return $crfrc
}

setCompiler() {
    COMP_PATH="`getROpath ${1}`"
    SITECONF="`getRWpath ${SITECONF}`"
    # Set the compiler hooks in the Site Configuration
    if [ -s "$SITECONF" ] ; then
        COMPILER_PATH="`cat $SITECONF | grep -v ^# | grep gcc${ARCH} | tail -n 1 | cut -d= -f 2`"
    fi
    if [ "$COMPILER_PATH" == "" -o "$COMPILER_PATH" != "${COMP_PATH}" ] ; then
        if [ -s "$SITECONF" ] ; then
            mv -f "$SITECONF" "${SITECONF}.orig"
            cat "${SITECONF}.orig" | grep -v "gcc${ARCH}=" > "$SITECONF"
        fi
        msgOut INFO "Adding gcc${ARCH}=${COMP_PATH} to $SITECONF"
        echo "gcc${ARCH}=${COMP_PATH}" >> $SITECONF
    else
        msgOut INFO "Compiler setup already present in $SITECONF for gcc${ARCH} ($COMPILER_PATH)"
    fi
    return 0
}

unsetCompiler() {
    SITECONF="`getRWpath ${SITECONF}`"
    # Unset the compiler hooks in the Site Configuration
    if [ -s "$SITECONF" ] ; then
        COMPILER_PATH="`cat $SITECONF | grep -v ^# | grep gcc${ARCH} | tail -n 1 | cut -d= -f 2`"
        if [ "$COMPILER_PATH"  != "" ] ; then
            msgOut INFO "Removing gcc${ARCH} from $SITECONF"
            mv -f "$SITECONF" "${SITECONF}.orig"
            cat "${SITECONF}.orig" | grep -v "gcc${ARCH}=" > "$SITECONF"
            [ ! -s "$SITECONF" ] && rm -f "$SITECONF"
        fi
    fi
    return 0
}

snap() {
    SNAPDIR="${1}"
    SNAPDIR_TMP="${SNAPDIR}.tmp.$$"
    SNAPNAME="${2}"
    SNAP="${SNAPDIR}/${SNAPNAME}"
    TAR_NAME=${SNAPNAME}.tar.gz
    NEW_SNAP="no"
    let snaprc=0

    # If the Grid caching is enabled try to get the file from a SE
    if [ "$USEGRID" == "yes" ] ; then
        mkdir -p "${SNAPDIR_TMP}"
        cd "${SNAPDIR_TMP}"
        getGridFile ${CATALOG_PATH}/${TAR_NAME} ${PWD}/${TAR_NAME}
        if [ -s $PWD/$TAR_NAME ] ; then
            msgOut INFO "Snapshot tarball copied to ${PWD}/${TAR_NAME}"
            msgOut INFO "`\ls -l ${PWD}/${TAR_NAME}`"
            tar xfz $TAR_NAME
            if [ $? -ne 0 ] ; then
                msgOut ERROR "Failed to untar the snapshot tarball"
            else
                msgOut INFO "Snapshot tarball unpacked successfully"
                md5sum -c MD5SUM > /dev/null
                if [ $? -ne 0 ] ; then
                    msgOut ERROR "Checksum error in the snapshot files"
                else
                    msgOut INFO "Snapshot checksum OK"
                    rm -fr ${SNAP}*
                    SNAPSHOT="`\ls -d ${SNAPNAME}.snap* 2>/dev/null | tail -n 1`"
                    if [ "$SNAPSHOT" != "" ] ; then
                        [ ! -d "${SNAPDIR}" ] && mkdir -p "${SNAPDIR}"
                        mv ${SNAPSHOT} ${SNAPDIR}
                        msgOut INFO "Snapshot ${SNAPSHOT} moved to ${SNAPDIR}"
                        msgOut INFO "Listing contents of dir ${SNAPDIR}"
                        msgOut INFO "`\ls -l ${SNAPDIR} 2>/dev/null`"
                        msgOut INFO "Listing details of the snapshot"
                        msgOut INFO "`\du -sk -l ${SNAP}.snap* 2>/dev/null`"
                    else
                        msgOut ERROR "Cannot find the snapshot"
                    fi
                fi
            fi
        fi
        cd -
        rm -fr ${SNAPDIR_TMP}
    fi

    # Make the snapshot, if needed
    SNAPSHOT="`\ls -ld ${SNAP}.snap* 2>/dev/null | tail -n 1`"
    if [ "${SNAPSHOT}" == "" ] ; then
        msgOut INFO "Cannot find snapshot called ${SNAP}.snap*"
        msgOut INFO "Downloading and snapshotting"
        msgOut INFO "Snapshot name: `basename ${SNAP}`"
        NEW_SNAP="yes"
        if [ "$PACMAN_OPTS" != "" ] ; then
            pacman $PACMAN_OPTS
            if [ `echo $PACMAN_VER | awk -F. '{printf "%d%02d%02d",$1,$2,$3}'` -lt 31800 ] ; then
                pacman -v down tar up
            else
                pacman -v download tar up
            fi
            pacman -def
        fi
        TMPAREA="${TOPDIR}/tmp.$$"
        TMPDIR="/tmp/atlas-install-$PRJNAME-$RELEASE"
        mkdir -p "${TMPAREA}"
        let snaprc=$snaprc+$?
        if [ $snaprc -ne 0 ] ; then
            msgOut ERROR "Cannot create ${TMPAREA}"
            return $snaprc
        fi
        ln -sf ${TMPAREA} ${TMPDIR}
        let snaprc=$snaprc+$?
        if [ $snaprc -ne 0 ] ; then
            msgOut ERROR "Cannot link ${TMPAREA} to ${TMPDIR}"
            return $snaprc
        fi
        let snaprc=$snaprc+$?
        cd "${TMPDIR}"
        if [ "$PACKOPT" == "all" ] ; then
            echo y | pacman $PACMAN_OPTS -fetch \
                     ${LCGCACHE}:${RELEASE}/${GCC}
            let snaprc=$snaprc+$?
            echo y | pacman $PACMAN_OPTS -fetch \
                     ${LCGCACHE}:${RELEASE}/${KV}
            let snaprc=$snaprc+$?
        fi
        echo "pacman $PACMAN_OPTS -fetch \"${ATLAS}:${ATLASRELEASE}\""
        echo y | pacman $PACMAN_OPTS -fetch "${ATLAS}:${ATLASRELEASE}"
        let snaprc=$snaprc+$?
        if [ $snaprc -ne 0 ] ; then
            msgOut ERROR "Cannot fetch ${ATLAS}:${ATLASRELEASE}"
            return $snaprc
        fi
        if [ "$EXTRPKG" != "" ] ; then
            echo "pacman $PACMAN_OPTS -fetch ${ATLAS}:${EXTRAPKG}"
            echo y | pacman $PACMAN_OPTS -fetch ${ATLAS}:${EXTRAPKG}
            let snaprc=$snaprc+$?
            if [ $snaprc -ne 0 ] ; then
                msgOut ERROR "Cannot fetch ${ATLAS}:${EXTRAPKG}"
                return $snaprc
            fi
        fi
        [ ! -d "${SNAPDIR}" ] && mkdir -p "${SNAPDIR}"
        pacman -snap -o "${SNAP}" .
        let snaprc=$snaprc+$?
        if [ $snaprc -ne 0 ] ; then
            msgOut ERROR "Cannot create the snapshot ${SNAP}"
            return $snaprc
        fi
        cd "${TOPDIR}"
        # Clean up the temporary directory and link
        rm -fr ${TMPDIR}
        let snaprc=$snaprc+$?
        if [ $snaprc -ne 0 ] ; then
            msgOut ERROR "Cannot remove the temporary link ${TMPDIR}"
            return $snaprc
        fi
        rm -fr ${TMPAREA}
        let snaprc=$snaprc+$?
        if [ $snaprc -ne 0 ] ; then
            msgOut ERROR "Cannot remove the temporary area ${TMPAREA}"
            return $snaprc
        fi

        # Register the tarball to the Grid, if required
        if [ "$USEGRID" == "yes" -a "$NEW_SNAP" == "yes" ] ; then
            cd "$SNAPDIR"
            # Checksums
            msgOut INFO "Calculating checksums"
            \find ${SNAPNAME}.* -type f -exec md5sum {} \; > MD5SUM
            let snaprc=$snaprc+$?
            # Create the tarball
            msgOut INFO "Creating the installation tarball"
            tar cfz ${TAR_NAME} ${SNAPNAME}.* MD5SUM
            let snaprc=$snaprc+$?
            if [ $snaprc -eq 0 ] ; then
                msgOut INFO "Registering the installation tarball to the Grid"
                putGridFile $PWD/${TAR_NAME} ${CATALOG_PATH}/${TAR_NAME}
            else
                msgOut ERROR "Cannot create ${TAR_NAME}"
            fi
            if [ -s "${TAR_NAME}" ] ; then
                msgOut INFO "Removing ${TAR_NAME}"
                rm -fr "${TAR_NAME}"
            fi
        fi
    else
        msgOut INFO "Snapshot found: ${SNAPSHOT}"
    fi
    msgOut INFO "Snapshot processing OK"
    return $snaprc
}

pacball() {
    PBDIR="${1}"
    PBDIR_TMP="${PWD}/pacballs.tmp.$$"
    PBNAME="${2}"
    TAR_NAME="${PBNAME}.tar.gz"
    PB="${PBDIR}/${PBNAME}"
    NEW_PB="no"
    let pbrc=0

    # Check if a pacball is available from TOPDIR and use it
    if [ -s "${TOPDIR}/${PBNAME}" ] ; then
      [ ! -d "${PBDIR}" ] && mkdir -p "${PBDIR}"
      if [ $? -ne 0 ] ; then
         msgOut ERROR "Cannot create ${PBDIR}"
         return 1
      fi
      ln -sf "${TOPDIR}/${PBNAME}" "$PB"
    fi

    # Start the pacball processing
    if [ ! -s $PB ] ; then
        # Create a temporary directory ad use it for the pacball downloads or creation
        mkdir -p "${PBDIR_TMP}"
        if [ $? -ne 0 ] ; then
            msgOut ERROR "Cannot create ${PBDIR_TMP}"
            return 1
        fi
        cd "${PBDIR_TMP}"

        # If the Grid caching is enabled try to get the file from a SE
        if [ "$USEGRID" == "yes" ] ; then
            rm -fr ${PBDIR_TMP}/*
            getGridFile ${CATALOG_PATH}/${PBNAME} ${PWD}/${PBNAME}
            if [ -s $PWD/$PBNAME ] ; then
                msgOut INFO "Pacball copied to ${PWD}/${PBNAME}"
                msgOut INFO "`\ls -l ${PWD}/${PBNAME}`"
            fi
        fi

        # If we failed to get the pacball from the grid or we didn't enable
        # the grid retrieval and the pacball is not available,
        # try to get it from the web repository
        PACBALL="`\ls -d ${PBNAME} 2>/dev/null | tail -n 1`"
        if [ "${PACBALL}" == "" -a "${PACBALLREPO}" != "" ] ; then
            rm -fr ${PBDIR_TMP}/*
            msgOut INFO "Cannot find any pacball called ${PBNAME}"
            msgOut INFO "Trying to download it from ${PACBALLREPO}"
            wget -q ${PACBALLREPO}/${PBNAME}
            if [ $? -eq 0 -a -s $PWD/$PBNAME ] ; then
                msgOut INFO "Pacball downloaded to ${PWD}/${PBNAME}"
                msgOut INFO "`\ls -l ${PWD}/${PBNAME}`"
            else
                msgOut WARNING "Failed to download the pacball from ${ATLAS}/${PBNAME}"
            fi
        fi

        # Make the pacball, if needed
        PACBALL="`\ls -d ${PBNAME} 2>/dev/null | tail -n 1`"
        if [ "${PACBALL}" == "" ] ; then
            rm -fr ${PBDIR_TMP}/*
            msgOut INFO "Cannot find any pacball called ${PBNAME}"
            msgOut INFO "Downloading and creating the pacball"
            msgOut INFO "Pacball name: ${PBNAME}"
            [ "`which pacman 2>/dev/null`" == "" ] && setupPacman
            NEW_PB="yes"
            if [ "$PACMAN_OPTS" != "" -a "$USEPACBALL" != "yes" ] ; then
                pacman $PACMAN_OPTS
                if [ `echo $PACMAN_VER | awk -F. '{printf "%d%02d%02d",$1,$2,$3}'` -lt 31800 ] ; then
                    pacman -v down tar up
                else
                    pacman -v download tar up
                fi
                pacman -def
            fi
            TMPAREA="${PBDIR_TMP}/tmp.$$"
            TMPDIR="/tmp/atlas-install-$PRJNAME-$RELEASE"
            mkdir -p "${TMPAREA}"
            let pbrc=$pbrc+$?
            if [ $pbrc -ne 0 ] ; then
                msgOut ERROR "Cannot create ${TMPAREA}"
                return $pbrc
            fi
            ln -sf ${TMPAREA} ${TMPDIR}
            let pbrc=$pbrc+$?
            if [ $pbrc -ne 0 ] ; then
                msgOut ERROR "Cannot link ${TMPAREA} to ${TMPDIR}"
                rm -fr "${TMPAREA}"
                return $pbrc
            fi
            let pbrc=$pbrc+$?
            cd "${TMPDIR}"
            PBPKG="`echo ${PBNAME} | cut -d'.' -f 1`"
            echo "pacman $PACMAN_OPTS -pacball ${ATLAS}:${PBPKG}"
            echo y | pacman $PACMAN_OPTS -pacball ${ATLAS}:${PBPKG}
            let pbrc=$pbrc+$?
            if [ $pbrc -eq 0 ] ; then
                mv ${PBPKG}.*.sh ${PBDIR_TMP}/${PBNAME} 2> /dev/null
            else
                msgOut ERROR "Cannot create the pacball ${PBPKG} from ${ATLAS}:${PBPKG}"
            fi
            cd "${PBDIR_TMP}"
            # Clean up the temporary directory and link
            rm -fr ${TMPDIR}
            let pbrc=$pbrc+$?
            [ $pbrc -ne 0 ] && msgOut ERROR "Cannot remove the temporary link ${TMPDIR}"
            rm -fr ${TMPAREA}
            let pbrc=$pbrc+$?
            [ $pbrc -ne 0 ] && msgOut ERROR "Cannot remove the temporary area ${TMPAREA}"

            # Register the tarball to the Grid, if required
            if [ "$USEGRID" == "yes" -a "$NEW_SNAP" == "yes" -a $pbrc -eq 0 ] ; then
                if [ $pbrc -eq 0 ] ; then
                    msgOut INFO "Registering the pacball to the Grid"
                    putGridFile $PBDIR_TMP}/${PBNAME} ${CATALOG_PATH}/${PBNAME}
                else
                    msgOut ERROR "Cannot register ${PBNAME} to the grid"
                fi
            fi
        fi

        # Check if we  finally get a pacball
        cd "${PBDIR_TMP}"
        PACBALL="`\ls -d ${PBNAME} 2>/dev/null | tail -n 1`"
        if [ $pbrc -eq 0 -a "${PACBALL}" != "" ] ; then
            msgOut INFO "Pacball container found: ${PBNAME}"
            MD5SUM="`echo ${PBNAME} | sed 's/.*\.md5-\(.*\).sh/\1/g'`"
            echo "$MD5SUM  $PBNAME" > MD5SUM
            msgOut INFO "Checking the pacball integrity using md5"
            msgOut INFO "`/bin/cat MD5SUM`"
            md5sum -c MD5SUM > /dev/null
            let pbrc=$pbrc+$?
            if [ $pbrc -ne 0 ] ; then
                msgOut ERROR "Checksum error in the pacball file"
            else
                msgOut INFO "Pacball checksum OK"
                [ ! -d "${PBDIR}" ] && mkdir -p "${PBDIR}"
                rm -fr ${PBDIR}/${PBNAME}
                mv ${PBNAME} ${PBDIR}
                msgOut INFO "Pacball ${PBNAME} moved to ${PBDIR}"
                msgOut INFO "Listing contents of dir ${PBDIR}"
                msgOut INFO "`\ls -l ${PBDIR} 2>/dev/null`"
                msgOut INFO "Listing details of the pacball"
                msgOut INFO "`\du -sk -l ${PBDIR}/${PBNAME} 2>/dev/null`"
            fi
        fi
    else
        msgOut INFO "Pacball found in ${PB}"
    fi
    if [ $pbrc -eq 0 ] ; then
        msgOut INFO "Pacball processing OK"
    else
        msgOut INFO "Failed to process the pacball"
    fi
    rm -fr "${PBDIR_TMP}"
    return $pbrc
}

OSGTags() {
    local TU_OPTS=`getopt -o adlLprtV -l add,ce:,debug,file:,list,location:,project:,remove,tags:,vo:,version -- "$@"`
    if [ $? != 0 ] ; then echo "Terminating..."; return -1 ; fi
    eval set -- "$TU_OPTS"

    # Defaults
    local TU_CE=
    local TU_DEBUG="no"
    local TU_TFILE=
    local TU_LOCATION=
    local TU_MODE="list"
    local TU_PROJECT=
    local TU_TAGS=
    local TU_VER="OSGTags v0.2 - (c) Alessandro De Salvo <Alessandro.DeSalvo@roma1.infn.it> - 20090211"
    local TU_VO="atlas"
    local TU_RC=0

    while true ; do
        case "$1" in
            --add|-a)      TU_MODE="add";shift;;
            --debug|-d)    TU_DEBUG="yes";shift;;
            --ce)          TU_CE="$2";shift 2;;
            --file|-f)     TU_TFILE="$2";shift 2;;
            --list|-l)     TU_MODE="list";shift;;
            --location|-L) TU_LOCATION="$2";shift 2;;
            --project|-p)  TU_PROJECT="$2";shift 2;;
            --remove|-r)   TU_MODE="remove";shift;;
            --tags|-t)     TU_TAGS="$2";shift 2;;
            --vo)          TU_VO="$2";shift 2;;
            --version|-V)  echo $TU_VER;return 0;;
            --)            shift;break;;
            \?)            break;
            exit;;
        esac
    done

    # Check the CLI syntax
    if [ "$TU_TFILE" == "" ] ; then
        if [ "$OSG_APP" != "" ] ; then
            if [ ! -d "$OSG_APP/etc" ] ; then
                echo "Cannot find dir $OSG_APP/etc"
                return 1
            fi
            TU_TFILE="$OSG_APP/etc/grid3-locations.txt"
        else
            echo "No output file specified and OSG_APP not defined! Please use --file <output file>."
            return 1
        fi
    fi
    if [ "$TU_MODE" != "list" -a "$TU_TAGS" == "" ] ; then
        echo "No tags specified! Please use --tags <tag list>."
        return 2
    fi
    if [ "$TU_MODE" != "list" -a "$TU_LOCATION" == "" ] ; then
        echo "No location specified! Please use --location <path>."
        return 3
    fi
    if [ "$TU_MODE" != "list" -a "$TU_PROJECT" == "" ] ; then
        echo "No project specified! Please use --project <path>."
        return 4
    fi

    local TU_TAGLINE=""
    local TU_TAG=""

    # Perform the actions

    # Xin Zhao -- move the lock file to $OSG_APP/atlas_app/atlas_rel, 
    # since not all OSG sites allow write permission to the whole $OSG_APP/etc dir
    TU_LOCKFILE=${RELLOC}/../`basename ${TU_TFILE}.lock`
    echo "Using Lockfile $TU_LOCKFILE"
    
    if [ "$TU_MODE" == "add" ] ; then
        [ "$TU_DEBUG" == "yes" ] && echo "Adding tags ${TU_TAGS} to ${TU_TFILE}"
        if [ -f "${TU_LOCKFILE}" ] ; then
            echo "File lock exists: ${TU_LOCKFILE}"
            echo "Aborting the tag operations"
            return 10
        else
            if [ -f ${TU_TFILE} ] ; then
                \cp "${TU_TFILE}" "${TU_LOCKFILE}"
            else
                touch "${TU_LOCKFILE}"
            fi
            if [ $? -ne 0 ] ; then
                echo "Cannot create lock file ${TU_LOCKFILE}"
                echo "Aborting the tag operations"
                return 11
            else
                for TU_TAG in "`echo ${TU_TAGS} | sed 's/,/ /g'`"; do
                    TU_TAGLINE="${TU_TAG} ${TU_PROJECT} ${TU_LOCATION}"
                    TU_FTAG="`grep "${TU_TAGLINE}" "${TU_TFILE}" 2>/dev/null`"
                    if [ "$TU_FTAG" == "" ] ; then
                        [ "$TU_DEBUG" == "yes" ] && echo "Adding tag ${TU_TAGLINE} to ${TU_TFILE}"
                        echo "${TU_TAGLINE}" >> "${TU_LOCKFILE}"
                        if [ $? -ne 0 ] ; then
                            echo "Cannot add new tags to file ${TU_LOCKFILE}"
                            echo "Aborting the tag operations"
                            rm -f "${TU_LOCKFILE}"
                            return 12
                        fi
                    else
                        echo "The tag ${TU_TAGLINE} is already present in ${TU_TFILE}"
                    fi
                done
                \cp "${TU_LOCKFILE}" "${TU_TFILE}"
                if [ $? -ne 0 ] ; then
                    echo "Cannot finalize the update to file ${TU_TFILE}"
                    echo "Aborting the tag operations"
                    rm -f "${TU_LOCKFILE}"
                    return 13
                fi 
                [ "$TU_DEBUG" == "yes" ] && echo "Tags added succesfully to ${TU_TFILE}"
            fi 
            rm -f "${TU_LOCKFILE}"
        fi
    elif [ "$TU_MODE" == "remove" ] ; then
        [ "$TU_DEBUG" == "yes" ] && echo "Removing tags ${TU_TAGS} from ${TU_TFILE}"
        if [ -f "${TU_LOCKFILE}" ] ; then
            echo "File lock exists: ${TU_LOCKFILE}"
            echo "Aborting the tag operations"
            return 20
        else
            local TU_FTAG=""
            [ ! -f "${TU_TFILE}" ] && touch "${TU_TFILE}"
            touch "${TU_LOCKFILE}"
            for TU_TAG in "`echo ${TU_TAGS} | sed 's/,/ /g'`"; do
                TU_TAGLINE="${TU_TAG} ${TU_PROJECT} ${TU_LOCATION}"
                TU_FTAG="`grep "${TU_TAGLINE}" "${TU_TFILE}"`"
                if [ "$TU_FTAG" != "" ] ; then
                    [ "$TU_DEBUG" == "yes" ] && echo "Removing tag ${TU_TAGLINE} from ${TU_TFILE}"
                    grep -v "${TU_TAGLINE}" "${TU_TFILE}" > "${TU_LOCKFILE}"
                    if [ $? -ne 0 -a `cat ${TU_TFILE} | wc -l` -gt 1 ] ; then
                        echo "Cannot create lock file ${TU_LOCKFILE} while removing tag ${TU_TAGLINE}"
                        echo "Aborting the tag operations"
                        rm -f "${TU_LOCKFILE}"
                        return 21
                    else
                        \cp "${TU_LOCKFILE}" "${TU_TFILE}"
                        if [ $? -ne 0 ] ; then
                            echo "Cannot finalize the update to file ${TU_TFILE} while removing tag ${TU_TAGLINE}"
                            echo "Aborting the tag operations"
                            rm -f "${TU_LOCKFILE}"
                            return 22
                        fi 
                        [ "$TU_DEBUG" == "yes" ] && echo "Tag ${TU_TAGLINE} removed successfully from $TU_TFILE"
                    fi 
                else
                    echo "No tag ${TU_TAGLINE} found in ${TU_TFILE}"
                fi 
            done
            rm -f "${TU_LOCKFILE}"
        fi
    else
        [ "$TU_DEBUG" == "yes" ] && echo "Listing tags from $TU_TFILE"
        if [ -f "${TU_TFILE}" ] ; then
            cat "$TU_TFILE"
            if [ $? -ne 0 ] ; then
                echo "Cannot list the tag file ${TU_TFILE}"
                return 30
            fi 
        else
            echo "File not found: ${TU_TFILE}"
        fi 
    fi
    return 0
}

prepareInstallDirs() {
    # Check if we're running in AFS and correct the installation path, if needed
    if [ "`echo $RELLOC | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] ; then
        # Check if we are already in the rw path
        if [ "`echo $RELLOC | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
            AFSRELLOC=$RELLOC
            RELLOC="`echo $RELLOC | sed 's#^/afs/\(.*\)#/afs/.\1#g'`"
            msgOut INFO "Using physical path $RELLOC"
            msgOut INFO "Will relocate to $AFSRELLOC"
        fi
    fi
    if [ "`echo $SWLOC | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] ; then
        # Check if we are already in the rw path
        if [ "`echo $SWLOC | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
            AFSLOC=$SWLOC
            SWLOC="`echo $SWLOC | sed 's#^/afs/\(.*\)#/afs/.\1#g'`"
            msgOut INFO "Using logical path $SWLOC"
            msgOut INFO "Will relocate to $AFSLOC"
        fi
    fi

    # Start preparing the dirs
    # Logical install dir
    if [ "$SWPATH" != "" ] ; then
        [ ! -d $SWPATH ] && mkdir -p "${SWPATH}"
        \find $SWPATH -maxdepth 1 -type d ! -perm -a+rx -exec chmod a+rx {} \;
        msgOut INFO "SWPATH: `ls -ld $SWPATH`"
    fi

    # Physical install dir
    if [  ! -d ${RELLOC} ] ; then
        if [ "$AFSRELLOC" != "" ] ; then
            # Create any missing directory
            [ ! -d "`dirname ${RELLOC}`" ] && mkdir -p "`dirname ${RELLOC}`"
            # Create a new volume for this physical installation, if possible
            AFSCREATE="`which afs_create 2>/dev/null`"
            if [ "$AFSCREATE" != "" ] ; then
                msgOut INFO "Available disk space in RELLOC before AFS volume creation: `getDiskFree ${RELLOC}`"
                msgOut INFO "Creating a new AFS volume for $RELLOC"
                msgOut INFO "Executing $AFSCREATE ${RELLOC}"
                $AFSCREATE "${RELLOC}"
                [ $? -eq 0 ] && msgOut INFO "AFS volume created successfully" \
                             || msgOut ERROR "Cannot create AFS volume - ErrCode: $?"
                msgOut INFO "Available disk space in RELLOC after AFS volume creation: `getDiskFree ${RELLOC}`"
                msgOut INFO "Mount point info for ${RELLOC}"
                msgOut INFO "`fs lq ${RELLOC}`"
            else
                msgOut WARNING "No afs_create command found"
                msgOut WARNING "PATH=$PATH"
            fi
        fi
    fi
    [  ! -d ${RELLOC} ] && mkdir -p "${RELLOC}"
    \find $RELLOC -maxdepth 1 -type d ! -perm -a+rx -exec chmod a+rx {} \;
    if [ ! -d ${SWLOC} -a "${PRJTYPE}" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "$PRJTYPE" != "eventview" -a "$SWLOC" != "$RELLOC" ] ; then
        msgOut ERROR "Missing logical installation dir (${SWLOC}). Trying to create it."
        mkdir -p "${SWLOC}"
        if [  $? -ne 0  ] ; then
            msgOut ERROR "Cannot create ${SWLOC}."
            return 120
        else
            chmod g-s "${SWLOC}"
            msgOut INFO "Logical installation dir created successfully."
        fi
    fi
    \find $SWLOC -maxdepth 1 -type d ! -perm -a+rx -exec chmod a+rx {} \;
    [ -d $SWLOC ] && msgOut INFO "SWLOC: `ls -ld $SWLOC`"
    if [ ! -d ${RELLOC} ] ; then
        msgOut ERROR "Missing physical installation dir (${RELLOC}). Trying to create it."
        mkdir -p "${RELLOC}"
        if [  $? -ne 0  ] ; then
            msgOut ERROR "Cannot create ${RELLOC}."
            return 121
        else
            chmod g-s "${RELLOC}"
            msgOut INFO "Physical installation dir created successfully."
        fi
    fi
    \find $RELLOC -maxdepth 1 -type d ! -perm -a+rx -exec chmod a+rx {} \;
    [ -d $RELLOC ] && msgOut INFO "RELLOC: `ls -ld $RELLOC`"
    return 0
}


install() {
    cd ${TOPDIR}
    let instrc=0
    SWPHYS=${RELLOC}
    SWLOG=${SWLOC}
    if [ "${SWPATH}" != "" ] ; then
        SWPHYS="$SWPATH"
        SWLOG="$SWPATH"
    fi

    # Release platform,arch and compiler
    REL_PLAT="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\2/g'`"
    REL_ARCH="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\1/g'`"
    REL_COMP="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\3/g'`"

    # Define the lock file
    LOCKFILE=${SWPHYS}/atlas-install.lock

    # Wait for previous installation process completion
    if [ -f ${LOCKFILE} ] ; then
        msgOut WARNING "Another installation process is currently active. Now waiting..."
        waittime=0
        while `test -f ${LOCKFILE}`; do
            sleep 1s
            let waittime=$waittime+1
            if [ $waittime -gt 3600 ] ; then
                msgOut WARNING "Timeout [3600 s]"
                msgOut WARNING "Removing stale installation lock"
                rm -f ${LOCKFILE}
            fi
        done
    fi
    msgOut INFO "Locking the installation area"
    echo "$RELEASE installation lock" > ${LOCKFILE}
    case `whoami` in
        usatlas*) msgOut INFO "This is an OSG site with static accounts. No further action required"
            ;;
        AAA*[0-9])
            msgOut INFO "This site is configured for SGM pool accounts. Changing group permissions to ${LOCKFILE}"
            chmod -R g+rw ${LOCKFILE} 2>/dev/null
            [ $? -ne 0 ] && msgOut ERROR "Cannot change group write permissions to ${LOCKFILE}"
        ;;
    esac

    # Installation options
    if [ "$NOCACHE" == "yes" ] ; then
        RELSNAP=${ATLAS}
        GCCSNAP=${LCGCACHE}
        KVSNAP=${LCGCACHE}
    elif [ "${PRJTYPE}" != "poolcond" ] ; then
        if [ "$USEPACBALL" != "yes" ] ; then
            SNAPN=${SWPHYS}/atlas-install.snapshot
            snap "${SNAPDIR}" "${SNAPNAME}"
        else
            SNAPN=${SWPHYS}/atlas-install.pacball
            pacball "${SNAPDIR}" "${SNAPNAME}"
        fi
        RELSNAP=${SNAPN}
        GCCSNAP=${SNAPN}
        KVSNAP=${SNAPN}
        let instrc=$instrc+$?
        if [ $instrc -eq 0 ] ; then
            if [ "$USEPACBALL" != "yes" ] ; then
                SNAPSHOT="`\ls -d ${SNAPDIR}/${SNAPNAME}*snap* 2>/dev/null | tail -n 1`"
                if [ "$SNAPSHOT" != "" ] ; then
                    msgOut INFO "Using snapshot ${SNAPSHOT}"
                    msgOut INFO "Linking snapshot to ${SNAPN}"
                    ln -sf ${SNAPSHOT} ${SNAPN}
                    msgOut INFO "`ls -l ${SNAPN}`"
                else
                    msgOut ERROR "Cannot find any snapshot called ${SNAPDIR}/${SNAPNAME}*snap*"
                    msgOut INFO "Unlocking the installation area"
                    rm -f ${LOCKFILE}
                    return 110
                fi
            else
                PB="`\ls -d ${SNAPDIR}/${SNAPNAME} 2>/dev/null | tail -n 1`"
                if [ "$PB" != "" ] ; then
                    msgOut INFO "Using pacball ${PB}"
                    msgOut INFO "Linking pacball to ${SNAPN}"
                    ln -sf ${PB} ${SNAPN}
                    msgOut INFO "`ls -l ${SNAPN}`"
                else
                    msgOut ERROR "Cannot find any pacball called ${SNAPDIR}/${PB}"
                    msgOut INFO "Unlocking the installation area"
                    rm -f ${LOCKFILE}
                    return 110
                fi
            fi
        else
            msgOut INFO "Unlocking the installation area"
            rm -f ${LOCKFILE}
            return $instrc
        fi
    fi

    # Check the installation dirs
    prepareInstallDirs
    instrc=$?
    if [ $instrc -ne 0 ] ; then
        msgOut ERROR "Skipping the installation task."
        msgOut INFO "Unlocking the installation area"
        rm -f ${LOCKFILE}
        return $instrc
    fi

    # Handle the patches to releases and EventView caches
    if [ "${PRJTYPE}" == "patch" -o "${PRJTYPE}" == "p1patch" -o "$PRJTYPE" == "t0patch" -o "${PRJTYPE}" == "p1nightly" -o "${PRJTYPE}" == "eventview" ] ; then
        MAINRELEASE="`echo $RELEASE | cut -d "." -f 1-3`"
        RELMAJOR="`echo $RELEASE | cut -d "." -f 1`"
        if [ $RELMAJOR -lt 12 ] ; then
            msgOut ERROR "Installation of patches or PAT tools not supported for releases < 12.0.0"
            msgOut INFO "Unlocking the installation area"
            rm -f ${LOCKFILE}
            return 130
        fi
        if [ ! -s ${RELLOC}/cmtsite/setup.sh ] ; then
            msgOut ERROR "No $MAINRELEASE release setup file found. Please install $MAINRELEASE first."
            msgOut INFO "Unlocking the installation area"
            rm -f ${SNAPN}
            rm -f ${LOCKFILE}
            return 131
        fi
        # Setup the main release
        msgOut INFO "Trying to setup release $MAINRELEASE."
        [ "${REQPRJNAME}" != "" ] && RPNAME="${REQPRJNAME}" || RPNAME="${PRJNAME}"
        # For slc5 releases or later, set some additional tags
        if [ $REL_PLAT -ge 5 ] ; then
            RUNTIME_TAGS=",gcc${REL_COMP},slc${REL_PLAT}"
            [ "$REL_ARCH" == "i686" ] && RUNTIME_TAGS="${RUNTIME_TAGS},32" || RUNTIME_TAGS="${RUNTIME_TAGS},64"
        fi
        msgOut INFO "source ${RELLOC}/cmtsite/setup.sh -tag=${MAINRELEASE},${RPNAME},${PRJOPT},${RUNTIME_TAGS}"
        source ${RELLOC}/cmtsite/setup.sh -tag=${MAINRELEASE},${RPNAME},${PRJOPT}${RUNTIME_TAGS}
        if [ ! -d ${CMTPATH} ] ; then
            msgOut ERROR "${RPNAME} $MAINRELEASE not found in $RELLOC. Please install release $MAINRELEASE first."
            msgOut INFO "Unlocking the installation area"
            rm -f ${SNAPN}
            rm -f ${LOCKFILE}
            return 132
        else
            msgOut INFO "${RPNAME} ${MAINRELEASE} found in $SITEROOT."
        fi
    fi

    # Setup the DDM
    if [ "$DDMSETUP" != "" -a -s "$DDMSETUP" ] ; then
        source $DDMSETUP
        if [ $? -eq 0 ] ; then
            msgOut INFO "DDM configured from $DDMSETUP"
        else
            msgOut ERROR "Cannot configure DDM from $DDMSETUP"
        fi
    else
        [ "$DDMSETUP" != "" ] && msgOut ERROR "No DDM setup file found in $DDMSETUP"
    fi

    # Start the installation
    cd "${SWPHYS}"
    msgOut INFO "Starting the installation"
    msgOut INFO "Installation type: ${PRJNAME}"
    msgOut INFO "PATH=${PATH}"
    msgOut INFO "Physical area: ${SWPHYS}"
    [ "${PRJTYPE}" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "${PRJTYPE}" != "eventview" -a "$SWLOC" != "$RELLOC" ] && \
    msgOut INFO "Logical area:  ${SWLOG}"
    msgOut INFO "Starting physical installation in ${PWD}"
    if [ "$DEBUG" == "yes" ] ; then
        msgOut DEBUG "PATH=${PATH}"
        msgOut DEBUG "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
        msgOut DEBUG "PYTHONPATH=${PYTHONPATH}"
    fi
    msgOut INFO "Listing the current directory contents"
    msgOut INFO "`\ls -l`"

    if [ "${PRJTYPE}" == "poolcond" ] ; then
        genPoolcondPFC
        let instrc=$?
        if [ $instrc -eq 0 ] ; then
            setLocalConfig
            let instrc=$instrc+$?
        else
            msgOut INFO "Skipping the local configuration setup"
        fi
    else
        if [ "$PACMAN_OPTS" != "" -a "$USEPACBALL" != "yes" ] ; then
            msgOut INFO "pacman $PACMAN_OPTS"
            pacman $PACMAN_OPTS
            let instrc=$instrc+$?
            if [ `echo $PACMAN_VER | awk -F. '{printf "%d%02d%02d",$1,$2,$3}'` -lt 31800 ] ; then
                pacman -v down tar up
            else
                msgOut INFO "pacman -v download tar up $PACMAN_OPTS"
                pacman -v download tar up $PACMAN_OPTS
            fi
            let instrc=$instrc+$?
            pacman -def
            let instrc=$instrc+$?
        fi
        rm -f *.tar

        if [ "$PACKOPT" == "all" -a "$USEPACBALL" != "yes" ] ; then
            # Install the compiler for this release using the cached files
            PACMAN_CMD="-get ${GCCSNAP}:${RELEASE}/${GCC}"
            [ "$UPDATE" == "yes" ] && PACMAN_CMD="$PACMAN_CMD -update ${GCCSNAP}:${RELEASE}/${GCC}"
            msgOut INFO "Executing pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
            echo y | \
            pacman ${PACMAN_OPTS} ${PACMAN_CMD}
            let instrc=$instrc+$?
            source setup.sh
        elif [ "$PACKOPT" != "all" -a "$INSTCOMPILER" != "" ] ; then
            COMPILER_VER="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\3/g'`"
            [ ! -d $VO_ATLAS_SW_DIR/gcc/${COMPILER_VER} ] && mkdir -p $VO_ATLAS_SW_DIR/gcc/${COMPILER_VER}
            cd $VO_ATLAS_SW_DIR/gcc/${COMPILER_VER}
            msgOut INFO "Installing the compiler ${GCC} in ${PWD}"
            PACMAN_CMD="-get ${LCGCACHE}:${RELEASE}/${GCC}"
            [ "$UPDATE" == "yes" ] && PACMAN_CMD="$PACMAN_CMD -update ${LCGCACHE}:${RELEASE}/${GCC}"
            msgOut INFO "Executing pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
            echo y | pacman ${PACMAN_OPTS} ${PACMAN_CMD}
            let instrc=$instrc+$?
            source setup.sh
            cd -

            # Add this custom compiler to the list of site compilers
            if [ $instrc -eq 0 -a "${GCC_DIR}" != "" ] ; then
                setCompiler $VO_ATLAS_SW_DIR/gcc/${COMPILER_VER}/${GCC_DIR}
            else
                msgOut INFO "Compiler installation failed or GCC_DIR not set"
            fi
        fi
        # Install the selected extra packages
        if [ "$EXTRAPKG" != "" ] ; then
            [ "`which pacman 2>/dev/null`" == "" ] && setupPacman
            PACMAN_CMD="-get ${RELSNAP}:${EXTRAPKG}"
            [ "$UPDATE" == "yes" ] && PACMAN_CMD="$PACMAN_CMD -update ${RELSNAP}:${EXTRAPKG}"
            msgOut INFO "Executing pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
            echo y | \
            pacman ${PACMAN_OPTS} ${PACMAN_CMD}
            let instrc=$instrc+$?
            if [ $instrc -ne 0 ] ; then
                msgOut ERROR "Physical area installation FAILED"
                msgOut ERROR "`pacman -last 2>&1`"
                OFFENDINGPKG="`pacman -last 2>&1 | grep -i 'has not been installed' | sed 's/\(.*\)\[\(.*\)\].*/\2/' | awk -F':' '{print $NF}'`"
                if [ "$OFFENDINGPKG" != "" ] ; then
                    msgOut WARNING "Trying to remove the offending package $OFFENDINGPKG"
                    pacman ${PACMAN_OPTS} -remove ${OFFENDINGPKG}
                    if [ $? -eq 0 ] ; then
                        msgOut INFO "Offending package removed successfully. Now retrying pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
                        pacman ${PACMAN_OPTS} ${PACMAN_CMD}
                        let instrc=$?
                    else
                        msgOut ERROR "Cannot remove the offending package $OFFENDINGPKG"
                        msgOut ERROR "`pacman -last 2>&1`"
                    fi
                fi
                if [ $instrc -ne 0 ] ; then
                    msgOut ERROR "Physical area installation FAILED"
                    msgOut ERROR "`pacman -last 2>&1`"
                    msgOut INFO "Unlocking the installation area"
                    rm -f ${LOCKFILE}
                    return $instrc
                fi
            fi
        fi

        # Handle the site compilers
        msgOut INFO "Searching for site compilers"
        SYSTEM_ARCH="`uname -m`"
        COMPILER_ARCH="`echo ${ARCH} | sed -e "s/i686/$SYSTEM_ARCH/g" -e "s/x86_64/$SYSTEM_ARCH/g"`"
        COMPILER_VER="`echo ${COMPILER_ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\3/g'`"
        msgOut INFO "Target site compiler is $COMPILER_VER (${COMPILER_ARCH})"
        if [ "$COMPILER_HOME" == "" ] ; then
            # Search for the gcc setup file and get the info from there
            # Revert to a basic search in $VO_ATLAS_SW_DIR in case the gcc setup
            # is not available
            if [ -s "$SITECONF" ] ; then
                msgOut INFO "Getting the site compiler path from $SITECONF"
                COMPILER_PATH="`cat $SITECONF | grep -v ^# | grep gcc${COMPILER_ARCH} | tail -n 1 | cut -d= -f 2`"
                if [ "$COMPILER_PATH" == "" ] ; then
                    COMPILER_PATH="`cat $SITECONF | grep -v ^# | grep ^gcc${COMPILER_VER} | tail -n 1 | cut -d= -f 2`"
                fi
                if [ "$COMPILER_PATH" == "" ] ; then
                    msgOut WARNING "No path matching gcc${ARCH} or gcc${COMPILER_VER} in $SITECONF"
                    msgOut WARNING "Listing the contents of $SITECONF"
                    msgOut WARNING "`cat $SITECONF`"
                else
                    COMPILER_HOME="`/bin/ls -d $COMPILER_PATH 2>/dev/null | tail -n 1`"
                fi
            else
                COMPILER_PATH="$VO_ATLAS_SW_DIR"
                if [ "$VO_ATLAS_SW_DIR" == "" ] ; then
                    if [ "${SWLOG}" != "" -a "${SWPHYS}" != "" ] ; then
                        COMPILER_PATH="`echo ${SWLOG} ${SWPHYS} | awk '{split($1,a,"/"); split ($2,b,"/"); for (i=2;i<length(a);i++) {if (a[i]==b[i]) printf "/%s", a[i];}}'`"
                    else
                        COMPILER_PATH="${TOPDIR}"
                    fi
                    COMPILER_HOME="`/bin/ls -d $COMPILER_PATH/gcc/${COMPILER_VER}* 2>/dev/null | tail -n 1`"
                fi
            fi
            if [ "$COMPILER_PATH" != "" ] ; then
                msgOut INFO "Looking for a site compiler in $COMPILER_PATH"
            fi
        fi
        # Create the AtlasSite (if not yet there) in case a custom compiler is found,
        # the ATLAS_CONDDB reference gatekeep must be set or a Frontier setup is needed
        [ -s ${RELLOC}/AtlasSite/cmt/requirements -a "${PRJTYPE}" == "release" -a "${PRJNAME}" != "gcc" ] && rm -f ${RELLOC}/AtlasSite/cmt/requirements
        if [ ! -s ${RELLOC}/AtlasSite/cmt/requirements -a "$PRJTYPE" != "ext" ] ; then
            if [ "$COMPILER_HOME" != "" ] ; then
                msgOut INFO "Site compiler found in $COMPILER_HOME"
                COMPILER_BIN="`find -L $COMPILER_HOME -xtype d -name bin 2>/dev/null | tail -n 1`"
                COMPILER_LIB="`find -L $COMPILER_HOME -xtype d -name lib 2>/dev/null | tail -n 1`"
                COMPILER_LIB64="`find -L $COMPILER_HOME -xtype d -name lib64 2>/dev/null | tail -n 1`"
                [ "$COMPILER_LIB64" != "" ] && COMPILER_LIB="${COMPILER_LIB}:${COMPILER_LIB64}"
                if [ "$COMPILER_BIN" != "" -a "$COMPILER_LIB" != "" ] ; then
                    msgOut INFO "Site compiler bin found in $COMPILER_BIN"
                    msgOut INFO "Site compiler lib found in $COMPILER_LIB"
                    if [ ! -d ${RELLOC}/AtlasSite/cmt ] ; then
                        mkdir -p ${RELLOC}/AtlasSite/cmt
                        \find $RELLOC/AtlasSite -type d ! -perm -a+rx -exec chmod -R a+rx {} \;
                    fi
cat > ${RELLOC}/AtlasSite/cmt/requirements <<EOAS
path_prepend PATH "$COMPILER_BIN"
path_prepend LD_LIBRARY_PATH "$COMPILER_LIB"
EOAS
                else
                    msgOut WARNING "No bin or lib found in the site compiler. Will use the site compiler"
                    SITECOMPVER="`gcc -v 2>&1 | grep "^gcc version" | awk '{print $3}' | sed 's/\.//g'`"
                    if [ "`echo $SITECOMPVER | grep ^$COMPILER_VER 2>/dev/null`" == "" ] ; then
                        if [ "$REQCOMPILER" == "yes" ] ; then
                            msgOut ERROR "The site compiler is version $SITECOMPVER while you requested version $COMPILER_VER"
                            msgOut INFO "Unlocking the installation area"
                            [ -f ${LOCKFILE} ] && rm -f ${LOCKFILE}
                            cd ${TOPDIR}
                            return $instrc
                        else
                            msgOut WARNING "The site compiler is version $SITECOMPVER while you need version $COMPILER_VER"
                        fi
                    fi
                    msgOut INFO "Listing the directory structure of $COMPILER_HOME"
                    msgOut INFO "`find -L $COMPILER_HOME -xtype d -exec /bin/ls -ld {} \;`"
                fi
            else
                msgOut INFO "No site compiler found, will use the system compiler"
                SITECOMPVER="`gcc -v 2>&1 | grep "^gcc version" | awk '{print $3}' | sed 's/\.//g'`"
                if [ "`echo $SITECOMPVER | grep ^$COMPILER_VER 2>/dev/null`" == "" ] ; then
                    if [ "$REQCOMPILER" == "yes" ] ; then
                        msgOut ERROR "The site compiler is version $SITECOMPVER while you requested version $COMPILER_VER"
                        msgOut INFO "Unlocking the installation area"
                        [ -f ${LOCKFILE} ] && rm -f ${LOCKFILE}
                        cd ${TOPDIR}
                        return $instrc
                    else
                        msgOut WARNING "The site compiler is version $SITECOMPVER while you need version $COMPILER_VER"
                    fi
                fi
            fi
            # Add the CONDDB host
            if [ "$TAGHOST" != "" ] ; then
                if [ ! -d ${RELLOC}/AtlasSite/cmt ] ; then
                    mkdir -p ${RELLOC}/AtlasSite/cmt
                    \find $RELLOC/AtlasSite -type d ! -perm -a+rx -exec chmod -R a+rx {} \;
                fi
                msgOut INFO "Setting ATLAS_CONDDB to $TAGHOST in AtlasSite"
cat >> ${RELLOC}/AtlasSite/cmt/requirements <<EOAS
set ATLAS_CONDDB $TAGHOST
EOAS
            fi
            # Frontier setup
            if [ "$ATLAS_FRONTIER_CONF" != "" -a  "$SETFRONTIER" == "y" ] ; then
                if [ ! -d ${RELLOC}/AtlasSite/cmt ] ; then
                    mkdir -p ${RELLOC}/AtlasSite/cmt
                    \find $RELLOC/AtlasSite -type d ! -perm -a+rx -exec chmod -R a+rx {} \;
                fi
                msgOut INFO "Setting FRONTIER_SERVER to \$ATLAS_FRONTIER_CONF in AtlasSite"
cat >> ${RELLOC}/AtlasSite/cmt/requirements <<EOAS
set FRONTIER_SERVER \$(ATLAS_FRONTIER_CONF)
EOAS
            fi
        else
            [ "$PRJTYPE" != "ext" ] && msgOut WARNING "A site requirements is already present in ${RELLOC}/AtlasSite/cmt/requirements. I will not overwrite it"
        fi

        # Install the selected release
        if [ "$USEPACBALL" != "yes" ] ; then
            PACMAN_CMD="-get \"${RELSNAP}:${ATLASRELEASE}\""
            [ "$UPDATE" == "yes" ] && PACMAN_CMD="$PACMAN_CMD -update ${RELSNAP}:${ATLASRELEASE}"
            msgOut INFO "Executing pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
            echo y | \
              eval pacman ${PACMAN_OPTS} ${PACMAN_CMD}
            let instrc=$instrc+$?
        else
            ATLASRELEASEFNAME="`\ls -d ${RELSNAP} 2>/dev/null`"
            if [ "$ATLASRELEASEFNAME" != "" ] ; then
                msgOut INFO "Executing /bin/bash ${ATLASRELEASEFNAME} ${ATLASRELEASE}"
                /bin/bash ${ATLASRELEASEFNAME} ${ATLASRELEASE}
                let instrc=$instrc+$?
            else
                msgOut ERROR "Cannot find ${RELSNAP}"
                let instrc=$instrc+15
            fi
        fi
        if [ $instrc -ne 0 ] ; then
            msgOut ERROR "Physical area installation FAILED"
            [ "`which pacman 2>/dev/null`" == "" ] && setupPacman
            msgOut ERROR "`pacman -last 2>&1`"
            OFFENDINGPKG="`pacman -last 2>&1 | grep -i 'has not been installed' | sed 's/\(.*\)\[\(.*\)\].*/\2/' | awk -F':' '{print $NF}'`"
            # Try to fix the broken installations
            if [ "$OFFENDINGPKG" != "" ] ; then
                msgOut WARNING "Trying to remove the offending package $OFFENDINGPKG"
                pacman ${PACMAN_OPTS} -remove ${OFFENDINGPKG}
                if [ $? -eq 0 ] ; then
                    msgOut INFO "Offending package removed successfully. Now retrying pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
                    pacman ${PACMAN_OPTS} ${PACMAN_CMD}
                    let instrc=$?
                else
                    msgOut ERROR "Cannot remove the offending package $OFFENDINGPKG"
                    msgOut ERROR "`pacman -last 2>&1`"
                fi
            fi
            if [ $instrc -ne 0 ] ; then
                msgOut ERROR "Physical area installation FAILED"
                msgOut ERROR "`pacman -last 2>&1`"
                msgOut INFO "Unlocking the installation area"
                rm -f ${LOCKFILE} ${SNAPN}
                return $instrc
            fi
        fi
        # Clean snapshots
        [ "$USEPACBALL" != "yes" ] && pacman -clear-snapshots
        # DB release
        if [ "$DBREL" != "" ] ; then
            # Check and fix the "DBRelease" directory if we are not the owners
            DBRELFIX="DBRelease"
            if [ -d DBRelease -a "`ls -ld $DBRELFIX 2>/dev/null | awk '{print $3}'`" != "`whoami`" ] ; then
                msgOut INFO "Fixing the $DBRELFIX directory to be able to write there"
                cp -a ${DBRELFIX} ${DBRELFIX}.new
                if [ $? -eq 0 ] ; then
                    cd ${DBRELFIX}
                    find . -type f -exec md5sum {} \; > ../MD5SUM
                    cd ../${DBRELFIX}.new
                    md5sum -c ../MD5SUM > /dev/null
                    dbrf_rc=$?
                    cd ..
                    rm -f MD5SUM
                    if [ $dbrf_rc -eq 0 ] ; then
                        mv ${DBRELFIX} ${DBRELFIX}.old
                        mv ${DBRELFIX}.new ${DBRELFIX}
                        rm -fr ${DBRELFIX}.old
                        msgOut INFO "$DBRELFIX successfully fixed"
                    else
                        msgOut ERROR "Fixed $DBRELFIX differs from the original. Keeping the original copy."
                        rm -fr ${DBRELFIX}.new
                    fi
                else
                    msgOut ERROR "Cannot fix $DBRELFIX"
                fi
            fi
            # Perform the DBRelease installation
            [ "`which pacman 2>/dev/null`" == "" ] && setupPacman
            PACMAN_CMD="-get ${DBRELCACHE}:${DBRELPKG}"
            msgOut INFO "Executing pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
            echo y | \
            pacman ${PACMAN_OPTS} ${PACMAN_CMD}
            let instrc=$instrc+$?
            if [ $instrc -ne 0 ] ; then
                msgOut ERROR "DB release installation FAILED"
                msgOut ERROR "`pacman -last 2>&1`"
                OFFENDINGPKG="`pacman -last 2>&1 | grep -i 'has not been installed' | sed 's/\(.*\)\[\(.*\)\].*/\2/' | awk -F':' '{print $NF}'`"
                # Try to fix the broken installations, in case we're not using pacballs
                if [ "$OFFENDINGPKG" != "" -a "$USEPACBALL" != "yes" ] ; then
                    msgOut WARNING "Trying to remove the offending package $OFFENDINGPKG"
                    pacman ${PACMAN_OPTS} -remove ${OFFENDINGPKG}
                    if [ $? -eq 0 ] ; then
                        msgOut INFO "Offending package removed successfully. Now retrying pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
                        pacman ${PACMAN_OPTS} ${PACMAN_CMD}
                        let instrc=$?
                    else
                        msgOut ERROR "Cannot remove the offending package $OFFENDINGPKG"
                        msgOut ERROR "`pacman -last 2>&1`"
                    fi
                fi
                if [ $instrc -ne 0 ] ; then
                    msgOut ERROR "Physical area installation FAILED"
                    msgOut ERROR "`pacman -last 2>&1`"
                fi
            fi
        fi
        # Create the logical installation for the selected release
        if [ "${PRJTYPE}" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "${PRJTYPE}" != "eventview" -a "${SWLOC}" != "${RELLOC}" ] ; then
            [ "`which pacman 2>/dev/null`" == "" ] && setupPacman
            cd "${SWLOG}"
            msgOut INFO "Starting the logical installation in ${PWD}"
            SWLOCBD="`date +%s`"
            rm -fr *
            if [ "$PACKOPT" == "all" -a "$USEPACBALL" != "yes" ] ; then
                echo y | \
                pacman ${PACMAN_OPTS} \
                       -get ${RELLOC}:${RELEASE}/${GCC}
                let instrc=$instrc+$?
                echo y | \
                pacman ${PACMAN_OPTS} \
                       -get ${KVSNAP}:${RELEASE}/${KV}
                let instrc=$instrc+$?
            fi
            PACMAN_CMD="-get ${RELLOC}:${ATLASRELEASE}"
            [ "$UPDATE" == "yes" ] && PACMAN_CMD="$PACMAN_CMD -update ${RELLOC}:${ATLASRELEASE}"
            msgOut INFO "Executing pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
            echo y | \
            pacman ${PACMAN_OPTS} ${PACMAN_CMD}
            let instrc=$instrc+$?
            SWLOCED="`date +%s`"
            msgOut INFO "Logical area installation completed in `echo $SWLOCED-$SWLOCBD | bc` s"
            if [ $instrc -ne 0 ] ; then
                msgOut ERROR "Logical area installation FAILED"
                msgOut ERROR "`pacman -last 2>&1`"
                OFFENDINGPKG="`pacman -last 2>&1 | grep -i 'has not been installed' | sed 's/\(.*\)\[\(.*\)\].*/\2/' | awk -F':' '{print $NF}'`"
                # Try to fix the broken installations, in case we're not using pacballs
                if [ "$OFFENDINGPKG" != "" -a "$USEPACBALL" != "yes" ] ; then
                    msgOut WARNING "Trying to remove the offending package $OFFENDINGPKG"
                    pacman ${PACMAN_OPTS} -remove ${OFFENDINGPKG}
                    if [ $? -eq 0 ] ; then
                        msgOut INFO "Offending package removed successfully. Now retrying pacman ${PACMAN_OPTS} ${PACMAN_CMD}"
                        pacman ${PACMAN_OPTS} ${PACMAN_CMD}
                        let instrc=$?
                    else
                        msgOut ERROR "Cannot remove the offending package $OFFENDINGPKG"
                        msgOut ERROR "`pacman -last 2>&1`"
                    fi
                fi
                if [ $instrc -ne 0 ] ; then
                    msgOut ERROR "Logical area installation FAILED"
                    msgOut ERROR "`pacman -last 2>&1`"
                    msgOut INFO "Unlocking the installation area"
                    rm -f ${LOCKFILE} ${SNAPN}
                    return $instrc
                fi
            fi
            pacman -clear-snapshots
        fi
        rm -f $SNAPN
        [ "$TEMPCACHE" == "yes" ] && rm -fr ${SNAPDIR}/${SNAPNAME}*
    fi
    # Post-install steps
    shift $#

    # Perform other ATLAS sw specific post-install steps. Exclude external packages, EventView caches and poolcond generations.
    cd "${SWLOG}"
    if [ "$PRJTYPE" == "ext" -a "$PRJNAME" == "gcc" ] ; then
        source setup.sh
        setCompiler $GCC_DIR
    fi
    if [ "$PRJTYPE" != "ext" -a "${PRJTYPE}" != "eventview" -a "${PRJTYPE}" != "poolcond" ] ; then
        if [ "$PRJNAME" == "release" -o "$PRJNAME" == "AtlasRelease" ] ; then
            source setup.sh
            msgOut INFO "Setting up runtime enviroment from ${SITEROOT}/dist/${RELEASE}/Control/AthenaRunTime"
            cd ${SITEROOT}/dist/${RELEASE}/Control/AthenaRunTime/*/cmt
            source setup.sh
        else
            if [ -s ${RELLOC}/cmtsite/setup.sh ] ; then
                # Compatibility link
                if [ ! -d cmtsite -a ! -L cmtsite ] ; then
                    msgOut INFO "Creating $PWD/cmtsite link"
                    ln -sf . cmtsite
                fi

                # Other actions
                if [ "${PRJTYPE}" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" ] ; then
                    # For slc5 releases or later, set some additional tags
                    if [ $REL_PLAT -ge 5 ] ; then
                        RUNTIME_TAGS=",gcc${REL_COMP},slc${REL_PLAT}"
                        [ "$REL_ARCH" == "i686" ] && RUNTIME_TAGS="${RUNTIME_TAGS},32" || RUNTIME_TAGS="${RUNTIME_TAGS},64"
                    fi
                    source ${RELLOC}/cmtsite/setup.sh -tag=${RELEASE},${PRJNAME},${PRJOPT}${RUNTIME_TAGS}
                    if [ "$SWLOC" != "$RELLOC" ] ; then
                        # Create the setup-release.sh hub
                        REL_ARCH="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\1/g'`"
                        REL_PLAT="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\2/g'`"
                        REL_COMP="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\3/g'`"
cat > setup-release.sh <<EOSR
CMD_OPT="\$*"
if [ "\$CMD_OPT" = "" ] ; then
    CMD_OPT="-tag=${RELEASE},${PRJNAME},${PRJOPT}${RUNTIME_TAGS},runtime"
    echo "Using default options \$CMD_OPT"
fi
source $SITEROOT/cmtsite/setup.sh \$CMD_OPT
EOSR
cat > setup-release.csh <<EOSR
set CMD_OPT="\$*"
if ( "x\$CMD_OPT" == "x" ) then
    set CMD_OPT="-tag=${RELEASE},${PRJNAME},${PRJOPT}${RUNTIME_TAGS},runtime"
    echo "Using default options \$CMD_OPT"
endif
source $SITEROOT/cmtsite/setup.csh \$CMD_OPT
EOSR
                        grep -v "source $PWD/setup-release.sh"  setup.sh | \
                                grep -v "source $SITEROOT/cmtsite/setup.sh"  > setup.sh.tmp
                        grep -v "source $PWD/setup-release.csh" setup.csh | \
                                grep -v "source $SITEROOT/cmtsite/setup.csh" > setup.csh.tmp
                        echo "source $PWD/setup-release.sh \$*"  >> setup.sh.tmp
                        echo "source $PWD/setup-release.csh \$*"  >> setup.csh.tmp
                        \mv -f setup.sh.tmp setup.sh
                        \mv -f setup.csh.tmp setup.csh
                    fi
                    # Compatibility patches
                    DETECTED_DIST="`lsb_release -d | cut -d: -f 2 | sed 's/[^[:alpha:]*]//'`"
                    COMPATDIST="`echo $DETECTED_DIST | egrep 'Scientific Linux .* 5\..*|CentOS .* 5\..*'`"
                    RELDETARCH="`echo ${ARCH} | sed 's/.*_\(slc[0-9]\)_.*/\1/'`"
                    if [ "$RELDETARCH" == "slc3" -o "$RELDETARCH" == "slc4" ] ; then
                        msgOut INFO "We are installing $RELDETARCH software. Checking if we need to install the SL5 compatibility patches."
                        if [ "$COMPATDIST" != "" ] ; then
                            msgOut INFO "The detected architecture might need patches: `echo $COMPATDIST | cut -d: -f 2-`"
                        elif [ "$DETECTED_DIST" != "" ] ; then
                            msgOut INFO "The detected architecture does not need patches: $DETECTED_DIST"
                        else
                            msgOut INFO "Unable to detect the system architecture"
                        fi
                    else
                        msgOut INFO "You are trying to install a $RELDETARCH software, no patches needed."
                        COMPATDIST=""
                    fi
                    if [ "$COMPATDIST" != "" -a "$COMPATPATCH" != "" ] ; then
                        LASTAL="`\ls -d $SITEROOT/AtlasLogin/* | sed 's#.*AtlasLogin-\([0-9]*\)-\([0-9]*\)-\([0-9]*\)#\1\2\3#' | sort | tail -n 1`"
                        LASTAS="`\ls -d $SITEROOT/AtlasSettings/* | sed 's#.*AtlasSettings-\([0-9]*\)-\([0-9]*\)-\([0-9]*\)#\1\2\3#' | sort | tail -n 1`"
                        LASTSLC4C="`\ls -d $SITEROOT/external/slc4compat 2>/dev/null`"
                        LASTACPP="`cat $SITEROOT/AtlasCore/${RELEASE}/External/PlatformPolicy/cmt/version.cmt 2>/dev/null | sed 's#.*PlatformPolicy-\([0-9]*\)-\([0-9]*\)-\([0-9]*\)#\1\2\3#'`"
                        LASTACSLC4C="`cat $SITEROOT/AtlasCore/${RELEASE}/External/SLC4_Compat/cmt/version.cmt 2>/dev/null | sed 's#.*SLC4_Compat-\([0-9]*\)-\([0-9]*\)-\([0-9]*\)#\1\2\3#'`"
                        [ "$LASTACPP" == "" ] && LASTACPP=0
                        [ "$LASTACSLC4C" == "" ] && LASTACSLC4C=0
                        if [ $LASTAL -lt 318 -o $LASTAS -lt 30220 -o "$LASTSLC4C" == "" -o $LASTACPP -lt 3 -o $LASTACSLC4C -lt 3 ] ; then
                            [ $LASTAL -lt 318 ] && msgOut INFO "Found AtlasLogin-`echo $LASTAL | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`, which is older than 00-03-18. Applying the SL4 to SL5 patches"
                            [ $LASTAS -lt 30220 ] && msgOut INFO "Found AtlasSettings-`echo $LASTAS | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`, which is older than 03-02-20. Applying the SL4 to SL5 patches"
                            [ "$LASTSLC4C" == "" ] && msgOut INFO "No slc4compat package found. Applying the SL4 to SL5 patches"
                            [ $LASTACPP -lt 3 ] && msgOut INFO "Found PlatformPolicy `echo $LASTACPP | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`. Applying the SL4 to SL5 patches"
                            [ $LASTACSLC4C -lt 3 ] && msgOut INFO "Found SLC4_Compat `echo $LASTACSLC4C | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`. Applying the SL4 to SL5 patches"
                            cd $SITEROOT
                            prc=0
                            for f in ${COMPATPATCH[@]}; do
                                rm -f ${f}
                                wget ${COMPATURL}/${f}
                                let prc=$prc+$?
                            done
                            if [ $prc -eq 0 ] ; then
                                chmod +x ${COMPATPATCH[0]}
                                ./${COMPATPATCH[0]} $RELEASE
                                [ $? -eq 0 ] && msgOut INFO "Patch successful" || msgOut ERROR "Patch Failed"
                            else
                                msgOut ERROR "Cannot get the patch files from $COMPATURL"
                            fi
                            for f in ${COMPATPATCH[@]}; do rm -f $f; done
                            cd -
                        else
                            msgOut INFO "Found AtlasLogin-`echo $LASTAL | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`, AtlasSettings-`echo $LASTAS | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`, slc4compat, PlatformPolicy `echo $LASTACPP | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`, SLC4_Compat `echo $LASTACSLC4C | sed 's#\(..\)\(..\)\(..\)#\1-\2\-\3#'`, no need to apply the SL4 to SL5 patches"
                        fi
                    fi
                else
                    # For slc5 releases or later, set some additional tags
                    if [ $REL_PLAT -ge 5 ] ; then
                        RUNTIME_TAGS=",gcc${REL_COMP},slc${REL_PLAT}"
                        [ "$REL_ARCH" == "i686" ] && RUNTIME_TAGS="${RUNTIME_TAGS},32" || RUNTIME_TAGS="${RUNTIME_TAGS},64"
                    fi
                    # Check if the patch number is in AtlasLogin and add it if needed
                    RELBASE="`echo $RELEASE | cut -d. -f 1-3`"
                    msgOut INFO "Checking the AtlasLogin requirements (source ${RELLOC}/cmtsite/setup.sh -tag=${RELBASE},${REQPRJNAME},${PRJOPT}${RUNTIME_TAGS})"
                    source ${RELLOC}/cmtsite/setup.sh -tag=${RELBASE},${REQPRJNAME},${PRJOPT}${RUNTIME_TAGS}

                    for ATLASLOGINREQ in `\find $SITEROOT/AtlasLogin -name "requirements"`; do
                        msgOut INFO "Checking $ATLASLOGINREQ"
                        grep -q  "$RELEASE[^0-9]" $ATLASLOGINREQ
                        if [ $? -ne 0 ] ; then
                            msgOut INFO "Adding $RELEASE to the AtlasLogin requirements ($ATLASLOGINREQ)"
                            LATESTPATCH="`grep ".*$RELBASE.*\\"$RELBASE.*\\"" $ATLASLOGINREQ | awk '{print $1}' | grep ^$RELBASE | tail -n 1`"
                            mv -f ${ATLASLOGINREQ} ${ATLASLOGINREQ}.orig
                            AWKCMD="{bs=\"\\\ \"; gsub(/ *\$/,\"\",bs); bss=sprintf(\" %s\",bs); if (/$LATESTPATCH.*\"$LATESTPATCH\"/ && !/\\\/) {printf \"%s%s\n\", \$0, bss;} else {print \$0;} if (/$LATESTPATCH.*\"$LATESTPATCH\"/) {gsub(/$LATESTPATCH/,\"$RELEASE\",\$0);print \$0;}}"
                            cat ${ATLASLOGINREQ}.orig | awk "$AWKCMD" > ${ATLASLOGINREQ}
                        else
                            msgOut INFO "$RELEASE already present in the AtlasLogin requirements ($ATLASLOGINREQ)"
                        fi
                        \find $ATLASLOGINREQ -maxdepth 1 -type d ! -perm -a+r -exec chmod a+rX {} \;
                    done
                fi
                if [ -d $SITEROOT/${PRJNAME}/${RELEASE}/${PRJNAME}RunTime/cmt ] ; then
                    msgOut INFO "Setting up runtime enviroment from $SITEROOT/${PRJNAME}/${RELEASE}/${PRJNAME}RunTime"
                    cd $SITEROOT/${PRJNAME}/${RELEASE}/${PRJNAME}RunTime/cmt
                    if [ ! -s setup.sh ] ; then
                        msgOut WARNING "No setup file found. Trying to configure..."
                        cd $SITEROOT/${PRJNAME}/${RELEASE}/${PRJNAME}Release/cmt
                        cmt -quiet br - 'cmt -quiet -no_cleanup config'
                        cd $SITEROOT/${PRJNAME}/${RELEASE}/${PRJNAME}RunTime/cmt
                        if [ ! -s setup.sh ] ; then
                            msgOut ERROR "Cannot configure the package"
                        else
                            source setup.sh
                        fi
                    else
                        source setup.sh
                    fi
                else
                    msgOut INFO "Cannot setup runtime enviroment from $SITEROOT/${PRJNAME}/${RELEASE}/${PRJNAME}RunTime"
                fi
            else
                msgOut ERROR "Cannot find setup file ${RELLOC}/cmtsite/setup.sh"
                let instrc=$instrc+1
            fi
        fi
    fi

    # End-of-run tasks
    if [ $instrc -eq 0 ] ; then
        if [ "$PRJTYPE" != "ext" -a "$PRJTYPE" != "eventview" -a "${PRJTYPE}" != "poolcond" ] ; then
            [ "`which SealPluginRefresh 2>/dev/null`" != "" ] && SealPluginRefresh
            cmt build library_links
        fi
        # Set the required environment variables in the setup scripts
        cd "${SWLOG}"
        for setvar in `echo $SETENV | sed 's/,/ /g'`; do
            msgOut INFO "Setting $setvar in $PWD/setup.sh"
            VAREXPORTSH="export $setvar"
            VAREXPORTCSH="setenv `echo $setvar | sed 's/=/ /g'`"
            grep -v "$VAREXPORTSH"  setup.sh > setup.sh.tmp
            grep -v "$VAREXPORTCSH" setup.csh > setup.csh.tmp
            echo "$VAREXPORTSH"  >> setup.sh.tmp
            echo "$VAREXPORTCSH" >> setup.csh.tmp
            \mv -f setup.sh.tmp setup.sh
            \mv -f setup.csh.tmp setup.csh
        done
        cd ${SWPHYS}
    fi

    # Set the correct file permissions for the sw areas
    case `whoami` in
        usatlas*) msgOut INFO "This is an OSG site with static accounts. No further action required"
            ;;
        AAA*[0-9])
            msgOut INFO "This site is configured for SGM pool accounts"
            msgOut INFO "Preparing to set write permissions to group \"`id -gn`\" on ${SWPHYS}"
            msgOut INFO "Preparing to set write permissions to group \"`id -gn`\" on ${SWLOG}"
            CHMOD_OPTS="g+rw,o+r"
            if [ "$DUMPTAGS" != "" ] ; then
                # Check if we are running in AFS
                if [ "`echo $DUMPTAGS | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] ; then
                    # Check if we are already in the rw path 
                    if [ "`echo $DUMPTAGS | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
                        DUMPTAGS="`echo $DUMPTAGS | sed 's#^/afs/\(.*\)#/afs/.\1#g'`"
                    fi
                fi
                WHOAMI="`whoami`"
                DUMPTAGSFILE="`find ${DUMPTAGS} -user ${WHOAMI} ! -perm -g+rw`"
                if [ "$DUMPTAGSFILE" != "" ] ; then
                    msgOut INFO "Setting group write permissions to ${DUMPTAGS}"
                    chmod g+rw $DUMPTAGS 2>/dev/null
                    [ $? -ne 0 ] && msgOut ERROR "Cannot change group write permissions to ${DUMPTAGS}"
                fi
            fi
            ;;
        *) msgOut INFO "This site is configured for SGM static accounts. No further action required"
            ;;
    esac
    [ "$CHMOD_OPTS" != "" ] && CHMOD_OPTS="o-w,a+X,$CHMOD_OPTS" || CHMOD_OPTS="o-w,a+X"
    msgOut INFO "Setting permissions in ${SWPHYS} to $CHMOD_OPTS"
    find ${SWPHYS} -user `whoami` ! -type l ! -perm -$CHMOD_OPTS -exec chmod $CHMOD_OPTS "{}" \; -exec ls -ld "{}" \;
    [ $? -ne 0 ] && msgOut ERROR "Cannot change permissions in ${SWPHYS}"
    if [ "$SWLOC" != "${RELLOC}" ] ; then
        msgOut INFO "Setting permissions in ${SWLOG} to $CHMOD_OPTS"
        find ${SWLOG} -user `whoami` ! -type l ! -perm -$CHMOD_OPTS -exec chmod $CHMOD_OPTS "{}" \; -exec ls -ld "{}" \;
        [ $? -ne 0 ] && msgOut ERROR "Cannot change permissions in ${SWLOG}"
    fi

    # End of post-processing
    if [ $instrc -eq 0 ] ; then
        # If we are using AFS, relocate the release to the correct path
        [ "$AFSRELLOC" != "" ] && relocateRelease $SWPHYS $AFSRELLOC $SWPHYS
        [ "$AFSRELLOC" != "" ] && relocateRelease $SWPHYS $AFSRELLOC $SWLOG
        [ "$AFSLOC"    != "" ] && relocateRelease $SWLOG $AFSLOC $SWLOG

        # Release the physical installation volume, if possible
        if [ "$AFSRELLOC" != "" ] ; then
            AFSRELEASE="`which afs_release 2>/dev/null`"
            if [ "$AFSRELEASE" != "" ] ; then
                AFSMP="`isAFSmountpoint ${AFSRELLOC}`"
                if [ "$AFSMP" != "" ] ; then
                    [ -f ${LOCKFILE} ] && rm -f ${LOCKFILE}
                    msgOut INFO "Releasing AFS volume: $AFSRELEASE ${AFSRELLOC}"
                    $AFSRELEASE "${AFSRELLOC}"
                    afsrelrc=$?
                    [ $afsrelrc -ne 0 ] && msgOut ERROR "Cannot release AFS volume. Error code: $afsrelrc" || msgOut INFO "AFS volume released successfully"
                    let instrc=$instrc+$afsrelrc
                else
                    msgOut WARNING "${AFSRELLOC} is not and AFS volume, will not try to release it"
                fi
            else
                msgOut WARNING "No afs_release command found"
                msgOut WARNING "PATH=$PATH"
            fi
        fi

        msgOut INFO "Installation OK"
    fi

    msgOut INFO "Unlocking the installation area"
    [ -f ${LOCKFILE} ] && rm -f ${LOCKFILE}
    cd ${TOPDIR}
    return $instrc
}


validate() {
    let validrc=0
    # Reset the environment
    ENVLAST="/tmp/sw-mgr-envlast.tmp.$$"
    /usr/bin/env | grep '=' | cut -d'=' -f 1 | egrep -v '^_$|^\s|^	|^$' | while read var; do echo "$var='`/usr/bin/printenv $var`'"; done > $ENVLAST
    if [ -s $ENVSTART ] ; then
        echo "ENVLAST=\"$ENVLAST\"" >> $ENVSTART
        msgOut INFO "Resetting the environment from $ENVSTART"
        source $ENVSTART
    fi

    # Start the validation
    SWPHYS=${RELLOC}
    SWLOG=${SWLOC}
    if [ "${SWPATH}" != "" ] ; then
        SWPHYS="$SWPATH"
        SWLOG="$SWPATH"
    fi
    cd ${TOPDIR}
    TESTDIR=${TOPDIR}/kvtest_$$
    mkdir "$TESTDIR"
    cd "$TESTDIR"
    if [ "$VALEXE" != "" ] ; then
        # Run an external validation script
        msgOut INFO "Setting up the release from ${SWLOG}"
        source ${SWLOG}/setup.sh
        msgOut INFO "Executing the external validation exe $TOPDIR/$VALEXE"
        chmod +x $TOPDIR/`echo $VALEXE | awk '{print $1}'`
        $TOPDIR/$VALEXE
        validrc=$?
    else
        if [ "${PRJTYPE}" == "ext" ] ; then
            # Let's run a generic setup and print the environment + some other commands
            msgOut INFO "Setting up the release from ${SWLOG}"
            source ${SWLOG}/setup.sh
            validrc=$?
            msgOut INFO "Printing the environment"
            msgOut INFO "`printenv`"
            [ "`which lcg-cp 2>/dev/null`"  != "" ] && msgOut INFO "lcg-cp:  `which lcg-cp`"
            [ "`which lcg-cr 2>/dev/null`"  != "" ] && msgOut INFO "lcg-cr:  `which lcg-cr`"
            [ "`which lcg-del 2>/dev/null`" != "" ] && msgOut INFO "lcg-del: `which lcg-del`"
        elif [ "${PRJTYPE}" == "poolcond" ] ; then
            if [ -s "$SWLOG/PoolFileCatalog.xml" ] ; then
                msgOut INFO "$SWLOG/PoolFileCatalog.xml found"
                VALEXE="`which FClistPFN 2>/dev/null`"
                if [ "$VALEXE" == "" -a "$RELSETUP" != "" ] ; then
                    MAXREL=$((${#RELSETUPLIST[@]}-1))
                    if [ ${MAXREL} -gt 0 ] ; then
                        for r in `seq $MAXREL -1 0`; do
                            msgOut WARNING "No FClistPFN found. Trying to setup the latest ATLAS release with ${RELSETUPLIST[$r]}"
                            eval ${RELSETUPLIST[$r]}
                            VALEXE="`which FClistPFN 2>/dev/null`"
                            if [ "$VALEXE" != "" ] ; then
                                msgOut INFO "FClistPFN found in release $AtlasVersion"
                                break
                            fi
                        done
                    fi
                fi
                if [ "$VALEXE" != "" ] ; then
                    PFCS="`FClistPFN -u file:$SWLOG/PoolFileCatalog.xml | wc -l`"
                    if [ $PFCS -gt 0 ] ; then
                        msgOut INFO "$PFCS entries found in $SWLOG/PoolFileCatalog.xml"
                        validrc=0
                    else
                        msgOut ERROR "No entries found in $SWLOG/PoolFileCatalog.xml"
                        validrc=30
                    fi
                else
                    msgOut ERROR "No FClistPFN found"
                    validrc=20
                fi
            else
                msgOut ERROR "Cannot find $SWLOG/PoolFileCatalog.xml or the file is empty"
                validrc=10
            fi
        else
            # Let's run KitValidation
            if [ "${PRJNAME}" == "AtlasRelease" -o "${PRJNAME}" == "release" ] ; then
                KVBUILD_OPTS=""
            else
                RELSERIAL="`echo $RELEASE | cut -d "." -f 1-3 | awk -F. '{printf "%d",$1; for(i=2;i<=NF;i++) printf "%03d", $i;}'`"
                if [ "${PRJNAME}" == "AtlasOffline" -a $RELSERIAL -lt 13000030 -a $RELSERIAL -gt 0 ] ; then
                    KVBUILD_OPTS="--project AtlasProduction"
                else
                    KVBUILD_OPTS="--project ${PRJNAME}"
                fi
            fi
            [ "$T_POST" == "yes" ] && msgOut INFO "KV posting enabled"
            [ "$KVPOSTTAG" != "" ] && msgOut INFO "Using GKV tag $KVPOSTTAG"
            [ "${PRJTYPE}" == "bugfix" -o "${PRJTYPE}" == "dev" -o "${PRJTYPE}" == "p1nightly" ] && KVRELTYPE=":${PRJTYPE}" || KVRELTYPE=""
            [ "${PRJTYPE}" == "p1patch" ] && KVRELTYPE=":p1" || KVRELTYPE=""
            [ "${PRJTYPE}" == "t0patch" ] && KVRELTYPE=":t0" || KVRELTYPE=""
            [ "${PRJTYPE}" == "eventview" ] && KVRELTYPE=":ev" || KVRELTYPE=""
            KVRELBASE="`echo $RELEASE | cut -d "." -f 1-3`"
            if [ "$DEBUG" == "yes" ] ; then
                msgOut DEBUG "PATH=${PATH}"
                msgOut DEBUG "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
                msgOut DEBUG "PYTHONPATH=${PYTHONPATH}"
            fi
            [ "`which pacman 2>/dev/null`" == "" ] && setupPacman
            msgOut INFO "Starting validation for release $RELEASE"
            msgOut INFO "Executing pacman $PACMAN_OPTS -get ${LCGCACHE}:${KVRELBASE}/KitValidation"
            pacman $PACMAN_OPTS -get ${LCGCACHE}:${KVRELBASE}/KitValidation
            msgOut INFO "Executing pacman $PACMAN_OPTS -get ${LCGCACHE}:${KVRELBASE}/KitValidationPatches"
            pacman $PACMAN_OPTS -get ${LCGCACHE}:${KVRELBASE}/KitValidationPatches
            [ $? -eq 0 ] && source setup.sh
            if [ "$KVBUILD_OPTS" != "" ] ; then
                REL_ARCH="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\1/g'`"
                REL_PLAT="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\2/g'`"
                REL_COMP="`echo ${ARCH} | sed 's/^[_ ]\(.*\)_slc\([0-9]\)_gcc\([0-9]*\)/\3/g'`"
                # For slc5 releases or later, set some additional tags
                if [ $REL_PLAT -ge 5 ] ; then
                    RUNTIME_TAGS=",gcc${REL_COMP},slc${REL_PLAT}"
                    [ "$REL_ARCH" == "i686" ] && RUNTIME_TAGS="${RUNTIME_TAGS},32" || RUNTIME_TAGS="${RUNTIME_TAGS},64"
                fi
                if [ "${PRJTYPE}" == "p1nightly" ] ; then
                    msgOut INFO "Setting up the point1 nightly release from $PWD"
                    msgOut INFO "source ${SWLOC}/cmtsite/setup.sh -tag=${PRJNAME},${RELEASE},${PRJOPT}${RUNTIME_TAGS},runtime"
                    source ${SWLOC}/cmtsite/setup.sh -tag=${PRJNAME},${RELEASE},${PRJOPT}${RUNTIME_TAGS},runtime
                elif [ "${PRJTYPE}" == "patch" -o "${PRJTYPE}" == "p1patch" -o "$PRJTYPE" == "t0patch" -o "${PRJTYPE}" == "eventview" ] ; then
                    msgOut INFO "Setting up the release from $PWD"
                    msgOut INFO "source ${SWLOC}/cmtsite/setup.sh -tag=${REQPRJNAME},${KVRELBASE},${PRJOPT}${RUNTIME_TAGS},runtime"
                    source ${SWLOC}/cmtsite/setup.sh -tag=${REQPRJNAME},${KVRELBASE},${PRJOPT}${RUNTIME_TAGS},runtime
                else
                    msgOut INFO "Setting up the release from $PWD"
                    msgOut INFO "source ${SWLOC}/cmtsite/setup.sh -tag=${PRJNAME},${RELEASE},${PRJOPT}${RUNTIME_TAGS}"
                    source ${SWLOC}/cmtsite/setup.sh -tag=${PRJNAME},${RELEASE},${PRJOPT}${RUNTIME_TAGS}
                fi
                if [ "${PRJTYPE}" == "patch" -o "${PRJTYPE}" == "p1patch" -o "$PRJTYPE" == "t0patch" ] ; then
                    msgOut INFO "Using patch release $RELEASE from $PWD"
                    unset CMTPATH
                    cd ${SITEROOT}/${PRJNAME}/${RELEASE}/${PRJNAME}RunTime/cmt
                    source setup.sh
                    validrc=$?
                    if [ $validrc -eq 0 ] ; then
                        msgOut INFO "Patch release ${RELEASE} setup complete"
                        msgOut INFO "CMTPATH=${CMTPATH}"
                        export AtlasPatchVersion=${RELEASE}
                        export AtlasVersion=${RELEASE}
                    else
                        msgOut ERROR "Cannot setup patch release ${RELEASE}"
                    fi
                    cd -
                elif [ "${PRJTYPE}" == "eventview" ] ; then
                    msgOut INFO "Using EventView version $RELEASE from $PWD"
                    setupDev "-tag=${REQPRJNAME},${KVRELBASE}${RUNTIME_TAGS},groupArea,runtime"
                    #validrc=$?
                    validrc=1
                else
                    msgOut INFO "Using plain release $RELEASE from $PWD"
                    msgOut INFO "Executing pacman $PACMAN_OPTS -get ${LCGCACHE}:${KVRELBASE}/KitValidationPyJTPatches"
                    pacman $PACMAN_OPTS -get ${LCGCACHE}:${KVRELBASE}/KitValidationPyJTPatches
                    msgOut INFO "Setting up the main release runtime: source ${SWLOC}/cmtsite/setup.sh -tag=${PRJNAME},${RELEASE},${PRJOPT}${RUNTIME_TAGS},runtime"
                    source ${SWLOC}/cmtsite/setup.sh -tag=${PRJNAME},${RELEASE},${PRJOPT}${RUNTIME_TAGS},runtime
                    if [ -d $PWD/AtlasProduction/*/AtlasProductionRunTime/cmt ] ; then
                        EPREL="`find $PWD/AtlasProduction -maxdepth 1 -exec basename {} \; | tail -n 1`"
                        msgOut INFO "Setting up the embedded patch ${EPREL} runtime environment"
                        unset CMTPATH
                        cd $PWD/AtlasProduction/$EPREL/AtlasProductionRunTime/cmt
                        if [ -s setup.sh ] ; then
                            source setup.sh
                        else
                            msgOut WARNING "No setup found for the embedded patch! Skipping"
                        fi
                        cd -
                    fi
                fi
            fi
            if [ $validrc -eq 0 ] ; then
                # Override the DB release if needed
                if [ "$DBREL" != "" ] ; then
                    export DBRELEASE_OVERRIDE=$DBREL
                    #export DBRELEASE_INSTALLED=$DBREL
                    msgOut INFO "Using DBRelease $DBRELEASE_OVERRIDE"
                fi

                # Start the test threads
                for kvthr in `seq 1 $TESTTHR`; do
                    TTDIR="$TESTDIR/KV.thr.$kvthr"
                    msgOut INFO "Creating dir $TTDIR"
                    mkdir -p $TTDIR; cd $TTDIR
                    \find $TESTDIR/ -maxdepth 1 -type d -name "KitValidation" -exec cp -a {} . \;
                    \find $TESTDIR/ -maxdepth 1 -type d -name "JobTransforms" -exec cp -a {} . \;
                    \find $TESTDIR/ -maxdepth 1 -type d -name "Atlas*" -exec ln -s {} . \;
                    KVHOME=`\find $PWD/KitValidation/ -type d -name share`
                    # Global test disable
                    [ "$KVDISABLE" != "" ] && KVDISABLE_OPTS=" --disable $KVDISABLE"
                    # Per-release test disable
                    KVDISREL="KVDISABLE_`echo $RELEASE | sed 's/\./_/g'`"
                    KVDISRELVAL="`eval echo \\$$KVDISREL`"
                    [ "$KVDISRELVAL" != "" ] && KVDISABLE_OPTS=" --disable $KVDISRELVAL"
                    # Other disables
                    if [ "$KVD" != "" ] ; then
                        if [ "$KVDISABLE_OPTS" != "" ] ; then
                            KVDISABLE_OPTS="$KVDISABLE_OPTS,$KVD"
                        else
                            KVDISABLE_OPTS=" --disable $KVD"
                        fi
                    fi
                    KVVER="`${KVHOME}/KitValidation -V | grep version | awk '{print $4'} | awk -F. '{printf "%d",$1; for(i=2;i<=NF;i++) printf "%03d", $i;}'`"
                    if [ $KVVER -ge 1009015 -a "$REQPRJNAME" != "" ] ; then
                        # This switch is supported only since release 1.9.15 of KV
                        KVADDSEARCH=" --search $REQPRJNAME"
                    else
                        [ "$REQPRJNAME" != "" ] && msgOut WARNING "Ignoring KV release base search for KV-$KVVER"
                    fi
                    if [ $KVVER -ge 1009016 -a "$KVPOSTTAG" != "" ] ; then
                        # This switch is supported only since release 1.9.16 of KV
                        KVPOSTTAG_OPTS=" --kvpost-tag ${KVPOSTTAG}"
                    else
                        [ "$KVPOSTTAG" != "" ] && msgOut WARNING "Ignoring KV user tags for KV-$KVVER"
                    fi
                    if [ $KVVER -ge 1009017 -a "$KVCONFURL" != "" ] ; then
                        # This switch is supported only since release 1.9.17 of KV
                        KVCONFURL_OPTS=" --test-config \"${KVCONFURL}\""
                    else
                        [ "$KVCONFURL" != "" ] && msgOut WARNING "Ignoring KV custom configuration XML for KV-$KVVER"
                    fi
                    if [ $KVVER -ge 1009016 ] ; then
                        # This switch is supported only since release 1.9.16 of KV
                        # Per-release test enable
                        KVENAREL="KVENABLE_`echo $RELEASE | sed 's/\./_/g'`"
                        KVENARELVAL="`eval echo \\$$KVENAREL`"
                        [ "$KVENARELVAL" != "" ] && KVENABLE_OPTS=" --enable $KVENARELVAL"
                        # Other test enable
                        [ "$KVE" != "" ] && KVENABLE_OPTS=" --enable ${KVE}"
                    else
                        [ "$KVE" != "" ] && msgOut WARNING "Test enabling not supported in KV-$KVVER"
                    fi
                    msgOut INFO "Starting KV (thread #${kvthr}/${TESTTHR})..."
                    msgOut INFO "${KVHOME}/KitValidation -r ${RELEASE}${KVRELTYPE} -p ${SWLOC} -gkvn --bw -t ${PWD} ${KVBUILD_OPTS}${KVDISABLE_OPTS}${KVADDSEARCH}${KVPOSTTAG_OPTS}${KVCONFURL_OPTS}${KVENABLE_OPTS}"
                    if [ "$DEBUG" == "yes" ] ; then
                        msgOut DEBUG "PATH=${PATH}"
                        msgOut DEBUG "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
                        msgOut DEBUG "PYTHONPATH=${PYTHONPATH}"
                    fi
                    (${KVHOME}/KitValidation -r ${RELEASE}${KVRELTYPE} -p ${SWLOC} -gkvn --bw \
                     -t ${PWD} ${KVBUILD_OPTS}${KVDISABLE_OPTS}${KVADDSEARCH}${KVPOSTTAG_OPTS}${KVCONFURL_OPTS}${KVENABLE_OPTS}; \
                     echo $? > ${TTDIR}.rc) &
                done
                # Wait for the threads to finish
                msgOut INFO "Waiting for ${TESTTHR} thread(s) to finish"
                wait
                # Calculate the global return code
                for kvthr in `seq 1 $TESTTHR`; do
                    TTDIR="$TESTDIR/KV.thr.$kvthr"
                    let validrc=$validrc+`cat ${TTDIR}.rc`
                done
            fi
        fi
    fi

    # Print out the test result
    if [ $validrc -ne 0 ] ; then
        msgOut ERROR "Test FAILED [rc=$validrc]"
    else
        msgOut INFO "Test OK [rc=$validrc]"
    fi

    # Clean up
    cd ${TOPDIR}
    if [ "$KVKEEP" != "y" ] ; then
        msgOut INFO "Removing test data"
        rm -fr "$TESTDIR"
    else
        msgOut INFO "Keeping test data in $TESTDIR"
    fi

    # Reset the environment
    if [ -s $ENVLAST ] ; then
        msgOut INFO "Reverting to the environment from $ENVLAST"
        source $ENVLAST
        rm -f $ENVLAST
    fi

    # End of the function
    return $validrc
}


findRelease() {
    RELDEFAULTLOC="${1}"
    DIRFOUND="`find ${RELDEFAULTLOC} -name "AtlasRelease" -o -name "${PRJNAME}Release" -type d 2>/dev/null | grep ".*[(dist),(${PRJNAME})]/${RELEASE}/" | tail -n 1`"
    if [ "$DIRFOUND" == "" ] ; then
        STARTDIR="`echo ${RELDEFAULTLOC} | xargs dirname | xargs dirname`"
        #[ "$VO_ATLAS_SW_DIR" != "" ] && STARTDIR=$VO_ATLAS_SW_DIR
        echo "The default directory $RELDEFAULTLOC does not contain release $RELEASE. Searching release $RELEASE performing a FULL DISK SCAN starting from $STARTDIR" > /dev/stderr
        DIRFOUND="`find $STARTDIR -name "AtlasRelease" -o -name "${PRJNAME}Release" -type d 2>/dev/null | grep ".*[(dist),(${PRJNAME})]/${RELEASE}/" | tail -n 1`"
    fi
    if [ "$DIRFOUND" != "" ] ; then
        echo "Release found in $DIRFOUND" > /dev/stderr
        DIRFOUND="`dirname $DIRFOUND | xargs dirname | xargs dirname`"
        echo "Using installation dir $DIRFOUND" > /dev/stderr
    fi
    echo $DIRFOUND
}


remove() {
    let removerc=0
    msgOut INFO "Removal of ${PRJNAME} ${RELEASE} started at `date`"

    if [ "$PRJTYPE" == "poolcond" ] ; then
        cleanup
        removerc=$?
    else
        # Setup the release and check the physical install path
        SETUPFILE="`/bin/ls -d ${SWLOC}/cmtsite/setup.sh 2> /dev/null`"
        [ "$SETUPFILE" == "" ] && SETUPFILE="${SWLOC}/setup.sh"
        if [ -s ${SETUPFILE} -a "${SWLOC}" != "${RELLOC}" ] ; then
            msgOut INFO "Setting up ${PRJNAME} ${RELEASE} from ${SETUPFILE}"
            SITEROOT="`(source ${SETUPFILE} -tag=${PRJNAME},${RELEASE} 2>&1 > /dev/null;[ $? -eq 0 ] && echo ${SITEROOT})`"
            if [ "$PRJTYPE" == "ext" ] ; then
                SITEROOT="`(source ${SETUPFILE} 2>&1 > /dev/null;env | grep ${RELLOC} 2>&1 > /dev/null;[ $? -eq 0 ] && echo ${RELLOC} || echo none)`"
            fi
            if [ "$SITEROOT" != "" ] ; then
                msgOut INFO "SITEROOT is ${SITEROOT}"
                #if [ -s "${SITEROOT}/setup.sh" -a "${RELLOC}" != "${SITEROOT}" -a "${SWLOC}" != "${SITEROOT}" ] ; then
                if [ "${RELLOC}" != "${SITEROOT}" -a "${SWLOC}" != "${SITEROOT}" ] ; then
                    if [ "$PRJTYPE" != "ext" ] ; then
                        msgOut INFO "The logical installation dir point to a different version of ${PRJNAME}. I will not delete ${SWLOC}."
                        SWLOC="none"
                    else
                        BASEDIR="`dirname ${SWLOC}`"
                        NUMDIRS="`\ls -d ${BASEDIR}/* | grep -v -E "${SWLOC}|${RELLOC}" | wc -l`"
                        if [ ${NUMDIRS} -gt 0 ] ; then
                            msgOut INFO "The logical installation dir point to a different version of ${PRJNAME}. I will not delete ${SWLOC}."
                            SWLOC="none"
                        fi
                    fi
                fi
            else
                msgOut INFO "No SITEROOT defined"
            fi
        else
            msgOut INFO "No release setup found (${SWLOC}/setup.sh or ${SWLOC}/cmtsite/setup.sh)"
        fi

        # Uninstall the releases
        for RELLOCFOUND in `\ls -d ${RELLOC} ${RELLOC}.r* 2>/dev/null` ; do
            LOCKFILE=${RELLOCFOUND}/atlas-install.lock
            if [ "$PRJTYPE" != "ext" ] ; then
                # Detect the physical installation area
                msgOut INFO "Trying with release $RELEASE in $RELLOCFOUND"

                # Check if any patch is installed
                if [ "$RELLOCFOUND" != "" -a "$PRJTYPE" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "${PRJTYPE}" != "eventview" ] ; then
                    msgOut INFO "Detecting patches for $RELEASE"
                    cd "${RELLOC}"
                    PATCHPATTERN="Atlas.*_`echo $RELEASE | sed 's#\.#_#g'`_[[:digit:]+].*"
                    INSTALLED_PATCHES="`pacman -lc -d none | grep "$PATCHPATTERN" | cut -d "_" -f 2-5 | sed 's#_#\.#g' | sort | uniq`"
                    if [ "$INSTALLED_PATCHES" != "" ] ; then
                        msgOut ERROR "The following patches to ${RELEASE} are installed"
                        msgOut ERROR "`echo ${INSTALLED_PATCHES} | sed 's# #,#g'`"
                        msgOut ERROR "Please remove all the patches before removing release $RELEASE"
                        return 150
                    else
                        msgOut INFO "No installed patches found for release $RELEASE"
                    fi
                fi
            fi

            # Wait for previous installation process completion
            if [ -f ${LOCKFILE} ] ; then
                msgOut WARNING "Another installation process is currently active. Now waiting..."
                waittime=0
                while `test -f ${LOCKFILE}`; do
                    sleep 1s
                    let waittime=$waittime+1
                    if [ $waittime -gt 3600 ] ; then
                        msgOut WARNING "Timeout [3600 s]"
                        msgOut WARNING "Removing stale installation lock"
                        rm -f ${LOCKFILE}
                    fi
                done
            fi
            if [ -d `dirname ${LOCKFILE}` ] ; then
                msgOut INFO "Locking the installation area"
                echo "$RELEASE installation lock" > ${LOCKFILE}
                case `whoami` in
                    usatlas*) msgOut INFO "This is an OSG site with static accounts. No further action required"
                        ;;
                    AAA*[0-9])
                        msgOut INFO "This site is configured for SGM pool accounts. Changing group permissions to ${LOCKFILE}"
                        chmod -R g+rw ${LOCKFILE} 2>/dev/null
                        [ $? -ne 0 ] && msgOut ERROR "Cannot change group write permissions to ${LOCKFILE}"
                        ;;
                esac
            else
                msgOut ERROR "Cannot lock the installation area because the directory does not exists."
            fi

            # Remove the physical installation
            if [ -d ${RELLOCFOUND} ] ; then
                RELLOCBEFORE="`du -sk ${RELLOCFOUND} 2>/dev/null | awk '{print $1}'`"
                [ "$RELLOCBEFORE" == "" ] && RELLOCBEFORE=0
                if [ $RELLOCBEFORE -lt $MININSTALLSIZE ] ; then
                    msgOut INFO "Physical installation area size is ${RELLOCBEFORE} kB. Removing the directory."
                    rm -fr ${RELLOCFOUND}
                    let removerc=$removerc+$?
                else
                    cd "${RELLOCFOUND}"
                    if [ "$PACKOPT" == "all" ] ; then
                        msgOut INFO "Removing gcc from $PWD"
                        pacman -remove ${RELEASE}/${GCC}
                    fi
                    if [ "$DBREL" != "" ] ; then
                        msgOut INFO "Removing DBRelease $DBREL from $PWD"
                        pacman -remove ${DBRELPKG}
                        let removerc=$removerc+$?
                        [ $removerc -ne 0 ] && msgOut WARNING "Error during DBRelease removal"
                    fi
                    msgOut INFO "Removing physical installation of ${ATLASRELEASE} from $PWD"
                    pacman -remove ${ATLASRELEASE}
                    let removerc=$removerc+$?
                    [ $removerc -ne 0 ] && msgOut ERROR "Error while removing ${ATLASRELEASE}"
                    if [ $removerc -eq 0 -a "$EXTRAPKG" != "" ] ; then
                        msgOut INFO "Removing physical installation of ${EXTRAPKG} from $PWD"
                        pacman -remove ${EXTRAPKG}
                        if [ $? -ne 0 ] ; then
                            msgOut WARNING "Cannot remove ${EXTRAPKG}"
                            msgOut ERROR "`pacman -last`"
                        fi
                    fi
                    if [ $removerc -ne 0 ] ; then
                        msgOut ERROR "`pacman -last`"
                    else
                        pacman -clear-snapshots

                        # Cleaning up the directories
                        [ -d dist/${RELEASE} ] && rm -fr dist/${RELEASE}
                        cd "${TOPDIR}"
                        RELLOCSIZE="`du -sk ${RELLOCFOUND} 2>/dev/null | awk '{print $1}'`"
                        [ "$RELLOCSIZE" == "" ] && RELLOCSIZE=-1
                        if [ ${RELLOCSIZE} -lt $MININSTALLSIZE ] ; then
                            if [ ${RELLOCSIZE} -lt 0 ] ; then
                                msgOut INFO "Physical installation area does not exists anymore."
                            else
                                msgOut INFO "Physical installation area size is ${RELLOCSIZE} kB. Removing the directory."
                                # Check if we're running in AFS and correct the installation path and removal method, if needed
                                if [ "`echo $RELLOCFOUND | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] ; then
                                    # Check if we are already in the rw path
                                    if [ "`echo $RELLOCFOUND | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
                                        AFSRLOC="`echo $RELLOCFOUND | sed 's#^/afs/\(.*\)#/afs/.\1#g'`"
                                        msgOut INFO "Removing data from volume $AFSRLOC"
                                        AFSREMOVE="`which afs_remove 2>/dev/null`"
                                        if [ "$AFSREMOVE" != "" ] ; then
                                            msgOut INFO "Destroying the volume using $AFSREMOVE"
                                            $AFSREMOVE $AFSRLOC
                                            let removerc=$removerc+$?
                                        else
                                            # Removing the directory contents
                                            msgOut INFO "No afs_remove found. Removing the contents of $RELLOCFOUND"
                                            rm -fr $RELLOCFOUND/*
                                            let removerc=$removerc+$?
                                            # Removing the directory itself, if this fails it's not a fatal error
                                            rmdir $RELLOCFOUND
                                            [ $? -ne 0 ] && msgOut WARNING "Cannot remove the directory $RELLOCFOUND"
                                        fi
                                    fi
                                else
                                    # Non-AFS filesystems
                                    rm -fr ${RELLOCFOUND}
                                    let removerc=$removerc+$?
                                fi
                            fi
                        else
                            msgOut INFO "Physical installation area size is ${RELLOCSIZE} kB. The directory is not empty."
                        fi 
                    fi
                fi
                RELLOCAFTER="`du -sk ${RELLOCFOUND} 2>/dev/null | awk '{print $1}'`"
                [ "$RELLOCAFTER" == "" ] && RELLOCAFTER=0
                msgOut INFO "Disk space saved: `echo $((${RELLOCBEFORE}-${RELLOCAFTER})) | awk '{printf "%7.1f", $1/1024}'` MB"
            else
                msgOut INFO "Physical installation area ($RELLOCFOUND) does not exists and no candidates have been found."
            fi
        done

        # Remove the logical installation, unless we're processing patches or we do not have it
        cd "${TOPDIR}"
        if [ "$PRJTYPE" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "${PRJTYPE}" != "eventview" -a "${SWLOC}" != "none" -a "$SWLOC" != "$RELLOC" ] ; then
            if [ -d ${SWLOC} ] ; then
                msgOut INFO "Removing logical installation from ${SWLOC}"
                SWLOCBEFORE="`du -sk ${SWLOC} 2>/dev/null | awk '{print $1}'`"
                [ "$SWLOCBEFORE" == "" ] && SWLOCBEFORE=0
                rm -fr "${SWLOC}"
                SWLOCAFTER="`du -sk ${SWLOC} 2>/dev/null | awk '{print $1}'`"
                [ "$SWLOCAFTER" == "" ] && SWLOCAFTER=0
                msgOut INFO "Disk space saved: `echo $((${SWLOCBEFORE}-${SWLOCAFTER})) | awk '{printf "%7.1f", $1/1024}'` MB"
            else
                msgOut INFO "Logical installation area ($SWLOC) does not exists."
            fi
        fi

        # Clean up the site configuration
        [ "$PRJTYPE" == "ext" -a "$PRJNAME" == "gcc" ] && unsetCompiler

        # Clean the local config
        [ "$PRJTYPE" == "poolcond" ] && unsetLocalConfig

        # List the software area contents
        SWLOCPATH="`dirname ${SWLOC}`" 
        RELLOCPATH="`dirname ${RELLOC}`" 
        if [ "${PRJTYPE}" != "patch" -a "${PRJTYPE}" != "p1patch" -a "$PRJTYPE" != "t0patch" -a "${PRJTYPE}" != "eventview" -a "$SWLOC" != "none" -a "$SWLOC" != "$RELLOC" ] ; then
            msgOut INFO "Showing contents of the logical installation path (${SWLOCPATH})"
            msgOut INFO "`\ls ${SWLOCPATH}`"
        fi
        msgOut INFO "Showing contents of the physical installation path (${RELLOCPATH})"
        msgOut INFO "`\ls ${RELLOCPATH}`"
        msgOut INFO "Unlocking the installation area"
        rm -f ${LOCKFILE}
    fi

    return $removerc
}

prepareTagging() {
    # Search and define the tagging utility
    if [ "$GRIDNAME" == "OSG" ] ; then
        TAG_UTILITY="OSGTags"
        msgOut INFO "Using embedded $TAG_UTILITY for $GRIDNAME Grid"
    else
        if [ "$GRIDNAME" != "EGEE" ] ; then
            msgOut INFO "Unknown Grid specified, assuming we are on EGEE"
            GRIDNAME="EGEE"
        fi
        TAG_UTILITY="`which lcg-tags 2> /dev/null`"
        if [ "$TAG_UTILITY" == "" ] ; then
            msgOut ERROR "Tagging utility (lcg-tags) not present."
            return 60
        else
            msgOut INFO "Using $TAG_UTILITY for $GRIDNAME Grid"
        fi
    fi
    return 0
}

addTag() {
    # Reset the environment
    ENVLAST="/tmp/sw-mgr-envlast.tmp.$$"
    #/usr/bin/printenv | grep -v '^_=' | sed -e "s/\([^=]\)=/\1='/" -e "s/$/'/g" > $ENVLAST
    /usr/bin/env | grep '=' | cut -d'=' -f 1 | egrep -v '^_$|^\s|^	|^$' | while read var; do echo "$var='`/usr/bin/printenv $var`'"; done > $ENVLAST
    if [ -s $ENVSTART ] ; then
        echo "ENVLAST=\"$ENVLAST\"" >> $ENVSTART
        msgOut INFO "Resetting the environment from $ENVSTART"
        source $ENVSTART
    fi

    # Prepare for tagging
    prepareTagging
    let addtagrc=$?

    # Manage the tags
    if [ "$TAGHOST" == "" ] ; then
        msgOut ERROR "No host to manage tags"
        let addtagrc=$addtagrc+1
    fi
    if [ "$TAGVO" == "" ] ; then
        msgOut ERROR "No VO to manage tags"
        let addtagrc=$addtagrc+1
    fi
    if [ $addtagrc -eq 0 ] ; then
        msgOut INFO "Listing current tags"
        msgOut INFO "`$TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list`"
        msgOut INFO "Adding tags $TAGNAME"
        if [ "$GRIDNAME" == "OSG" ] ; then
            [ "$TAGFILE" != "" ] && TF_OPT="--file $TAGFILE"
            $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --add --tags $TAGNAME --project $PRJNAME --location $RELLOC $TF_OPT
        else
            $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --add --tags $TAGNAME
        fi
        let addtagrc=$addtagrc+$?

        # Extra tag
        if [ $addtagrc -eq 0 ] ; then
            if [ "$EXTRATAG" != "" ] ; then
                TAGDEL="`$TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list | grep ${EXTRATAG}$ | tail -n 1`"
                if [ "$TAGDEL" != "" ] ; then
                    msgOut INFO "Removing tag $TAGDEL"
                    $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --remove --tags $TAGDEL
                    let addtagrc=$addtagrc+$?
                fi
                if [ $addtagrc -eq 0 ] ; then
                    msgOut INFO "Adding tag ${TAGNAME}-${EXTRATAG}"
                    if [ "$GRIDNAME" == "OSG" ] ; then
                        [ "$TAGFILE" != "" ] && TF_OPT="--file $TAGFILE"
                        $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --add --tags ${TAGNAME}-${EXTRATAG} --project $PRJNAME --location $RELLOC $TF_OPT
                    else
                        $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --add --tags ${TAGNAME}-${EXTRATAG}
                    fi
                    let addtagrc=$addtagrc+$?
                else
                    msgOut ERROR "Cannot remove tag $TAGDEL"
                fi
            fi
        fi
        msgOut INFO "Listing tags for $TAGHOST"
        msgOut INFO "`$TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list`"
        $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list | grep -q ${TAGNAME}
        if [ $addtagrc -eq 0 -a $? -ne 0 ] ; then
            msgOut ERROR "The tagging utility reports no error but the tag was not added"
            let addtagrc=$addtagrc+1
        fi
        if [ "$DUMPTAGS" != "" ] ; then
            # Check if we are running in AFS
            if [ "`echo $DUMPTAGS | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] ; then
                # Check if we are already in the rw path 
                if [ "`echo $DUMPTAGS | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
                    DUMPTAGS="`echo $DUMPTAGS | sed 's#^/afs/\(.*\)#/afs/.\1#g'`"
                fi
            fi
            msgOut INFO "Dumping tags into $DUMPTAGS"
            $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list > $DUMPTAGS
            if [ $? -ne 0 ] ; then
                msgOut ERROR "Cannot dump tags to $DUMPTAGS"
                let addtagrc=$addtagrc+1
            fi
        else
            msgOut INFO "No tag dump"
        fi
    fi

    # Reset the environment
    if [ -s $ENVLAST ] ; then
        msgOut INFO "Reverting to the environment from $ENVLAST"
        source $ENVLAST
        rm -f $ENVLAST
    fi

    # Return from this fuction
    return $addtagrc
}


removeTag() {
    # Reset the environment
    ENVLAST="/tmp/sw-mgr-envlast.tmp.$$"
    #/usr/bin/printenv | grep -v '^_=' | sed -e "s/\([^=]\)=/\1='/" -e "s/$/'/g" > $ENVLAST
    /usr/bin/env | grep '=' | cut -d'=' -f 1 | egrep -v '^_$|^\s|^	|^$' | while read var; do echo "$var='`/usr/bin/printenv $var`'"; done > $ENVLAST
    if [ -s $ENVSTART ] ; then
        echo "ENVLAST=\"$ENVLAST\"" >> $ENVSTART
        msgOut INFO "Resetting the environment from $ENVSTART"
        source $ENVSTART
    fi

    # Prepare for tagging
    prepareTagging
    let removetagrc=$?

    # Manage the tags
    if [ "$TAGHOST" == "" ] ; then
        msgOut ERROR "No host to manage tags"
        let removetagrc=$removetagrc+1
    fi
    if [ "$TAGVO" == "" ] ; then
        msgOut ERROR "No VO to manage tags"
        let removetagrc=$removetagrc+1
    fi
    if [ $removetagrc -eq 0 ] ; then
        msgOut INFO "Removing tags $TAGNAME"
        if [ "$GRIDNAME" == "OSG" ] ; then
            [ "$TAGFILE" != "" ] && TF_OPT="--file $TAGFILE"
            $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --remove --tags ${TAGNAME} --project $PRJNAME --location $RELLOC $TF_OPT
        else
            $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --remove --tags $TAGNAME
        fi
        let removetagrc=$removetagrc+$?

        # Extra tag
        if [ "$EXTRATAG" != "" ] ; then
            msgOut INFO "Removing tag ${TAGNAME}-${EXTRATAG}"
            if [ "$GRIDNAME" == "OSG" ] ; then
                [ "$TAGFILE" != "" ] && TF_OPT="--file $TAGFILE"
                $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --remove --tags ${TAGNAME}-${EXTRATAG} --project $PRJNAME --location $RELLOC $TF_OPT
            else
                $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --remove --tags ${TAGNAME}-${EXTRATAG}
            fi
            let removetagrc=$removetagrc+$?
        fi
        msgOut INFO "Listing current tags"
        msgOut INFO "`$TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list`"
        if [ "$DUMPTAGS" != "" ] ; then
            # Check if we are running in AFS
            if [ "`echo $DUMPTAGS | sed 's#^/\(afs\).*#\1#g'`" == "afs" ] ; then
                # Check if we are already in the rw path 
                if [ "`echo $DUMPTAGS | sed 's#^/afs/\(.\).*#\1#g'`" != "." ] ; then
                    DUMPTAGS="`echo $DUMPTAGS | sed 's#^/afs/\(.*\)#/afs/.\1#g'`"
                fi
            fi
            msgOut INFO "Dumping tags into $DUMPTAGS"
            $TAG_UTILITY --ce $TAGHOST --vo $TAGVO --list > $DUMPTAGS
            if [ $? -ne 0 ] ; then
                msgOut ERROR "Cannot dump tags to $DUMPTAGS"
                let removetagrc=$removetagrc+1
            fi
        fi
    fi

    # Reset the environment
    if [ -s $ENVLAST ] ; then
        msgOut INFO "Reverting to the environment from $ENVLAST"
        source $ENVLAST
        rm -f $ENVLAST
    fi

    # Return from this fuction
    return $removetagrc
}


relocateRelease() {
    FROMPATH=${1}
    TOPATH=${2}
    SPATH=${3}
    [ "$SPATH" == "" ] && SPATH=$FROMPATH

    msgOut INFO "Relocating files in $SPATH from $FROMPATH to $TOPATH"
    \find $SPATH -type f -path "*/cmt*/*" -o -name "*cmtref" -o -name "*.sh" -o -name "*.csh" | \
    while read INFILE; do
        grep $FROMPATH "$INFILE" 2>&1 > /dev/null
        if [ $? -eq 0 ] ; then
            echo "Relocating file $INFILE"
            INFILE_PERM="`stat -c %a $INFILE`"
            \mv "${INFILE}" "${INFILE}.old"
            cat "${INFILE}.old" | sed "s#$FROMPATH#$TOPATH#g" > "${INFILE}"
            [ -s "${INFILE}" ] && rm -f "${INFILE}.old"
            chmod 0$INFILE_PERM "${INFILE}"
        fi
    done

    msgOut INFO "Relocating links in $SPATH from $FROMPATH to $TOPATH"
    \find $SPATH -type l -lname "${FROMPATH}*" | \
    while read INLINK; do
        echo "Fixing link $INLINK"
        NEWLINK="`\ls -l "$INLINK" | awk -F " -> " '{print $2}' | sed "s#$FROMPATH#$TOPATH#g"`"
        echo ln -sf "$NEWLINK" "$INLINK"
        ln -sf "$NEWLINK" "$INLINK"
    done

    if [ -d "$SPATH/DBRelease" ] ; then
        msgOut INFO "Relocating DBRelease in $SPATH from $FROMPATH to $TOPATH"
        \find $SPATH/DBRelease -noleaf -type f -name "*.xml" | xargs -r sed -i "s#$FROMPATH#$TOPATH#g"
    fi
}


setDDMhelper() {
    # Check if dq2 and the python interface are available
    DDMHELPER="$INSTALLER_HOME/getFrontierEnv.py"
    if [ ! -s "$DDMHELPER" ] ; then
        msgOut ERROR "No getFrontierEnv.py found in $INSTALLER_HOME"
        return 1
    fi
    python -c "import dq2.info.TiersOfATLAS" &> /dev/null
    if [ $? -ne 0 ] ; then
        msgOut ERROR "DDM is not available or cannot import dq2.info.TiersOfATLAS"
        return 2
    fi
    msgOut INFO "Using DDM helper $DDMHELPER"
    return 0
}


genPoolcondPFC() {
    # Return code
    gprc=0

    # Check if dq2-ls and dq2-get are available
    DQ2LS="`which dq2-ls 2>/dev/null`"
    DQ2GET="`which dq2-get 2>/dev/null`"
    if [ "$DQ2LS" == "" ] ; then
        msgOut ERROR "No dq2-ls found"
        return 1
    fi
    if [ "$DQ2GET" == "" ] ; then
        msgOut ERROR "No dq2-get found"
        return 1
    fi

    # Check if we are able to use LFC
    python -c "import lfc" &> /dev/null
    let gprc=$?
    if [ $gprc -ne 0 ] ; then
        MAXREL=$((${#RELSETUPLIST[@]}-1))
        if [ ${MAXREL} -gt 0 ] ; then
            for r in `seq $MAXREL -1 0`; do
                msgOut WARNING "Cannot import LFC bindings using `which python`. Trying to setup the ATLAS sw release with ${RELSETUPLIST[$r]}"
                eval ${RELSETUPLIST[$r]}
                python -c "import lfc" &> /dev/null
                let gprc=$?
                if [ $gprc -eq 0 ] ; then
                    msgOut INFO "LFC import successful using release $AtlasVersion"
                    break
                fi
            done
        else
            msgOut ERROR "Cannot import LFC bindings using `which python` and no ATLAS sw release is found"
        fi
    fi
    if [ $gprc -ne 0 ] ; then
        msgOut ERROR "Cannot import LFC bindings"
        return $gprc
    fi

    # Set up the ddm helper
    [ "$DDMHELPER" == "" ] && setDDMhelper

    # Generate a Poolcond PFC for the local site
    if [ "$PCPATTERN" != "" ] ; then
        [ "$DDMSITE" == "" -a "$DQ2_LOCAL_SITE_ID" != "" ] && DDMSITE="`echo $DQ2_LOCAL_SITE_ID | sed 's/\(.*\)_\(.*\)/\1_HOTDISK/'`"
        if [ "$DDMSITE" != "" ] ; then
            PFCDIR="$PWD"
            PFCTMPDIR="$PWD/.pfctmp"
            [ ! -d $PFCTMPDIR ] && mkdir -p $PFCTMPDIR
            if [ -d $PFCTMPDIR ] ; then
                msgOut INFO "Proxy info:"
                msgOut INFO "`voms-proxy-info -all`"
                # Try to detect the se type from the DDM
                [ "$DDMHELPER" != "" ] && SETYPE="`python $DDMHELPER --setype $DDMSITE | tr a-z A-Z`"
            
                if [ -n "$PCTOPDIR" ] ; then
                    msgOut INFO "Local storage site detected. Storing the poolcond files in $PCTOPDIR"
                    [ ! -d $PCTOPDIR ] && mkdir $PCTOPDIR
                    if [ -d $PCTOPDIR ] ; then
                        SETYPE="FILE"
                        cd $PCTOPDIR
                        for d in $PCPATTERN; do
                            msgOut INFO "Getting dataset $d from $DDMSITE"
                            $DQ2GET -V -d -L ROAMING -s $DDMSITE $d
                            let gprc=$gprc+$?
                            [ $gprc -ne 0 ] && msgOut ERROR "Failed to get dataset $d"
                        done
                    else
                        msgOut ERROR "Cannot create $PCTOPDIR"
                        let gprc=1
                    fi
                elif [ -n "$SETYPE" ] ; then
                    msgOut INFO "$SETYPE site detected from DDM"
                elif [ -n "$DPM_HOST" ] ; then
                    msgOut INFO "DPM site detected from DPM_HOST"
                elif [ -n "$STORM_HOST" ] ; then
                    msgOut INFO "STORM site detected from STORM_HOST"
                else
                    msgOut INFO "Generic SE site detected (fallback)"
                fi
                cd $PFCTMPDIR
                msgOut INFO "Generating temporary PFC in $PWD"
                if [ "$SETYPE" != "FILE" ] ; then
                    for d in $PCPATTERN; do
                        msgOut INFO "Generating PFC in site $DDMSITE for dataset $d"
                        if [ "$SETYPE" == "DPM" -o -n "$DPM_HOST" ] ; then
                            $DQ2LS -P -R ".*/dpm/^rfio:/dpm/" -L $DDMSITE $d
                        elif [ "$SETYPE" == "STORM" -o -n "$STORM_HOST" ] ; then
                            $DQ2LS -P -R ".*://[A-Za-z0-9-._]*/^/" -L $DDMSITE $d
                        elif [ "$SETYPE" == "DCACHE" ] ; then
                            $DQ2LS -D -P -L $DDMSITE $d
                        else
                            $DQ2LS -P -G -L $DDMSITE $d
                        fi
                    done
                else
                    msgOut INFO "Generating T3-style PFC"
                    if [ "$PCTOPDIR" != "" ] ; then
                        $DQ2LS -P -G -L ROAMING -T $PCTOPDIR
                    else
                        msgOut ERROR "No topdir defined for $SETYPE storage type"
                    fi
                fi
                if [ -s PoolFileCatalog.xml ] ; then
                    msgOut INFO "PoolFileCatalog.xml generated successfully. Installing in $PFCDIR"
                    mv -f $PFCTMPDIR/PoolFileCatalog.xml $PFCDIR
                    let gprc=$gprc+$?
                    [ $gprc -ne 0 ] && msgOut ERROR "Cannot install PFC"
                    cd $PFCDIR; rm -fr $PFCTMPDIR
                    SITECONF="`getRWpath ${SITECONF}`"
                    if [ "`grep "^export ATLAS_POOLCOND_PATH=" ${SITECONF} 2>/dev/null | cut -d'=' -f 2-`" != "`dirname $PWD`" ] ; then
                        PCPATH="`dirname $PWD`"
                        PCPATH="`getROpath $PCPATH`"
                        msgOut INFO "Setting ATLAS_POOLCOND_PATH=$PCPATH in ${SITECONF}"
                        if [ -s "${SITECONF}" ] ; then
                            cp -f ${SITECONF} ${SITECONF}.orig
                            cat ${SITECONF}.orig | grep -v "^export ATLAS_POOLCOND_PATH=" > ${SITECONF}
                        fi
                        echo "export ATLAS_POOLCOND_PATH=$PCPATH" >> ${SITECONF}
                        let gprc=$gprc+$?
                        [ $gprc -ne 0 ] && msgOut ERROR "Cannot write into ${SITECONF}"
                    fi
                else
                    msgOut ERROR "PoolFileCatalog.xml not created or empty"
                    let gprc=2
                fi
                cd $PFCDIR; rm -fr $PFCTMPDIR
            else
                msgOut ERROR "Cannot create $PFCTMPDIR"
                let gprc=3
            fi
        else
            msgOut ERROR "No DDM site specified"
            let gprc=4
        fi
    else
        msgOut ERROR "No Poolcond pattern specified"
        let gprc=5
    fi
    return $gprc
}


unsetLocalConfig() {
    let unsetlcrc=0
    if [ "$LOCALCONF" != "" ] ; then
        LOCALCONF="`getRWpath ${LOCALCONF}`"
        msgOut INFO "Removing $LOCALCONF"
        rm -fr $LOCALCONF
        let unsetlcrc=$?
        [ $unsetlcrc -eq 0 ] && msgOut INFO "Removal successful" || msgOut ERROR "Cannot remove $LOCALCONF"
    else
        msgOut WARNING "No local configuration area specified"
    fi
    return $unsetlcrc
}


setLocalConfig() {
    let setlcrc=0

    # Set up the ddm helper
    if [ "$DDMHELPER" == "" ] ; then
        setDDMhelper
        let setlcrc=$?
        [ $setlcrc -ne 0 ] && return $setlcrc
    fi

    # Generate the local site setup
    if [ "$LOCALCONF" != "" ] ; then
        LOCALCONF="`getRWpath ${LOCALCONF}`"
        SITECONF="`getRWpath ${SITECONF}`"
        [ ! -d ${LOCALCONF} ] && mkdir -p ${LOCALCONF}
        [ ! -d ${LOCALCONF}/lib ] && mkdir -p ${LOCALCONF}/lib
        [ ! -d ${LOCALCONF}/lib64 ] && mkdir -p ${LOCALCONF}/lib64
        LOCALSETUP=${LOCALCONF}/setup.sh
        [ "$GOCNAME" == "" -a "$DDMSITE" != "" ] && GOCNAME="`echo $DDMSITE | sed 's/\(.*\)_\([^_]*\)/\1/'`"
        if [ "$GOCNAME" != "" ] ; then
            msgOut INFO "Getting Frontier setup for $GOCNAME using python $DDMHELPER $GOCNAME"
            FRONTIER_SETUP="`python $DDMHELPER $GOCNAME`"
            if [ "$FRONTIER_SETUP" != "" ] ; then
                msgOut INFO "Frontier setup for $GOCNAME is $FRONTIER_SETUP"
            else
                msgOut WARNING "Frontier setup for $GOCNAME is empty"
            fi
            eval $(LANG=C fgrep "ATLAS_POOLCOND_PATH=" ${SITECONF})
            if [ "$ATLAS_POOLCOND_PATH" != "" ] ; then
                msgOut INFO "ATLAS_POOLCOND_PATH for $GOCNAME is $ATLAS_POOLCOND_PATH"
            else
                msgOut ERROR "ATLAS_POOLCOND_PATH for $GOCNAME is empty"
                # This is a fatal error is we have a Frontier configuration
                [ "$FRONTIER_SETUP" != "" ] && setlcrc=1
            fi
        else
            msgOut ERROR "No DDM site specified"
            setlcrc=2
        fi
        if [ -s "${LOCALSETUP}" ] ; then
            mv -f ${LOCALSETUP} ${LOCALSETUP}.orig
            if [ $? -ne 0 ] ; then
                msgOut ERROR "Cannot make a backup copy of ${LOCALSETUP}"
                setlcrc=10
            fi
        fi
        if [ "$ATLAS_POOLCOND_PATH" != "" ] ; then
            echo "export ATLAS_POOLCOND_PATH=\"${ATLAS_POOLCOND_PATH}\"" >> ${LOCALSETUP}
            let setlcrc=$setlcrc+$?
        fi
        if [ "$FRONTIER_SETUP" != "" ] ; then
cat >> ${LOCALSETUP} <<EOD
export FRONTIER_SERVER="${FRONTIER_SETUP}"
export FRONTIER_LOG_LEVEL=warning
export FRONTIER_READTIMEOUTSECS=60
EOD
            let setlcrc=$setlcrc+$?
        fi
        [ $setlcrc -ne 0 ] && msgOut ERROR "Cannot write into ${LOCALSETUP}"

        # Try to detect the se type from the DDM
        [ "$DDMHELPER" != "" ] && SETYPE="`python $DDMHELPER --setype $DDMSITE | tr a-z A-Z`"

        # Check if this is not a DPM site and apply the dcache fixes
        if [ -z "$DPM_HOST" -a "$SETYPE" != "DPM" ] ; then
            msgOut INFO "This is not a DPM site. Applying the dcache fixes."
            echo "# dcache setup" >> ${LOCALSETUP}
            echo "export DCACHE_RAHEAD=TRUE" >> ${LOCALSETUP}
            echo "export DCACHE_RA_BUFFER=32768" >> ${LOCALSETUP}
            DCAPVER="`dccp -h 2>&1 | grep -i libdcap | sed 's/.*version-\([0-9]*\)-\([0-9]*\)-\([0-9]*\).*/\1.\2.\3/'`"
            #if [ `echo $DCAPVER | awk -F'.' '{for(i=1;i<=NF;i++) printf "%02d",$i}'` -lt 10243 ] ; then
                msgOut INFO "The libdcap version installed in this node is $DCAPVER, replacing with $DCAPURL"
                cd ${LOCALCONF}/lib
                wget --quiet -N -c $DCAPURL
                if [ $? -eq 0 ] ; then
                    msgOut INFO "Updated `basename $DCAPURL` installed successfully"
                else
                    msgOut WARNING "Failed to get $DCAPURL"
                    setlcrc=4
                fi
                cd -
            #else
            #    msgOut INFO "The dcap version installed in this node is $DCAPVER, no need to update the libraries."
            #fi
        else
            cd ${LOCALCONF}/lib
            msgOut INFO "This is possibly a DPM site, fixing the rfio libraries."
            LIBDPM="`find $LCG_LOCATION/lib -name 'libdpm.so' -xtype f 2>/dev/null`"
            if [ "$LIBDPM" != "" ] ; then
                ln -sf $LIBDPM libshift.so
                ln -sf $LIBDPM libshift.so.2.1
            else
                msgOut WARNING "Cannot find libdpm.so in LCG_LOCATION/lib ($LCG_LOCATION/lib)"
            fi
            GSSAPILIBNAME="libglobus_gssapi_gsi_gcc32dbgpthr.so"
            msgOut INFO "Fixing $GSSAPILIBNAME"
            if [ -f $GLOBUS_LOCATION/lib/$GSSAPILIBNAME ] ; then
                GSSAPILIB="$GLOBUS_LOCATION/lib/$GSSAPILIBNAME"
            elif [ -f $LCG_LOCATION/lib/$GSSAPILIBNAME ] ; then
                GSSAPILIB="$LCG_LOCATION/lib/$GSSAPILIBNAME"
            fi
            if [ -n $GSSAPILIB ] ; then
                GSSAPILIBARCH="`file -L $GSSAPILIB | sed 's/.*ELF \([0-9]*\)-bit.*/\1/'`"
                if [ "${GSSAPILIBARCH}" == "32" -o "${GSSAPILIBARCH}" == "64" ] ; then
                    msgOut INFO "Found a ${GSSAPILIBARCH}-bit ${GSSAPILIBNAME} library in `dirname ${GSSAPILIB}`"
                    # Install a fake library partner to avoid problems with LD_PRELOAD
                    if [ "${GSSAPILIBARCH}" == "32" ] ; then
                        msgOut INFO "Linking the ${GSSAPILIBARCH}-bit ${GSSAPILIBNAME} library to ${LOCALCONF}/lib/${GSSAPILIBNAME}"
                        ln -sf $GSSAPILIB ${LOCALCONF}/lib/${GSSAPILIBNAME}
                        LIBDIR=lib64
                        LIBARCH=64
                    else
                        msgOut INFO "Linking the ${GSSAPILIBARCH}-bit ${GSSAPILIBNAME} library to ${LOCALCONF}/lib64/${GSSAPILIBNAME}"
                        ln -sf $GSSAPILIB ${LOCALCONF}/lib64/${GSSAPILIBNAME}
                        LIBDIR=lib
                        LIBARCH=32
                    fi
                    msgOut INFO "Installing a fake ${LIBARCH}-bit ${GSSAPILIBNAME} library in ${LOCALCONF}/${LIBDIR}"
                    gcc -shared -fpic -o ${LOCALCONF}/${LIBDIR}/${GSSAPILIBNAME}.new -xc /dev/null -m${LIBARCH}
                    if [ -s ${LOCALCONF}/${LIBDIR}/${GSSAPILIBNAME}.new ] ; then
                        mv -f ${LOCALCONF}/${LIBDIR}/${GSSAPILIBNAME} ${LOCALCONF}/${LIBDIR}/${GSSAPILIBNAME}.save
                        mv -f ${LOCALCONF}/${LIBDIR}/${GSSAPILIBNAME}.new ${LOCALCONF}/${LIBDIR}/${GSSAPILIBNAME}
                    fi
                fi
            fi
            if [ -f "${LOCALCONF}/lib/${GSSAPILIBNAME}" ] ; then
                LOCALCONFRO="`getROpath ${LOCALCONF}`"
                echo "export LD_PRELOAD=${LOCALCONFRO}/'\$LIB'/${GSSAPILIBNAME}" >> ${LOCALSETUP}
            else
                msgOut INFO "Cannot find ${LOCALCONF}/lib/${GSSAPILIBNAME}"
            fi
            msgOut INFO "Local lib listing: `\ls -l`"
            cd -
        fi
        LOCALCONFRO="`getROpath ${LOCALCONF}`"
        LOCALSETUPRO="`getROpath ${LOCALSETUP}`"
        echo "export LD_LIBRARY_PATH=$LOCALCONFRO/lib:\$LD_LIBRARY_PATH" >> ${LOCALSETUP}
        echo "# allow local override at end" >> ${LOCALSETUP}
        echo "[ -f ${LOCALSETUPRO}.local ] && source ${LOCALSETUPRO}.local" >> ${LOCALSETUP}
        msgOut INFO "Local configuration file:"
        msgOut INFO "`cat ${LOCALSETUP}`"
    else
        msgOut ERROR "No local configuration area specified"
        setlcrc=5
    fi
    return $setlcrc
}


# Query the cached releases
query() {
    let queryrc=0
    mode="${1}"
    if [ "$mode" != "-quiet" ] ; then
        printf "List of releases available locally:\n"
        printf "===========================================================================\n"
        printf "| %12s | %10s | %20s | %20s |\n" "Type" "Version" "Architecture" "Date/Time"
        printf "===========================================================================\n"
    fi
    ATLVER_1=""
    ATLVER_2=""
    TMPFILE="/tmp/tmp.query.$$"
    for snap in `\ls -d $SNAPDIR/*.snap* 2>/dev/null` ; do
        snapname="`echo $snap | awk -F '-' '{print $2"-"$(NF-3)"-"$(NF-1)}' | sed 's/\.snap//g'`"
        ATLTYPE="`echo $snapname | cut -d '-' -f 1`"
        ATLVER="`echo $snapname | cut -d '-' -f 2`"
        ATLARCH="`echo $snapname | cut -d '-' -f 3`"
        ATLDT="`stat -c %y $snap 2>&1 | cut -d '.' -f 1`"
        if [ "$mode" != "-quiet" ] ; then
            printf "| %12s | %10s | %20s | %20s |\n" "$ATLTYPE" "$ATLVER" "$ATLARCH" "$ATLDT" >> $TMPFILE
        fi
        [ "$ATLVER_1" == "" ] && ATLVER_1="$ATLVER"
        ATLVER_2="$ATLVER"
    done
    cat $TMPFILE 2> /dev/null | sort -n -k 2
    rm -f $TMPFILE
    if [ "$mode" != "-quiet" ] ; then
        printf "===========================================================================\n"
    else
        if [ "${ATLVER_1}" != "${ATLVER_2}" ] ; then
            echo "${ATLVER_1}_${ATLVER_2}"
        else
            echo "${ATLVER_1}"
        fi
    fi
    return $queryrc
}


writeDVD() {
    let writedvdrc=0
    image="${1}"
    CDRECORD="cdrecord"
    CDSCAN="$CDRECORD -scanbus"
    CDWRITE="$CDRECORD -v -eject -dao"
    TMPSCAN=/tmp/tmp.scan.$$
    $CDSCAN 2>&1 \
            | awk '/.,.,..*CD-ROM/ {indx+=1; print "["indx"] "$0}' > $TMPSCAN
    cat $TMPSCAN
    echo -n "Please choose a device to write: "
    read dev
    DEV_ADDR="`grep \"^\[$dev\]\" $TMPSCAN | cut -f 2`"
    echo "Device $DEV_ADDR selected for writing..."
    rm -fr $TMPSCAN
    $CDWRITE dev=ATA:${DEV_ADDR} "${image}"
    let writedvdrc=$writedvdrc+$?
    return $writedvdrc
}


mkiso() {
    let mkisorc=0
    MKISOFS="mkisofs"
    image="${1}"
    volume="${2}"
    preparer="${3}"
    inpath="${4}"
    TMPDIR=/tmp/tmp.mkiso.$$
    mkdir "$TMPDIR"
    cd "$TMPDIR"
    ln -sf "$inpath" .
    cd "$TOPDIR"
    $MKISOFS -f -J -r -o "$image" -V "$volume" -p "$preparer" -m "*.gz" $TMPDIR
    rm -fr $TMPDIR
    echo "Do you want to write a DVD [Y/n] ?"
    read dowrite
    if [ "$dowrite" == "" -o "$dowrite" == "Y" -o "$dowrite" == "y" ] ; then
        writeDVD $image
    else
        echo "The DVD image $image has been created successfully"
    fi
    let mkisorc=$mkisorc+$?
    return $mkisorc
}

cleanup() {
    let cleanrc=0
    RELLOC="`getRWpath ${RELLOC}`"
    SWLOC="`getRWpath ${SWLOC}`"
    LOCKFILE="${RELLOC}/atlas-install.lock"
    if [ -f ${SWLOC}/setup.sh ] ; then
      SITEROOT="`(source ${SWLOC}/cmtsite/setup.sh &> /dev/null;echo $SITEROOT)`"
      [ "$SITEROOT" == "" ] && SITEROOT="`(source ${SWLOC}/setup.sh &> /dev/null;echo $SITEROOT)`"
      if [ "$SITEROOT" == "" ] ; then
          msgOut WARNING "Empty SITEROOT. The current installation is possibly corrupted. Resetting SITEROOT to ${RELLOC}"
          SITEROOT="${RELLOC}"
      fi
      SITEROOT="`getRWpath ${SITEROOT}`"
      if [ "${RELLOC}" != "${SWLOC}" -a "${RELLOC}" != "`echo ${SITEROOT} | sed 's#\.r[0-9]*$##g'`" ] ; then
        msgOut INFO "The logical installation points to a different SITEROOT (expected: ${RELLOC}, actual: ${SITEROOT}). I will not delete ${SWLOC}"
        SWLOC="none"
      fi
      LOCKFILE=${SITEROOT}/atlas-install.lock
    fi

    # Wait for previous installation process completion
    if [ -f ${LOCKFILE} ] ; then
        msgOut WARNING "Another installation process is currently active. Now waiting..."
        waittime=0
        while `test -f ${LOCKFILE}`; do
            sleep 1s
            let waittime=$waittime+1
            if [ $waittime -gt 3600 ] ; then
                msgOut WARNING "Timeout [3600 s]"
                msgOut WARNING "Removing stale installation lock"
                rm -f ${LOCKFILE}
            fi
        done
    fi
    msgOut INFO "Locking the installation area"
    echo "$RELEASE installation lock" > ${LOCKFILE}
    case `whoami` in
        usatlas*) msgOut INFO "This is an OSG site with static accounts. No further action required"
            ;;
        AAA*[0-9])
            msgOut INFO "This site is configured for SGM pool accounts. Changing group permissions to ${LOCKFILE}"
            chmod -R g+rw ${LOCKFILE} 2>/dev/null
            [ $? -ne 0 ] && msgOut ERROR "Cannot change group write permissions to ${LOCKFILE}"
        ;;
    esac

    # Clean the site config
    SITECONF="`getRWpath ${SITECONF}`"
    if [ "$PRJTYPE" == "poolcond" -a "`grep "^export ATLAS_POOLCOND_PATH" 2>/dev/null ${SITECONF}`" != "" ] ; then
        msgOut INFO "Removing ATLAS_POOLCOND_PATH from ${SITECONF}"
        cp -f ${SITECONF} ${SITECONF}.orig
        cat ${SITECONF}.orig | grep -v "^export ATLAS_POOLCOND_PATH" > ${SITECONF}
        [ ! -s ${SITECONF} ] && rm -f ${SITECONF}
    fi

    # Clean the local config
    [ "$PRJTYPE" == "poolcond" ] && unsetLocalConfig

    # Clean up the compiler configuration
    [ "$PRJTYPE" == "ext" -a "$PRJNAME" == "gcc" ] && unsetCompiler

    # Clean the release
    if [ "$REINSTALL" != "yes" ] ; then
      if [ "${SWLOC}" != "${RELLOC}" ] ; then
        if [ -d ${SWLOC} ] ; then
          msgOut INFO "Removing $SWLOC"
          SWLOCBEFORE="`du -sk ${SWLOC} 2>/dev/null | awk '{print $1}'`"
          [ "$SWLOCBEFORE" == "" ] && SWLOCBEFORE=0
          rm -fr $SWLOC
          let swclean=$?
          let cleanrc=$cleanrc+$swclean
          [ $swclean -ne 0 ] && msgOut ERROR "An error occurred while removing ${SWLOC}"
          SWLOCAFTER="`du -sk ${SWLOC} 2>/dev/null | awk '{print $1}'`"
          [ "$SWLOCAFTER" == "" ] && SWLOCAFTER=0
          msgOut INFO "Disk space saved: `echo $((${SWLOCBEFORE}-${SWLOCAFTER})) | awk '{printf "%7.1f", $1/1024}'` MB"
        else
          msgOut INFO "No directory ${SWLOC} found"
        fi
      fi
    fi

    if [ "$REINSTALL" != "yes" ] ; then
      RELLOCS="`\ls -d ${RELLOC} ${RELLOC}.r* 2>/dev/null`"
    else
      [ "$SITEROOT" == "" ] && SITEROOT="$RELLOC"
      msgOut INFO "Skipping $SITEROOT"
      RELLOCS="`\ls -d ${RELLOC} ${RELLOC}.r* 2>/dev/null | grep -v $SITEROOT`"
    fi
    for RLOC in ${RELLOCS} ; do
      msgOut INFO "Removing $RLOC"
      RELLOCBEFORE="`du -sk ${RLOC} 2>/dev/null | awk '{print $1}'`"
      [ "$RELLOCBEFORE" == "" ] && RELLOCBEFORE=0
      # Physically remove the installation directory
      # Check if we're running in AFS and correct the installation path and removal method, if needed
      if [ "`isAFSpath $RLOC`" == "yes" ] ; then
          msgOut INFO "Removing data from volume $RLOC"
          AFSREMOVE="`which afs_remove 2>/dev/null`"
          AFSMP="`isAFSmountpoint $RLOC`"
          if [ "$AFSMP" != "" ] ; then
              if [ "$AFSREMOVE" != "" ] ; then
                  msgOut INFO "Destroying the volume using $AFSREMOVE"
                  $AFSREMOVE $RLOC
                  let relclean=$?
              else
                  # Removing the directory contents
                  msgOut INFO "No afs_remove found. Removing the contents of $RLOC"
                  rm -fr $RLOC/*
                  let relclean=$?
                  # Removing the directory itself, if this fails it's not a fatal error
                  rmdir $RLOC
                  [ $? -ne 0 ] && msgOut WARNING "Cannot remove the directory $RLOC"
              fi
          else
              # Remove the orphaned directory
              msgOut WARNING "$RLOC is not an afs mountpoint. Will remove it"
              rm -fr $RLOC
              let relclean=$?
          fi
      else
          # Non-AFS filesystems
          rm -fr $RLOC
          let relclean=$?
      fi
      let cleanrc=$cleanrc+$relclean
      [ $relclean -ne 0 ] && msgOut ERROR "An error occurred while removing ${RLOC}"
      RELLOCAFTER="`du -sk ${RLOC} 2>/dev/null | awk '{print $1}'`"
      [ "$RELLOCAFTER" == "" ] && RELLOCAFTER=0
      msgOut INFO "Disk space saved: `echo $((${RELLOCBEFORE}-${RELLOCAFTER})) | awk '{printf "%7.1f", $1/1024}'` MB"
    done
    if [ "$RELLOCS" == "" ] ; then
      msgOut INFO "No directory ${RELLOC} or ${RELLOC}.r* found or the directory is in use and you request to cleanup after a reinstallation"
    fi

    # End of function, check for errors
    if [ $cleanrc -ne 0 ] ; then
        msgOut ERROR "Cannot remove the installation directories"
    else
        msgOut INFO "Cleanup OK"
    fi

    # List the software area contents
    RELLOCPATH="`dirname ${RELLOC}`" 
    if [ "${SWLOC}" != "${RELLOC}" ] ; then
        SWLOCPATH="`dirname ${SWLOC}`" 
        msgOut INFO "Showing contents of the logical installation path (${SWLOCPATH})"
        msgOut INFO "`\ls ${SWLOCPATH}`"
    fi
    msgOut INFO "Showing contents of the physical installation path (${RELLOCPATH})"
    msgOut INFO "`\ls ${RELLOCPATH}`"

    # Unlock the installation area
    msgOut INFO "Unlocking the installation area"
    rm -f ${LOCKFILE}

    return $cleanrc
}

setupPacman() {
    let setuprc=0
    # Save the current directory
    CURDIR=$PWD
    # Use ${TOPDIR} to store pacman
    cd ${TOPDIR}
    # Download/find and install pacman, if needed
    if [ ! -d ${PACMAN_DIR} ] ; then
        msgOut WARNING "Pacman not found in `dirname ${PACMAN_DIR}`"
        if [ ! -s ${PACMAN_TAR} ] ; then
            wget ${PACMAN_URL}/`basename ${PACMAN_TAR}`
            let setuprc=$setuprc+$?
            if [ ! -s ${PACMAN_TAR} ] ; then
                msgOut ERROR "Cannot get pacman ${PACMAN_VER} from ${PACMAN_URL}"
                return 50
            fi
        fi
        msgOut INFO "Installing pacman ${PACMAN_VER}"
        tar xfz ${PACMAN_TAR}
        let setuprc=$setuprc+$?
        rm -f ${PACMAN_TAR}
        PACMAN_DIR="$PWD/`basename ${PACMAN_DIR}`"
        cd "${PACMAN_DIR}"
        [ "${PACMAN_PATCH}" != "" -a -s "${PACMAN_PATCH}" ] && \
             patch -p1 < ${PACMAN_PATCH}
        cd "${TOPDIR}"
    fi

    # Setup pacman
    cd "${PACMAN_DIR}"
    source $PWD/setup.sh
    let setuprc=$setuprc+$?
    if [ $setuprc -eq 0 ] ; then
        msgOut INFO "pacman ${PACMAN_VER} installed and set up correctly from ${PACMAN_DIR}."
        if [ "`which pacman 2>/dev/null`" == "" ] ; then
            msgOut ERROR "Cannot find the 'pacman' executable"
            msgOut INFO  "$PWD"
            msgOut INFO  "$PACMAN_LOCATION"
            setuprc=10
        fi
    else
        msgOut ERROR "Unable to setup pacman ${PACMAN_VER}."
    fi
    # Go back to the startup directory
    cd $CURDIR
    return $setuprc
}

# MAIN program
msgOut INFO "$VERSION starting"

# Deafults
MKDVD="no"
PACKOPT="all"
PRJNAME="release"
PRJTYPE="release"
PRJOPT="opt"
PACMAN_VER="3.18.5"
TEMPCACHE="no"
TAGACTION="none"
REGISTER="no"
RELVER="1"
USEGRID="no"
GRIDREPLICA="no"
TAGVO="atlas"
MINDF="6000000:20000:3000000"
MININSTALLSIZE=100000
REQSHAREDFS="no"
XMLFILE=""
T_POST="no"
REINSTALL="no"
UPDATE="no"
EXTRATAG=""
FORCETAGS="no"
KVPOSTTAG=""
KVKEEP="n"
ATLAS=""
QUIET=""
SNAPNAME=""
TESTTHR="1"
USEPACBALL="no"
DEBUG="no"
POSTSITEINFO="no"
POSTSITEURL="http://atlas-install.roma1.infn.it/atlas_install/exec/updinfo.php"
POSTRELURL="http://atlas-install.roma1.infn.it/atlas_install/exec/relstat.php"
GRIDNAME="EGEE"
TAGFILE=""
COMPATURL="http://classis01.roma1.infn.it/pacman/packages/sl4_to_sl5"
COMPATPATCH=(patch-slc4-to-slc5-modular.sh AtlasCore_PlatformPolicy.tgz AtlasCore_SLC4_Compat.tgz AtlasLogin.tar.gz AtlasSettings.tar.gz slc4compat.tar.gz)
DCAPURL="http://classis01.roma1.infn.it/pacman/packages/dcap/libdcap.so"

OPTS=`getopt -o d:D:fgG:H:i:k:l:m:M:oO:p:P:Qr:R:s:St:T:x:w:hcCfnNquv:V -l add-tags,check,cleanup,compiler-home:,debug,dest:,dbrelease:,ddm-setup:,ddm-site:,dir:,disk-free:,dump-tags:,extra-tag:,extra-pkg:,force-tags,goc-name:,grid-name:,kv-conf:,kv-disable:,kv-enable:,kv-keep,kvpost-tag:,grid-cache,host:,install:,install-compiler,kit-cache:,kv-cache:,kvpost,local-config:,logical:,manage:,min-install-size:,no-opt,no-tag,no-compat-patch,override-lock,package:,pacman-ver:,pretend-platform:,physical:,post-siteinfo,project:,project-opt:,project-type:,quiet,reinstall,reinstall-clean,release-only,pacball,pacball-repo:,poolcond-topdir:,poolcond-pattern:,release-setup:,release-ver:,replicate,remove:,remove-snap:,remove-tags,require-compiler,require-shfs,require-prj:,setenv:,set-frontier,setup-latest:,site-config:,snap:,snapdir:,snapname:,tag-file:,tags:,target:,temp-cache,test:,tthreads:,update,use-grid,vo:,validate,validation-exe:,xml:,create-dvd,write-dvd:,help,force,no-cache,no-version,query -- "$@"` 
if [ $? != 0 ] ; then echo "Terminating..."; exit -1 ; fi
eval set -- "$OPTS"

while true ; do
    case "$1" in
        --add-tags)         TAGACTION="add";shift;;
        --dump-tags)        DUMPTAGS="$2";shift 2;;
        --create-dvd|-c)    ACTION="mkiso";shift;;
        --cleanup|-C)       ACTION="cleanup";shift;;
        --check)            ACTION="check";shift;;
        --compiler-home)    COMPILER_HOME="$2";shift 2;;
        --ddm-setup)        DDMSETUP="$2";shift 2;;
        --ddm-site)         DDMSITE="$2";shift 2;;
        --debug)            DEBUG="yes";shift;;
        --disk-free|-D)     MINDF="$2";shift 2;;
        --dbrelease)        DBREL="$2";shift 2;;
        --extra-tag)        EXTRATAG="$2";shift 2;;
        --extra-pkg)        EXTRAPKG="$2";shift 2;;
        --force-tags|-f)    FORCETAGS="yes";shift;;
        --goc-name)         GOCNAME="$2";shift 2;;
        --install-compiler) INSTCOMPILER="yes";shift;;
        --grid-name|-G)     GRIDNAME="$2";shift 2;;
        --kv-cache)         LCGCACHE="$2";shift 2;;
        --kv-conf)          KVCONFURL="$2";shift 2;;
        --kv-disable)       KVD="$2";shift 2;;
        --kv-enable)        KVE="$2";shift 2;;
        --kv-keep)          KVKEEP="y";shift;;
        --kvpost)           T_POST="yes";shift;;
        --kvpost-tag)       KVPOSTTAG="$2";shift 2;;
        --validate|-V)      ACTION="validate";shift;;
        --force|-f)         PACMAN_OPTS="$PACMAN_OPTS -clear-lock";shift;;
        --override-lock)    PACMAN_OPTS="$PACMAN_OPTS -allow lock-override";shift;;
        --pretend-platform) PACMAN_OPTS="$PACMAN_OPTS -pretend-platform:$2";shift 2;;
        --help|-h)          help;exit;;
        --host|-H)          TAGHOST="$2";shift 2;;
        --vo)               TAGVO="$2";shift 2;;
        --install|-i)       ACTION="install";RELEASE="$2";shift 2;;
        --manage|-M)        ACTION="manage";RELEASE="$2";shift 2;;
        --kit-cache|-k)     ATLAS="$2";shift 2;;
        --min-install-size) MININSTALLSIZE="$2";shift 2;;
        --dest)             SWPATH="$2";shift 2;;
        --local-config)     LOCALCONF="$2";shift 2;;
        --logical|-l)       SWLOC="$2";shift 2;;
        --no-opt)           NOOPT="yes";shift;;
        --no-tag)           NOTAG="yes";shift;;
        --no-cache|-n)      NOCACHE="yes";shift;;
        --no-version)       NOVERSION="yes";shift;;
        --no-compat-patch)  COMPATPATCH="";shift;;
        --package)          PACKAGE="$2";shift 2;;
        --pacman-ver|-m)    PACMAN_VER="$2";shift 2;;
        --physical|-p)      RELLOC="$2";shift 2;;
        --poolcond-topdir)  PCTOPDIR="$2";shift 2;;
        --poolcond-pattern) PCPATTERN="$2";shift 2;;
        --post-siteinfo)    POSTSITEINFO="yes";shift;;
        --project|-P)       PRJNAME="$2";shift 2;;
        --project-opt|-O)   PRJOPT="$2";shift 2;;
        --project-type|-T)  PRJTYPE="`echo $2 | tr [A-Z] [a-z]`";shift 2;;
        --quiet|-Q)         QUIET="yes";shift;;
        --require-compiler) REQCOMPILER="yes";shift;;
        --require-prj)      REQPRJNAME="$2";shift 2;;
        --use-grid|-g)      USEGRID="yes";shift;;
        --pacball)          USEPACBALL="yes";shift;;
        --pacball-repo)     PACBALLREPO="$2";shift 2;;
        --reinstall)        REINSTALL="yes";shift;;
        --reinstall-clean)  REINSTALLCLEAN="yes";shift;;
        --release-only|-o)  PACKOPT="rel";shift;;
        --release-setup)    RELSETPATH="$2";shift 2;;
        --release-ver|-v)   RELVER="$2";shift 2;;
        --remove|-r)        ACTION="remove";RELEASE="$2";shift 2;;
        --remove-snap|-R)   ACTION="remove-snap";RELEASE="$2";shift 2;;
        --remove-tags)      TAGACTION="remove";shift;;
        --replicate)        GRIDREPLICA="yes";shift;;
        --require-shfs|-S)  REQSHAREDFS="yes";shift;;
        --setenv)           SETENV="$2";shift 2;;
        --set-frontier)     SETFRONTIER="y";shift;;
        --setup-latest)     PRESETUP="$2";shift 2;;
        --site-config)      SITECONF="$2";shift 2;;
        --snap|-s)          ACTION="snap";RELEASE="$2";shift 2;;
        --snapname)         SNAPNAME="$2";shift 2;;
        --snapdir)          SNAPDIR="$2";shift 2;;
        --tag-file)         TAGFILE="$2";shift 2;;
        --tags)             TAGNAME="$2";shift 2;;
        --target|-t)        ARCH="$2";shift 2;;
        --temp-cache)       TEMPCACHE="yes";shift;;
        --test)             ACTION="test";RELEASE="$2";shift 2;;
        --tthreads)         TESTTHR="$2";shift 2;;
        --update|-u)        UPDATE="yes";shift;;
        --dir|-d)           TOPDIR="$2";shift 2;;
        --query|-q)         ACTION="query";shift;;
        --write-dvd|-w)     ACTION="writeiso";ISOIMAGE="$2";shift 2;;
        --xml|-x)           XMLFILE="${2}";shift 2;;
        --validation-exe)   VALEXE="$2";shift 2;;
        --)                 shift;break;;
        \?)                 break;
        exit;;
    esac
done

export T_POST
CATALOG_PATH="/grid/$TAGVO/install/lcg"
PRJTAGNAME="`echo $PRJNAME | sed 's#^Atlas##g' | tr [A-Z] [a-z]`"
PACMAN_OPTS="$PACMAN_OPTS -trust-all-caches -allow tar-overwrite -allow unsupported-platforms"
[ "`echo $MINDF | cut -d':' -f 1`" != "" ] && MINRELDF="`echo $MINDF | cut -d':' -f 1`"
[ "`echo $MINDF | cut -d':' -f 2`" != "" ] && MINSWDF="`echo $MINDF | cut -d':' -f 2`"
[ "`echo $MINDF | cut -d':' -f 3`" != "" ] && MINTDDF="`echo $MINDF | cut -d':' -f 3`"
[ "$TAGNAME" == "" ]  && TAGNAME="VO-atlas-${PRJTAGNAME}-${RELEASE}"

# PoolCond pattern
PCSCHEMA="`echo $PCPATTERN | sed 's#\(http.*\)://\(.*\)#\1#'`"
if [ "$PCSCHEMA" == "http" -o "$PCSCHEMA" == "https" ] ; then
    wget -N -c $PCPATTERN
    PCSCHEMAFILE="`basename $PCPATTERN`"
    PCPATTERN="`cat $PCSCHEMAFILE 2> /dev/null`"
else
    PCPATTERN="`echo $PCPATTERN | sed 's/+/ /g'`"
fi

# Grid stuff
if [ "$USEGRID" == "yes" ] ; then
    CLOSESE="`edg-brokerinfo getCloseSEs 2>/dev/null| head -n 1 | awk '{ print $1}' | tr [A-Z] [a-z] | grep -v ^error`"
    [ "$CLOSESE" == "" ] && CLOSESE="`glite-brokerinfo getCloseSEs 2>/dev/null| head -n 1 | awk '{ print $1}' | tr [A-Z] [a-z] | grep -v ^error`"
    [ "$CLOSESE" != "" ] && msgOut INFO "Close SE: $CLOSESE" || msgOut WARNING "No close SE found"
fi
if [ "$XMLFILE" != "" ] ; then
    [ "`dirname $XMLFILE`" == "." ] && XMLFILE="$PWD/`basename $XMLFILE`"
    xml open
fi

msgOut INFO "Initial umask: `umask`"
case `whoami` in
    usatlas*) msgOut INFO "This is an OSG site with static accounts. Setting umask to g-w,o-w,a+rx"
        umask g-w,o-w,a+rx
        ;;
    AAA*[0-9])
        msgOut INFO "This site is configured for SGM pool accounts. Setting umask to g+w,o-w,a+rx"
        umask g+w,o-w,a+rx
        ;;
    *) msgOut INFO "This site is configured for SGM static accounts. Setting umask to g-w,o-w,a+rx"
        umask g-w,o-w,a+rx
        ;;
esac
msgOut INFO "Using umask `umask`"


INSTALLER_HOME="`dirname $0`"
if [ "$XMLFILE" != "" ] ; then
    [ "$XMLFILE" == "`basename $XMLFILE`" ] && XMLFILE=$INSTALLER_HOME/$XMLFILE
fi
[ "$INSTALLER_HOME" == "." ] && INSTALLER_HOME="$PWD"
[ "$TOPDIR" == "" ] && TOPDIR="${PWD}"
[ "$ARCH"   == "" ] && ARCH="rh73"
if [ "$ACTION" == "" ] ; then
    msgOut ERROR "No action specified. Type -h for help."
    [ "$XMLFILE" != "" ] && xml close
    exit -1
fi
[ ! -d $TOPDIR ] && mkdir $TOPDIR
\find $TOPDIR -maxdepth 1 -type d ! -perm -a+rx -exec chmod a+rx {} \;
export PATH=.:$INSTALLER_HOME:$PATH
[ "$VO_ATLAS_SW_DIR" == "" ] && export VO_ATLAS_SW_DIR=$TOPDIR
export PATH=$VO_ATLAS_SW_DIR:$PATH
[ "$SITECONF" == "" ] && SITECONF=$VO_ATLAS_SW_DIR/AtlasSiteConfig.sh
[ -s $PWD/lcg-tags ] && chmod +x $PWD/lcg-tags
[ "$LCGCACHE" == "" ] && LCGCACHE="http://classis01.roma1.infn.it/pacman/cache"
if [ "$ACTION" == "genpfc" ] ; then
    [ "$PCDIR" == "" ] && PCDIR="$VO_ATLAS_SW_DIR/local/conditions"
    [ "$PCPATTERN" == "" ] && PCPATTERN="comcond* cmccond* cond09* cond08* oflcond.*"
fi
DBRELCACHE="http://atlas.web.cern.ch/Atlas/GROUPS/DATABASE/pacman4/DBRelease"
DBRELPKG="DBRelease-$DBREL"
if [ "$ATLAS" == "" ] ; then
  if [ "$PRJNAME" == "release" -o "$PRJNAME" == "AtlasRelease" ] ; then
    ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/monolith/slc3/cache"
  else
    if [ "$PRJTYPE" == "p1nightly" ] ; then
      ATLAS="$TOPDIR/AtlasPoint1.caches"
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel1/pcache/cache" > $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_0/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_1/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_2/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_3/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_4/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_5/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/pcache1/rel_6/cache" >> $ATLAS
      echo "http://atlas-computing.web.cern.ch/atlas-computing/links/kitsDirectory/projects/cache" >> $ATLAS
    elif [ "$PRJTYPE" == "bugfix" ] ; then
      ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/bugfix/cache"
    elif [ "$PRJTYPE" == "dev" ] ; then
      ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/buildDirectory/kitrel/nightlies/dev/cache"
    elif [ "$PRJTYPE" == "patch" ] ; then
      ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/kitsDirectory/Production/cache"
      [ "$REQPRJNAME" == "" ] && REQPRJNAME="AtlasOffline"
    elif [ "$PRJTYPE" == "p1patch" -o "$PRJTYPE" == "t0patch" ] ; then
      ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/kitsDirectory/Production/cache"
      [ "$REQPRJNAME" == "" ] && REQPRJNAME="AtlasOffline"
    elif [ "$PRJTYPE" == "eventview" ] ; then
      ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/kitsDirectory/PAT/EventView"
      [ "$REQPRJNAME" == "" ] && REQPRJNAME="AtlasOffline"
    elif [ "$PRJTYPE" == "ext" ] ; then
      ATLAS="http://classis01.roma1.infn.it/pacman/cache"
    else
      ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/kitsDirectory/projects/cache"
    fi
  fi
fi
PACMAN_URL="http://physics.bu.edu/pacman/sample_cache/tarballs"
PACMAN_DIR=${INSTALLER_HOME}/pacman-${PACMAN_VER}
PACMAN_TAR=${PACMAN_DIR}.tar.gz
[ "$SNAPDIR" == "" ] && SNAPDIR=${TOPDIR}/snapshots
# Define the snapshot name
if [ "$SNAPNAME" == "" ] ; then
  SNAPNAME="atlas-`echo ${PRJNAME} | tr [A-Z] [a-z] | sed 's#^atlas##g'``echo -${PRJTYPE} | tr [A-Z] [a-z] | sed 's#-release##g'`-${RELEASE}-${RELVER}"
  [ "$ARCH" != "" ] && SNAPNAME="${SNAPNAME}-`echo ${ARCH} | sed -e 's#^_##g'`"
  [ "$PRJOPT" != "" ] && SNAPNAME="${SNAPNAME}-${PRJOPT}"
  msgOut INFO "Self-generated snapshot name: $SNAPNAME"
else
  SNAPNAME="`echo $SNAPNAME | sed -e 's/.tar.gz//g' -e 's/.tgz//g'`"
  msgOut INFO "Requested snapshot name: $SNAPNAME"
fi

[ -s ${INSTALLER_HOME}/`basename ${SNAPDIR}`/${SNAPNAME} ] \
                      && SNAPDIR="${INSTALLER_HOME}/`basename ${SNAPDIR}`"

KV=KitValidation
if [ "$PACKAGE" != "" ] ; then
  ARC="`uname -m`"
  GCC=gcc${ARCH}
  ATLASRELEASE="${PACKAGE}"
elif [ "$ARCH" == "rh73_old" ] ; then
  GCC=gcc
  ATLASRELEASE="${RELEASE}/AtlasRelease-opt"
elif [ "$ARCH" == "slc3" ] ; then
  GCC=gcc-slc3
  ATLASRELEASE="${RELEASE}/AtlasRelease-${ARCH}-opt"
  ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/monolith/slc3/cache"
elif [ "$ARCH" == "slc3_ia32" ] ; then
  GCC=gcc-slc3
  ATLASRELEASE="${RELEASE}/AtlasRelease-${ARCH}-opt"
  ATLAS="http://atlas-computing.web.cern.ch/atlas-computing/links/monolith/slc3/cache"
elif [ "`echo $ARCH | grep ^_`" != "" -a "$PRJNAME" != "release" -a "$PRJNAME" != "AtlasRelease" ] ; then
  ARC="`uname -m`"
  GCC=gcc${ARCH}
  REL="`echo ${RELEASE} | sed "s#\.#_#g"`"
  ATLASRELEASE="${PRJNAME}_${REL}${ARCH}"
  [ "$PRJOPT" != "" -a "$NOOPT" != "yes" ] && ATLASRELEASE="${ATLASRELEASE}_${PRJOPT}"
elif [ "$ARCH" == "noarch" ] ; then
  ATLASRELEASE="${PRJNAME}"
  [ "$NOVERSION" != "yes" ] && ATLASRELEASE="${ATLASRELEASE}-${RELEASE}" || ATLASRELEASE="${ATLASRELEASE}|version('${RELEASE}')"
else
  GCC=gcc-${ARCH}
  ATLASRELEASE="${RELEASE}/AtlasRelease-${ARCH}-opt"
fi

# Initialize the return code
let rc=0

[ "$DEBUG" == "yes" ] && msgOut DEBUG "Debug output enabled"

# Show the site info
showSiteInfo
if [ "$DEBUG" == "yes" ] ; then
    msgOut DEBUG "PATH=${PATH}"
    msgOut DEBUG "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
    msgOut DEBUG "PYTHONPATH=${PYTHONPATH}"
fi

# Setup pacman
cd "${TOPDIR}"
if [ "$ACTION" == "validate" -o "$ACTION" == "install" -o "$ACTION" == "test" -o "$ACTION" == "remove" -o "$ACTION" == "snap" ] ; then
    if [ "$ACTION" == "validate" -o "$ACTION" == "install" ] ; then
        [ "$USEPACBALL" == "yes" ] && SKIPSETUP="yes"
    fi
    [ "$PRJTYPE" == "poolcond" ] && SKIPSETUP="yes"
    # Skip the pacman setup if we're installing and using pacballs
    if [ "$SKIPSETUP" == "" -a "`which pacman 2>/dev/null`" == "" ] ; then    
        setupPacman
        let rc=$rc+$?
        if [ $rc -ne 0 ] ; then
            msgOut ERROR "Cannot setup pacman"
            [ "$XMLFILE" != "" ] && xml close
            exit $rc
        fi
        if [ "$DEBUG" == "yes" ] ; then
            msgOut DEBUG "PATH=${PATH}"
            msgOut DEBUG "LD_LIBRARY_PATH=${LD_LIBRARY_PATH}"
            msgOut DEBUG "PYTHONPATH=${PYTHONPATH}"
        fi
    else
        msgOut INFO "I will not download pacman since we are using pacballs or pacman has been disabled."
    fi
fi

# Define the installation directories
[ "$DEBUG" == "yes" ] && msgOut DEBUG "SWLOC [1] =$SWLOC"
if [ "$SWLOC" == ""  ] ; then
    [ "$RELLOC" != "" ] && SWLOC="$RELLOC" \
                        || SWLOC="${TOPDIR}/software/${RELEASE}"
fi
[ "$RELLOC" == "" ] && RELLOC=${TOPDIR}/releases
[ ! -d "$RELLOC" -a -d ${TOPDIR}/releases/`basename $RELLOC` ] && RELLOC=${TOPDIR}/releases/`basename $RELLOC`
if [ "$ACTION" == "install" -o "$ACTION" == "validate" ] ; then
    prepareInstallDirs
    let rc=$rc+$?
    if [ $rc -ne 0 ] ; then
        msgOut ERROR "Cannot create the installation directories. The installer will now exit."
        [ "$XMLFILE" != "" ] && xml close
        exit $rc
    fi
fi

# Save the environment
export ENVSTART="/tmp/sw-mgr-envstart.tmp.$$"
msgOut INFO "Saving the installation environment in $ENVSTART"
/usr/bin/env | grep '=' | cut -d'=' -f 1 | egrep -v '^_$|^\s|^	|^$' | while read var; do echo "$var='`/usr/bin/printenv $var`'"; done > $ENVSTART
[ "$LD_LIBRARY_PATH" == "" ] && echo "unset LD_LIBRARY_PATH" >> $ENVSTART
[ "$PYTHONPATH" == "" ] && echo "unset PYTHONPATH" >> $ENVSTART

# Perform the pre-setup, if required
if [ "$RELSETPATH" != "" -o "$PRESETUP" != "" ] ; then
    [ "$RELSETPATH" != "" ] && RSP="$RELSETPATH"
    [ "$PRESETUP"   != "" ] && RSP="$PRESETUP"
    msgOut INFO "Searching for ATLAS sw releases in ${RSP} - this may time some time..."
    RELLIST=(`find $RSP -maxdepth 5 -path "*/AtlasCore/*/InstallArea/*slc*gcc*" 2>/dev/null | sort`)
    MAXREL=$((${#RELLIST[@]}-1))
    msgOut INFO "${#RELLIST[@]} releases found in $RSP"
    declare RELSETUP
    for r in `seq 0 $MAXREL`; do
        RELDATA=(`echo ${RELLIST[$r]} | sed 's#\(.*\)/AtlasCore/\([0-9\.]*\)/InstallArea/\([^-]*\)-\(slc[0-9]\)-\(gcc[0-9]*\)-.*#\1 \2 \3 \4 \5#'`)
        RELSETUPLIST[$r]="source ${RELDATA[0]}/cmtsite/setup.sh -tag=AtlasOffline,${RELDATA[1]},runtime,${RELDATA[3]},${RELDATA[4]}"
        [ "${RELDATA[2]}" == "i686" ] && RELSETUPLIST[$r]="${RELSETUPLIST[$r]},32" || RELSETUPLIST[$r]="${RELSETUPLIST[$r]},64"
    done
    RELSETUP=${RELSETUPLIST[$MAXREL]}
    if [ "$PRESETUP" != "" ] ; then
        if [ -s "$RELSETUP" ] ; then
            msgOut INFO "Setting up the latest release with $RELSETUP"
            msgOut INFO "${RELSETUP}"
            eval ${RELSETUP}
        else
            msgOut WARNING "Cannot setup a suitable release from $RSP"
        fi
    fi
fi

# Execute the actions
if [ "$ACTION" == "install" -o "$ACTION" == "validate" ] ; then
    if [ "$REINSTALL" == "yes" ] ; then
        RELLOCBASE="$RELLOC"
        RELLOCINDX="`\ls -d ${RELLOC}.r* 2> /dev/null | wc -l`"
        let RELLOCINDX=$RELLOCINDX+1
        RELLOC="${RELLOC}.r${RELLOCINDX}"
        msgOut INFO "Re-installation requested. Installing in $RELLOC."
    elif [ "$REINSTALLCLEAN" == "yes" ] ; then
            msgOut INFO "Re-installation cleanup requested. Removing the old stuff."
            remove
    fi
    if [ "$REINSTALL" == "yes" -o "$REINSTALLCLEAN" == "yes" ] ; then
        prepareInstallDirs
        let rc=$rc+$?
        if [ $rc -ne 0 ] ; then
            msgOut ERROR "Cannot create the installation directories. The installer will now exit."
            [ "$XMLFILE" != "" ] && xml close
            exit $rc
        fi
    else
        msgOut INFO "Starting the normal installation phase."
    fi

    # Check the site parameters for the installation
    checkSite
    let rc=$rc+$?

    # Install only if everything is OK
    if [ $rc -eq 0 ] ; then
        install
        let rc=$rc+$?
        if [ "$ACTION" == "validate" ] ; then
            if [ $rc -eq 0 ] ; then
                validate
                let rc=$rc+$?
            else
                msgOut INFO "Skipping validation due to previous errors"
            fi
        fi
        if [ $rc -eq 0 -o "$FORCETAGS" == "yes" ] ; then
            if [ "$TAGACTION" == "add" ] ; then
                addTag
                let tagrc=$?
                [ $tagrc -ne 0 ] && msgOut ERROR "Cannot add tags"
                let rc=$rc+$tagrc
            fi
        fi
    fi
elif [ "$ACTION" == "test" ] ; then
    validate
    let rc=$rc+$?
    if [ "$NOTAG" != "yes" ] ; then
        if [ $rc -eq 0 ] ; then
            addTag
        else
            if [ "$TAGHOST" != "" ] ; then
                SWAREAINFO="`getSWarea`"
                SHARED_INSTALL="`wget -qO - --post-data="swarea=${SWAREAINFO}&rel=${RELEASE}&status=installed" ${POSTRELURL}`"
                if [ $? -eq 0 ] ; then
                    SHARED_INSTALL="`echo $SHARED_INSTALL | awk '{print $1}' | sed "s#${RELEASE}#yes#g"`"
                    if [ "$SHARED_INSTALL" == "yes" ] ; then
                        msgOut WARNING "Will not remove the tag from the dump file because this sw area (${SWAREAINFO}) is shared with other installed nodes"
                        unset DUMPTAGS
                    else
                        msgOut INFO "No other nodes are sharing this installation (${SWAREAINFO}), will remove the tag from the dump file"
                    fi
                else
                    msgOut WARNING "Cannot contact the LJSFi release info service. Will not remove the tag from the dump file"
                    unset DUMPTAGS
                fi
                removeTag
            else
                msgOut WARNING "No host to tag"
            fi
        fi
        let tagrc=$?
        [ $tagrc -ne 0 ] && msgOut ERROR "Cannot manage tags"
        let rc=$rc+$tagrc
    fi
elif [ "$ACTION" == "remove" ] ; then
    if [ "$TAGACTION" == "remove" ] ; then
        removeTag
        let tagrc=$?
        [ $tagrc -ne 0 ] && msgOut ERROR "Cannot remove tags"
        let rc=$rc+$tagrc
    fi
    if [ $rc -eq 0 ] ; then
        remove
        let rc=$rc+$?
    else
        msgOut ERROR "Skipping software removal due to previous problems."
    fi
elif [ "$ACTION" == "manage" ] ; then
    if [ "$TAGACTION" == "add" ] ; then
        addTag
    elif [ "$TAGACTION" == "remove" ] ; then
        removeTag
    fi
    let tagrc=$?
    [ $tagrc -ne 0 ] && msgOut ERROR "Cannot manage tags"
    let rc=$rc+$tagrc
elif [ "$ACTION" == "check" ] ; then
    checkSite
    let rc=$rc+$?
elif [ "$ACTION" == "remove-snap" ] ; then
    rm -f $SNAPDIR/${SNAPNAME}
    let rc=$rc+$?
elif [ "$ACTION" == "snap" ] ; then
    if [ "$USEPACBALL" != "yes" ] ; then
        snap "$SNAPDIR" "${SNAPNAME}"
    else
        pacball "$SNAPDIR" "${SNAPNAME}"
    fi
    let rc=$rc+$?
elif [ "$ACTION" == "query" ] ; then
    query
    let rc=$rc+$?
elif [ "$ACTION" == "cleanup" ] ; then
    cleanup
    let rc=$rc+$?
    if [ $rc -eq 0 ] ; then
        if [ "$TAGACTION" == "add" ] ; then
            addTag
        elif [ "$TAGACTION" == "remove" ] ; then
            removeTag
        fi
        let tagrc=$?
        [ $tagrc -ne 0 ] && msgOut ERROR "Cannot manage tags"
        let rc=$rc+$tagrc
    fi
elif [ "$ACTION" == "mkiso" ] ; then
    mkiso "atlas-kit-DVD-`date +%Y%m%d`.iso" "Atlas_`query -quiet`" "${USER}" "${TOPDIR}/sw-mgr ${PACMAN_DIR} ${TOPDIR}/patches ${SNAPDIR}"
    let rc=$rc+$?
elif [ "$ACTION" == "writeiso" ] ; then
    writeDVD "${ISOIMAGE}"
    let rc=$rc+$?
fi

# Clean up other files
if [ -f $ENVSTART ] ; then
    msgOut INFO  "Removing temporary environment file $ENVSTART"
    rm -fr $ENVSTART
fi

# Exit the installer
if [ $rc -eq 0 ] ; then
    msgOut INFO  "Processing OK"
else
    msgOut ERROR "Processing FAILED"
fi

# Close the xml file
[ "$XMLFILE" != "" ] && xml close

# Exit with the appropriate return code
exit $rc
