#! /bin/sh

## "@(#) $Id: macOSX.installMIDAS 4665 2024-03-28 14:39:30Z smpd $"

## The latest version of script is available from:
## http://www.hq.eso.org/~jpritcha/MIDASonMacOSX.html
##
##  Copyright (C) 2007  J.D.Pritchard
##
##  This program is free software; you can redistribute it and/or modify
##  it under the terms of the GNU General Public License as published by
##  the Free Software Foundation; either version 2 of the License, or
##  (at your option) any later version.
##
##  This program is distributed in the hope that it will be useful,
##  but WITHOUT ANY WARRANTY; without even the implied warranty of
##  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##  GNU General Public License for more details.
##
##  You should have received a copy of the GNU General Public License
##  along with this program; if not, write to the Free Software
##  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
##
## ChangeLog
## 2024-03-28: [WIP] Implementing support for 23FEBpl1.0+gcc-mp-13
## 2017-03-21: Implemented support for 17FEBpl1.1+gcc-mp-5
## 2015-09-15: Full support for 15SEPpl1.0 for Mac OS X Yosemite implemented, Default is now 15SEPpl1.0, compiler gcc-mp-4.9
## 2014-04-11: Full support for 13SEPpl1.2 for Mac OS X Mavericks implemented, Default is now 13SEPpl1.2, compiler gcc-mp-4.8
## 2012-05-09: Full support for 12FEBpl1.2 for Mac OS X Snow Leopard implemented, Default is now 12FEBpl1.2
## 2011-08-03: Full support for 11FEBpl1.3 for Mac OS X Snow Leopard implemented, Default is now 11FEBpl1.3
## 2010-10-09: Full support for 10SEPpl1.1 for Mac OS X Leopard implemented, Default is now 10SEPpl1.1
## 2010-09-16: Full support for 10SEPpl1.0 for Mac OS X Ephemerides FilesLeopard implemented, Default is now 10SEPpl1.0
## 2010-03-30: Full support for 10FEBpl1.0 for Mac OS X Leopard implemented, Default is now 10FEBpl1.0
## 2009-06-30: Full support for 09FEBpl1.0 for Mac OS X Leopard implemented, Default is now 09FEBpl1.0
## 2008-01-11: Full support for 07SEPpl1.1 for Mac OS X Tiger and Leopard implemented, Default is now 07SEPpl1.1
## 2007-11-27: Full support for 07FEBpl1.1 for Mac OS X implemented
## 2007-04-17: Implemented support for Linux ( -V 07FEBpl1.1 --gcc Linux.gcc-g77 ),
##             Full support for 07FEBpl1.1 still pending
## 2007-03-01: Updated to MIDAS Version 06SEPpl1.3
## 2007-02-01: Updated to MIDAS Version 06SEPpl1.2
## 2006-11-30: Updated to MIDAS Version 06SEPpl1.1

################################################################################
## Definition of functions
usage() {
  printf "\
Usage: ${execName} [-h|dvnq] [--demo] [--calib] [--verify|--superVerify]
                   [-M <MIDASHOME>]   [-V <MIDVERS>] [-S <SRCDIR>]
		   [--noGUIs] [--manualSelection]
                   [--prefix <dirspec>] [--bindir <dirspec>] [--mandir <dirspec>]
                   [--gcc <gcc-spec>]
                   [--sudo]
		   [-bf|-be|-bp|-bc|-bb|-bs|-bv]


  -h: help
  -d: debug
  -n: dry-run
  -q: quiet
     -q Only Warnings and Errors are written out (to stderr)
     -q -q increases quietness, only Errors are written out (to stderr)
     -q -q -q increases quietness, NO output to stdout or stderr
  -v: verbose
  --demo:  demo
  --calib: calib
  --verify: verify (i.e. run @@ veriall)
  --superVerify: run @ superverify if demo/data exists, else run @@ verify
                 provided calib dir exists
  --sudo: use sudo if necessary
  -bf|-be|-bp|-bc|-bb|-bs|-bv: Build steps
    By default script will:
      *) -bf: fetch source files (if do not already exist in <SRCDIR>)
      *) -be: extract the source files
      *) -bp: prep the source (i.e. apply patches)
      *) -bc: choose (select) the packages
      *) -bb: build the installation
      *) -bs: setup the installation
      *) -bv: verify the installation
    Individual steps can be executed by specifying the relevant option.
    Several options can be specified at the same time in order to execute
    several steps at once. Order is not important.
================================================================================
  -M <MIDASHOME>
     default = /midas, but will use the value of the environment variable MIDASHOME
     if it is set
  -V <MIDVERS>
     default = ${defVer}, but will use the value of the environment variable MIDVERS
     if it is set
  --noGUIs
     Do not compile GUIs, avoids the dependance on a motif library.
  --manualSelection
     Manual selection of which MIDAS packages you want. This allows you for example
     to NOT select the GUIs and thus avoid the dependance on a motif library.
  --deSelPack <package name>
  -S <SRCDIR>
     default = \$MIDASHOME/tmp
  --gcc <gcc-dp-4.2|gcc-mp-4.2|gcc-mp-4.3|gcc-mp-4.5|gcc-mp-4.6|gcc-mp-4.7|gcc-mp-4.8|gcc-mp-4.9|gcc-mp-5|gcc-mp-13|gcc+gfortran|Linux.gcc-g77>
      default = ${default_GCC}
  --prefix <dirspec>
     default /usr/local, Note: /usr/local normally requires root user privelige to
     write there.
  --bindir <dirspec>
     default = <prefix>/bin
  --mandir <dirspec>
     default = <prefix>/man/manl
  --ftpURL <host/rootpath>: to be prefixed by ftp://.
     Default is ftp.eso.org/pub/midaspub
  --x86_64: force x86_64, should be auto-detected (via uname -m == 'x86_64')
"
  exit ${exstat:-0}
}

SED="sed"
which gsed > /dev/null 2>&1 && SED="gsed"
which ssed > /dev/null 2>&1 && SED="ssed"

verboseLog() {
  [ ! -z "${vbose}" ] && echo "${execName}::info:: $1" > ${2:-/dev/stdout}
}

debugLog() {
  [ ! -z "${debug}" ] && echo "${execName}::debug:: $1" > ${2:-/dev/stdout}
}

notQuietLog() {
  [ -z "${quiet}" ] && echo "${execName}::info:: $1" > ${2:-/dev/stdout}
}

errorLog() {
  [ ${quietLevel:-0} -lt 3 ] && echo "${execName}::Error:: $1" > ${2:-/dev/stderr}
}

warningLog() {
  [ ${quietLevel:-0} -lt 2 ] && echo "${execName}::Warning:: $1" > ${2:-/dev/stderr}
}

execCmd() {
  [ ! -z "${debug}" ] || [ ! -z ${dryRun} ] && echo "${execName}::execCmd:: $1"
  [ -z "${dryRun}"  ] && eval ${1}
}

################################################################################
## Usage:
## checkVarIsSet <VAR-NAME> <level> [error-message] [exit-status]
##      <VAR-NAME>: name of variable to check for, no '$'
##         <level>: fatal|fatalNoExit|warn
## <error-message>: Error/Warning message to print
##   [exit-status]: Optional exit status value
##
  checkVarIsSet(){
  v1="$`echo $1`"
  v2="`eval echo $v1`"
  if [ -z "${v2}" ]; then
    debugLog "Variable $1 is not set"
    case $2 in
      fatal)       errorLog   "${3:-Variable $1 not set}"; exstat=${4:-1} ; usage ;;
      fatalNoExit) errorLog   "${3:-Variable $1 not set}"; (( exstat=${exstat-0}+${4:-1} ));;
      warn)        warningLog "${3:-Variable $1 not set}";;
      *)           errorLog   "*** Coding error:: error-level not recognised"; exit 1
    esac
  else
    debugLog "Variable $1 is set to $v2"
  fi
}

## checkFileExists <file> <level> [error-message] [exit-status] [Y/N]
## Y/N ==> Yes --> file should exist even if running in dryRun Mode
##         No --> file need not exist in dryRun Mode
## default is Y
checkFileExists(){
  err=0
  [ ! -e "${1}" ] && err=1
  [ "${5}" == "N" ] && [ ! -z "${dryRun}" ] && err=0
  if [ $err -ne 0 ]; then
    debugLog "Can't find ${1}"
    case $2 in
      fatal)       errorLog   "${3:-File $1 not found}"; exstat=${4:-1} ; exit $exstat ;;
      fatalNoExit) errorLog   "${3:-File $1 not found}"; (( exstat=${exstat-0}+${4:-1} ));;
      warn)        warningLog "${3:-File $1 not found}";;
      *)           errorLog   "*** Coding error:: error-level not recognised"; exit 1
    esac
  else
    debugLog "Found ${1}"
  fi
}

## Check for required files...
checkForRequiredFiles() {
  checkFileExists ${SRCDIR}/${MIDVERS}.tar.gz \
    fatalNoExit \
    "File not found: ${SRCDIR}/${MIDVERS}.tar.gz" \
    1 N
  if [ ! -e /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/netat/sysglue.h ]; then \
    checkFileExists ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9 \
      fatalNoExit \
      "File not found ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9" \
      2 N
  fi
  case "${MIDVERS}" in
  06SEPpl1.0|06SEPpl1.1|06SEPpl1.2|06SEPpl1.3|07FEBpl1.1|07SEPpl1.1|08SEPpl1.0|09FEBpl1.0|10FEBpl1.0|10SEPpl1.0|10SEPpl1.1|11FEBpl1.3|12FEBpl1.2|13SEPpl1.2|15FEBpl0.2|15FEBpl1.0)
    checkFileExists ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer} \
      fatalNoExit \
      "File not found: ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer}" \
      4 N
    ;;
  esac
  if [ ! -z "${GCCok}" ]; then
    checkFileExists ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch} \
      fatalNoExit \
      "File not found: ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch}" \
      8 N
  else
    notQuietLog "::(warning) GCC value not recognised."
  fi
}
################################################################################
mkdirWithSudoIN() {
  if [ ! -d "${1}" ]; then
    pdir="`dirname ${1}`"
    while [ ! -d "${pdir}" ]; do
      pdir="`dirname ${pdir}`"
    done
    debugLog "Parent Directory is ${pdir}"
    [ ! -z "${sudo}" ] && unset sudo
    if [ ! -w $pdir ]; then
      if [ ! -z "${useSuDo}" ]; then
        sudo="sudo "
      else
        errorLog "Directory $pdir is not writable by $USER, try with --sudo option"
	exit 1
      fi
    fi
    execCmd "${sudo}mkdir -p ${vbose} ${1}"
  else
    debugLog "Directory ${1} exists, nothing to do."
  fi
}

useSudoIN() {
  pdir="`dirname ${1}`"
  [ ! -z "${sudo}" ] && unset sudo
  if [ ! -w $pdir ]; then
    if [ ! -z "${useSuDo}" ]; then
      sudo="sudo "
    else
      errorLog "Directory $pdir is not writable by $USER, try with --sudo command line option."
      exit 1
    fi
  fi
}

################################################################################
## fetch
## Check for existance of SRCDIR, create if necessary...

fetch() {
debugLog "################################################################################"
debugLog "function fetch()"

mkdirWithSudoIN ${SRCDIR}
useSudoIN ${SRCDIR}/dummy
if [ ! -z "${sudo}" ]; then
  execCmd "${sudo}chown ${USER}${GROUP:+:${GROUP}} ${SRCDIR}"
fi
## The MIDAS source code...
if [ ! -e ${SRCDIR}/${MIDVERS}.tar.gz ]; then
  verboseLog "Fetching ftp://${FTPURL}/${MIDVERS:0:5}/sources/${MIDVERS}.tar.gz"
  execCmd "wget -O ${SRCDIR}/${MIDVERS}.tar.gz ftp://${FTPURL}/${MIDVERS:0:5}/sources/${MIDVERS}.tar.gz"
  checkFileExists ${SRCDIR}/${MIDVERS}.tar.gz \
    fatal \
    "Can't wget ftp://${FTPURL}/${MIDVERS:0:5}/sources/${MIDVERS}.tar.gz" \
    1 N
fi
## sysglue.h
if [ ! -e /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/netat/sysglue.h ] && [ ! -e ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9 ]; then
  execCmd "wget -O ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9 http://www.hq.eso.org/~jpritcha/midas/sysglue.h.Developer.SDKs.MacOSX10.3.9"
  checkFileExists ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9 \
    fatal \
    "Can't wget http://www.hq.eso.org/~jpritcha/midas/sysglue.h.Developer.SDKs.MacOSX10.3.9" \
    2 N
fi
## Patch files...
case "${MIDVERS}" in
  06SEPpl1.0|06SEPpl1.1|06SEPpl1.2|06SEPpl1.3|07FEBpl1.1|07SEPpl1.1|08SEPpl1.0|09FEBpl1.0|10FEBpl1.0|10SEPpl1.0|10SEPpl1.1|11FEBpl1.3|12FEBpl1.2|13SEPpl1.2|15FEBpl0.2|15FEBpl1.0)
  if [ ! -e ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer} ]; then
    execCmd "wget -O ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer} http://www.hq.eso.org/~jpritcha/midas/patch.${MIDVERS}.macOSX-${MacOSXMajVer}"
    checkFileExists ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer} \
      fatal \
      "Can't wget http://www.hq.eso.org/~jpritcha/midas/patch.${MIDVERS}.macOSX-${MacOSXMajVer}" \
      4 N
  fi
  ;;
esac
if [ ! -z "${GCCok}" ]; then
  if [ ! -e ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch} ]; then
    execCmd "wget -O ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch} http://www.hq.eso.org/~jpritcha/midas/patch.${MIDVERS}.${GCC}${_arch}"
    checkFileExists ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch} \
      fatal \
      "Can't wget http://www.hq.eso.org/~jpritcha/midas/patch.${MIDVERS}.${GCC}${_arch}" \
      8 N
  fi
else
  warningLog "GCC value not recognised."
fi
## Optional downloads:
## The installation instructions...
if [ $haveWGET -eq 1 ]; then
  if [ ! -e ${SRCDIR}/installunix.ps.gz ]; then
    verboseLog "Fetching ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.ps.gz"
    execCmd "wget -O ${SRCDIR}/installunix.ps.gz ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.ps.gz"
    checkFileExists ${SRCDIR}/installunix.ps.gz \
      warn \
      "Can't wget ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.ps.gz" \
      1 N
  fi
  if [ ! -e ${SRCDIR}/installunix.pdf ]; then
    verboseLog "Fetching ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.pdf"
    execCmd "wget -O ${SRCDIR}/installunix.pdf ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.pdf"
    checkFileExists ${SRCDIR}/installunix.pdf \
      warn \
      "Can't wget ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.pdf" \
      1 N
  fi
  if [ ! -e ${SRCDIR}/demo_data.tar.gz ] && [ ! -z "${demo}" ]; then
  verboseLog "Fetching ftp://${FTPURL}/${MIDVERS:0:5}/sources/demo_data.tar.gz"
  execCmd "wget -O ${SRCDIR}/demo_data.tar.gz ftp://${FTPURL}/${MIDVERS:0:5}/sources/demo_data.tar.gz"
  checkFileExists ${SRCDIR}/demo_data.tar.gz \
    warn \
    "Can't wget ftp://${FTPURL}/${MIDVERS:0:5}/sources/demo_data.tar.gz" \
    1 N
  fi
  if [ ! -e ${SRCDIR}/calib_src.tar.gz ] && [ ! -z "${calib}" ]; then
  verboseLog "Fetching ftp://${FTPURL}/${MIDVERS:0:5}/sources/calib_src.tar.gz"
  execCmd "wget -O ${SRCDIR}/calib_src.tar.gz ftp://${FTPURL}/${MIDVERS:0:5}/sources/calib_src.tar.gz"
  checkFileExists ${SRCDIR}/calib_src.tar.gz \
    warn \
    "Can't wget ftp://${FTPURL}/${MIDVERS:0:5}/sources/calib_src.tar.gz" \
    1 N
  fi
fi

}
################################################################################
## extract
## Create directory structure...

extract() {
debugLog "################################################################################"
debugLog "function extract()"

mkdirWithSudoIN ${MIDASHOME}
useSudoIN ${MIDASHOME}/dummy
if [ ! -z "${sudo}" ]; then
  execCmd "${sudo}chown ${USER}:${GROUP} ${MIDASHOME}"
fi
execCmd "cd ${MIDASHOME}"
notQuietLog "Extracting ${SRCDIR}/${MIDVERS}.tar.gz"
execCmd "tar ${vbose} -zxf ${SRCDIR}/${MIDVERS}.tar.gz"
[ ! -d ${MIDASHOME}/${MIDVERS}/incl/netat ] && mkdirWithSudoIN ${MIDASHOME}/${MIDVERS}/incl/netat

if [ ! -d demo ] && [ -e ${SRCDIR}/demo_data.tar.gz ] && [ ! -z "${demo}" ]; then
  mkdirWithSudoIN demo
  execCmd "cd demo"
  execCmd "tar ${vbose} -xzf ${SRCDIR}/demo_data.tar.gz"
  cd ..
  [ ! -z ${debug} ] && execCmd "du -sh demo"
fi
if [ ! -d calib ] && [ -e ${SRCDIR}/calib_src.tar.gz ] && [ ! -z "${calib}" ]; then
  execCmd "tar ${vbose} -xzf ${SRCDIR}/calib_src.tar.gz"
  buildCalDB="Y"
  [ ! -z ${debug} ] && execCmd "du -sh calib"
fi

}

################################################################################
## prep

prep() {
debugLog "################################################################################"
debugLog "function prep()"

## sysglue.h
case "${MacOSXMajVer}" in 10.4|10.5|10.6|10.7)
  case "${GCC}" in gcc-dp-4.2|gcc-mp-4.2|gcc-mp-4.3|gcc-mp-4.5|gcc-mp-4.6|gcc-mp-4.7|gcc-mp-4.8)
    if [ ! -e ${MIDASHOME}/${MIDVERS}/incl/netat/sysglue.h ]; then
      if [ -e /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/netat/sysglue.h ]; then
        execCmd "ln -s ${vbose} /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/netat/sysglue.h ${MIDASHOME}/${MIDVERS}/incl/netat"
      else
        execCmd "cp ${vbose} ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9 ${MIDASHOME}/${MIDVERS}/incl/netat/sysglue.h"
      fi
    fi
    ;;
  esac
  ;;
esac
## mtio.h
case "${MacOSXMajVer}" in 10.6.1)
  [ ! -d ${MIDASHOME}/${MIDVERS}/incl/sys ] && execCmd "mkdir ${vbose:--}p ${MIDASHOME}/${MIDVERS}/incl/sys"
  if [ ! -e ${MIDASHOME}/${MIDVERS}/incl/sys/mtio.h ]; then
    if [ -e /Developer/SDKs/MacOSX10.5.sdk/usr/include/sys/mtio.h ]; then
      execCmd "ln -s ${vbose} /Developer/SDKs/MacOSX10.5.sdk/usr/include/sys/mtio.h ${MIDASHOME}/${MIDVERS}/incl/sys/mtio.h"
    else
      errorLog "Can't find /Developer/SDKs/MacOSX10.5.sdk/usr/include/sys/mtio.h, insure XCode is installed."
      exit 1
    fi
  fi
  ;;
esac
##
## Patch files...
#
### Generic Patch
[ -e ${SRCDIR}/patch.${MIDVERS}.gen ] && execCmd "patch -p0 < ${SRCDIR}/patch.${MIDVERS}.gen"
### Version specific patch
case "${MIDVERS}" in 06SEPpl1.0|06SEPpl1.1|06SEPpl1.2|06SEPpl1.3|07FEBpl1.1|07SEPpl1.1|08SEPpl1.0|09FEBpl1.0|10FEBpl1.0|10SEPpl1.0|10SEPpl1.1|11FEBpl1.3|12FEBpl1.2|13SEPpl1.2|15FEBpl0.2|15FEBpl1.0)
  notQuietLog "Applying patch ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer}"
  execCmd "patch -p0 < ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer}"
 ;;
esac
### Compiler patch...
if [ ! -z "${GCCok}" ]; then
  notQuietLog "Applying patch ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch}"
  execCmd "patch -p0 < ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch}"
else
  warningLog "GCC value not recognised."
fi

}

################################################################################
## Select Packages

selectPacks() {
  debugLog "################################################################################"
  debugLog "function selectPacks()"

  if [ -z "${dryRun}" ]; then
    if [ ! -z "${manualSelection}" ]; then
      ${MIDASHOME}/${MIDVERS}/install/unix/config
    else
      ${MIDASHOME}/${MIDVERS}/install/unix/config <<EOF
3

q
EOF
      if [ ! -z "${noGUIs}" ]; then
        notQuietLog "Deselecting GUIs..."
        for pack in `ls ${MIDASHOME}/${MIDVERS}/gui | egrep -v 'incl|lib|exec|proc|help|resource|Xstuff'`; do
          if [ -e ${MIDASHOME}/${MIDVERS}/gui/$pack/SELECTED ]; then
            execCmd "rm -f ${MIDASHOME}/${MIDVERS}/gui/$pack/SELECTED"
            notQuietLog "Deselected $pack"
          fi
          if [ -f ${MIDASHOME}/${MIDVERS}/gui/$pack/DEPENDENCIES ]; then
            for depend in `cat ${MIDASHOME}/${MIDVERS}/gui/$pack/DEPENDENCIES` ; do
              [ -e ${MIDASHOME}/${MIDVERS}/gui/$depend/SELECTED_BY_$pack ] && \
                execCmd "rm -f ${MIDASHOME}/${MIDVERS}/gui/$depend/SELECTED_BY_$pack"
                notQuietLog "Deselected $pack dependency $depend"
            done
          fi
        done
      fi
      [[ "${MIDVERS}" == "07FEBpl1.1" ]] && [[ "${GCC/gfortran}" != "${GCC}" ]] && deSelPacks="${deSelPacks:+${deSelPacks} }daophot"
#      [[ "${MacOSXMajVer}" == "10.9" ]] && deSelPacks="${deSelPacks:+${deSelPacks} }irspec"
      for pack in ${deSelPacks} ; do
        notQuietLog "Deselecting ${pack}..."
        if [ -e ${MIDASHOME}/${MIDVERS}/contrib/$pack/SELECTED ]; then
          execCmd "rm -f ${MIDASHOME}/${MIDVERS}/contrib/$pack/SELECTED"
          notQuietLog "Deselected $pack"
        fi
        if [ -f ${MIDASHOME}/${MIDVERS}/contrib/$pack/DEPENDENCIES ]; then
          for depend in `cat ${MIDASHOME}/${MIDVERS}/contrib/$pack/DEPENDENCIES` ; do
            [ -e ${MIDASHOME}/${MIDVERS}/contrib/$depend/SELECTED_BY_$pack ] && \
              execCmd "rm -f ${MIDASHOME}/${MIDVERS}/contrib/$depend/SELECTED_BY_$pack"
              notQuietLog "Deselected $pack dependency $depend"
          done
        fi
        execCmd "${SED} -i /${pack}/I,/reset\\\\/display/I's/^.*/\\!&/' ${MIDASHOME}/${MIDVERS}/{prim/proc/{superverify.prg,tutoall.prg},test/prim/all_{,i}tutos.prg}"
      done
    fi
  else
    notQuietLog "Select all MIDAS packages"
  fi

}

################################################################################
## Build

build() {
debugLog "################################################################################"
debugLog "function build()"
debugLog ${MacOSXMajVer}
[ ! -z "${debug}" ] && read -p "<Enter>" dummy
case "${MacOSXMajVer}" in 10.4|10.5|10.6|10.7)
  case "${GCC}" in gcc-dp-4.2|gcc-mp-4.2|gcc-mp-4.3|gcc-mp-4.5|gcc-mp-4.6|gcc-mp-4.7|gcc-mp-4.8)
    [ ! -x $(pwd)/gfortran ] && createGFORTRAN=true
    if ${createGFORTRAN:-false} ; then
      if [ -x $(which ${GCC/gcc/gfortran}) ]; then
        verboseLog "Linking ${GCC/gcc/gfortran} to $(pwd)/gfortran"
        execCmd "ln -fs${vbose:+v} $(which ${GCC/gcc/gfortran}) gfortran"
        sPATH="${PATH}"
        execCmd "export PATH=$(pwd):${PATH}"
        [ ! -z "${debug}" ] && read -p "<Enter> " dummy
      else
        errorLog "${GCC/gcc/gfortran} NOT found in PATH"
        exit 1
      fi
    fi
    ;;
  esac
  ;;
esac
[ ! -z "${debug}" ] && read -p "<Enter> " dummy
if [ -z "${dryRun}" ]; then
  ${MIDASHOME}/${MIDVERS}/install/unix/config <<EOF
5




6






q
EOF
  echo " "
  echo "Waiting 5 seconds..."
  sleep 5
  logfile=`ls -tr1 $MIDASHOME/$MIDVERS/tmp/install.* | tail -n 1`
  xterm -T "MIDAS compile log window" -e tail -f $logfile &
  PID=`basename $logfile | cut -d. -f2`
  echo " "
  echo "================================================================================"
  echo "Waiting for MIDAS to finish compiling..."
  pscom="ps"
  [ "`uname`" == "Linux" ] && pscom="ps x"
  while [ ! -z "`${pscom} | grep \"${MIDASHOME}/${MIDVERS}/install/unix/install\" | grep -v grep`" ]; do
    sleep 10
  done
  if ${createGFORTRAN:-false} && [ -e gfortran ]; then
    execCmd "rm -f${vbose:+v} gfortran"
    execCmd "export PATH=${sPATH}"
  fi
  if egrep "Error:"\|"^make: \[.*\] Error " $logfile > /dev/null 2>&1 ; then
    echo "***Error: There were errors in the compiling."
    echo "See $logfile, check for 'Error'."
    exit 1
  fi
else
  notQuietLog "Pre-Install MIDAS"
  notQuietLog "Install MIDAS"
fi

}

################################################################################
## setup

setup() {
debugLog "################################################################################"
debugLog "function setup()"

if [ -z "${dryRun}" ]; then
  ${MIDASHOME}/${MIDVERS}/install/unix/config <<EOF
8







q
EOF
else
  notQuietLog "Setup MIDAS"
fi

mkdirWithSudoIN ${MIDASBINDIR}
if [ ! -d ${MIDASBINDIR} ] && [ -z "${dryRun}" ]; then
  warningLog "Could NOT create directory ${MIDASBINDIR}"
else
  for file in inmidas gomidas helpmidas drs ; do
    useSudoIN ${MIDASBINDIR}/$file
    execCmd "${sudo}ln ${vbose} -fs ${MIDASHOME}/${MIDVERS}/system/unix/$file ${MIDASBINDIR}/$file"
    [ ! -e ${MIDASBINDIR}/$file ] && [ -z "${dryRun}" ] && warningLog "::(warning) Could NOT create ${MIDASBINDIR}/$file"
  done
fi
mkdirWithSudoIN ${MIDASMANDIR}
if [ ! -d ${MIDASMANDIR} ] && [ -z "${dryRun}" ]; then
  warningLog "Could NOT create directory ${MIDASMANDIR}"
else
  for file in inmidas.l gomidas.l helpmidas.l ; do
    useSudoIN ${MIDASMANDIR}/$file
    execCmd "${sudo}ln ${vbose} -fs ${MIDASHOME}/${MIDVERS}/system/unix/manl/$file ${MIDASMANDIR}/$file"
    [ ! -e ${MIDASMANDIR}/$file ] && [ -z "${dryRun}" ] && warningLog "Could NOT create ${MIDASMANDIR}/$file"
  done
fi
execCmd "cd ${MIDASHOME}/${MIDVERS}/tmp"
if [ -z "${dryRun}" ]; then
  ${MIDASBINDIR}/inmidas -m ${MIDASHOME}/${MIDVERS}/tmp/midwork <<EOF
@ compile.all
EOF
  ${MIDASBINDIR}/gomidas -m ${MIDASHOME}/${MIDVERS}/tmp/midwork <<EOF
@ ascii_bin
bye
EOF
  if [ ! -z "${buildCalDB}" ]; then
    execCmd "cd ${MIDASHOME}/calib/install"
    execCmd ". dbassign.sh"
    ${MIDASBINDIR}/inmidas -m ${MIDASHOME}/${MIDVERS}/tmp/midwork <<EOF
@@ caldb
@@ filters
EOF
    execCmd "cd .."
    execCmd "rm -fr ${vbose} install"
  fi
else
  notQuietLog "Execute @ compile.all in MIDAS"
  notQuietLog "Execute @ ascii_bin in MIDAS"
  if [ ! -z "${buildCalDB}" ]; then
    notQuietLog "Do cd ${MIDASHOME}/calib/install"
    notQuietLog "Do . dbassign.sh"
    notQuietLog "Execute @@ caldb in MIDAS"
    notQuietLog "Execute @@ filters in MIDAS"
    notQuietLog "Do cd .."
    notQuietLog "Do rm -fr ${vbose} install"
  fi
fi
execCmd "cd ${MIDASHOME}"

}

################################################################################
## verify

verify() {
debugLog "################################################################################"
debugLog "function verify()"

execCmd "cd ${MIDASHOME}"
[ ! -z ${debug} ] && execCmd "du -sh ${MIDVERS}"
if [ ! -z "${verify}" ]; then
  VorSV="@@ veriall"
  verifyDir="${MIDASHOME}/${MIDVERS}/tmp/verify"
  if [ ! -z "${superVerify}" ]; then
    if [ -d demo/data ] || ( [ ! -z "${dryRun}" ] && [ ! -z "${demo}" ] ) ; then
      [ -d demo/data ] && debugLog "Found `pwd`/demo/data."
      VorSV="@ superverify"
      verifyDir="${MIDASHOME}/${MIDVERS}/tmp/superverify"
    else
      [ ! -d demo/data ] && debugLog "Can't find `pwd`/demo/data."
    fi
  fi
  debugLog "VorSV = ${VorSV}"
  mkdirWithSudoIN ${verifyDir}
  execCmd "cd ${verifyDir}"
  if [ -z "${dryRun}" ]; then
    gomidas -m ${MIDASHOME}/${MIDVERS}/tmp/midwork <<EOF
@ vericopy
write/out "${VorSV}"
${VorSV}
bye
EOF
  else
    notQuietLog "Execute @ vericopy in MIDAS"
    notQuietLog "Execute ${VorSV} in MIDAS"
  fi
  execCmd "cd ${MIDASHOME}"
fi
[ ! -z ${debug} ] && execCmd "du -shc ${MIDVERS} ${MIDVERS}/tmp demo calib"
[ ! -z ${debug} ] && execCmd "du -shc ${SRCDIR}/*"

}

setStep() {
  if [ -z "${indSteps}" ]; then
    noFetch=1
    noExtract=1
    noPrep=1
    noSelect=1
    noBuild=1
    noSetup=1
    noVerify=1
  fi
  case $1 in
    fetch)   unset noFetch;;
    extract) unset noExtract;;
    prep)    unset noPrep;;
    select)  unset noSelect;;
    build)   unset noBuild;;
    setup)   unset noSetup;;
    verify)  unset noVerify;;
  esac
  indSteps=1
}

################################################################################
## Definition of variable who need default values
execName="`basename ${0}`"
quietLevel=0
FTPURL="ftp.eso.org:/pub/midaspub"
## The following can be set either as environment variables from the shell
## or at the command line
defVer=22FEBpl1.0
#defVer=17FEBpl1.1
#defVer=15SEPpl1.0
#defVer=13SEPpl1.2
#defVer=12FEBpl1.2
#defVer=11FEBpl1.3
#defVer=10SEPpl1.0default
#defVer=10FEBpl1.0
#defVer=09FEBpl1.0
#defVer=08SEPpl1.0
#defVer=07SEPpl1.1
[ -z "${MIDASHOME}" ] && export MIDASHOME=/midas
[ -z "${MIDVERS}" ]   && export MIDVERS=${defVer}
_arch="${_arch:-_$(uname -m)}"
default_GCC=gcc-mp-13

################################################################################
## Command line options
while [ ! -z "${1}" ]; do
  case $1 in
    -h) usage ; shift;;
    -d) debug="-d"; quiet=""; vbose="-v"; quietLevel=0 ; shift;;
    -n) dryRun="-n"; shift;;
    -q) quiet="-q"; vbose=""; debug=""; (( quietLevel++ )) ; shift;;
    -v) vbose="-v"; quiet=""; quietLevel=0 ; shift;;
    -M) MIDASHOME="${2}"; shift; shift;;
    -V) MIDVERS="${2}"; shift; shift;;
    -S) SRCDIR="${2}"; shift; shift;;
    --noGUIs) noGUIs="--noGUIs"; shift;;
    --manualSelection) manualSelection="--manualSelection"; shift;;
    --deSelPack) deSelPacks="${deSelPacks:+${deSelPacks} }${2}"; shift; shift;;
    --gcc)    GCC="${2}"; shift; shift;;
    --prefix) MIDASPREFIX="${2}"; shift; shift;;
    --mandir) MIDASMANDIR="${2}"; shift; shift;;
    --bindir) MIDASBINDIR="${2}"; shift; shift;;
    --ftpURL) FTPURL="${2}"; shift; shift;;
    --demo)   demo=1; shift;;
    --calib)  calib=1; shift;;
    --sudo)   useSuDo=1; shift;;
    --verify) verify=1; shift;;
    --superVerify) superVerify=1; verify=1; shift;;
    --x86_64) _arch="_x86_64"; shift;;
    -bf) setStep fetch   ; shift;;
    -be) setStep extract ; shift;;
    -bp) setStep prep    ; shift;;
    -bc) setStep select  ; shift;;
    -bb) setStep build   ; shift;;
    -bs) setStep setup   ; shift;;
    -bv) setStep verify  ; verify=1; shift;;
    *) exstat=1; usage; shift;;
  esac
done

[ -z "${SRCDIR}" ]      && export SRCDIR=${MIDASHOME}/tmp
[ -z "${GCC}" ]         && export GCC=${default_GCC}
[ -z "${MIDASPREFIX}" ] && export MIDASPREFIX="/usr/local"
[ -z "${MIDASBINDIR}" ] && export MIDASBINDIR="${MIDASPREFIX}/bin"
[ -z "${MIDASMANDIR}" ] && export MIDASMANDIR="${MIDASPREFIX}/man/manl"

################################################################################
## Main loop starts...
exstat=0

checkVarIsSet MIDASHOME   fatalNoExit
checkVarIsSet MIDVERS     fatalNoExit
checkVarIsSet SRCDIR      fatalNoExit
checkVarIsSet GCC         fatalNoExit
checkVarIsSet MIDASPREFIX fatalNoExit
checkVarIsSet MIDASBINDIR fatalNoExit
checkVarIsSet MIDASMANDIR fatalNoExit

if [ "`uname`" == "Darwin" ]; then
  MacOSXver=`sw_vers -productVersion`
  MacOSXMajVer="${MacOSXver}"
  case "${MacOSXver%.[0-9]*}" in 10.4|10.5|10.6|10.7|10.8|10.9|10.10|10.11|10.12)
    MacOSXMajVer="${MacOSXver%.[0-9]*}"
  esac
fi

case "${GCC}" in
  "gcc-dp-4.2")    GCCok="T" ;;
  "gcc-mp-4.2")    GCCok="T" ;;
  "gcc-mp-4.3")    GCCok="T" ;;
  "gcc-mp-4.5")    GCCok="T" ;;
  "gcc-mp-4.6")    GCCok="T" ;;
  "gcc-mp-4.7")    GCCok="T" ;;
  "gcc-mp-4.8")    GCCok="T" ;;
  "gcc-mp-4.9")    GCCok="T" ;;
  "gcc-mp-5")      GCCok="T" ;;
  "gcc-mp-6")      GCCok="T" ;;
  "gcc-mp-7")      GCCok="T" ;;
  "gcc-mp-8")      GCCok="T" ;;
  "gcc-mp-9")      GCCok="T" ;;
  "gcc-mp-10")     GCCok="T" ;;
  "gcc-mp-11")     GCCok="T" ;;
  "gcc-mp-12")     GCCok="T" ;;
  "gcc-mp-13")     GCCok="T" ;;
  "gcc+gfortran")  GCCok="T" ;;
  "Linux.gcc-g77") GCCok="T" ;;
  *) ;;
esac

haveWGET=1
which wget > /dev/null 2>&1
estat=$?
checkForRequiredFiles > /dev/null 2>&1
if [ $exstat -ne 0 ]; then
## Check for wget:
  while [ $estat -ne 0 ]; do
    haveWGET=0
    echo "Can't find wget command, will not be able to fetch files."
    echo "Either install wget (e.g. from MacPorts), download the files manually"
    echo "or quit."
    echo "If you wish to download manually you will need the following files:"
    echo " "
    if [ ! -e ${SRCDIR}/${MIDVERS}.tar.gz ]; then
      echo "  ftp://${FTPURL}/${MIDVERS:0:5}/sources/${MIDVERS}.tar.gz"
      echo "Save as ${SRCDIR}/${MIDVERS}.tar.gz"
    fi
    if [ ! -e /Developer/SDKs/MacOSX10.3.9.sdk/usr/include/netat/sysglue.h ] && [ ! -e ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9 ]; then
      echo " "
      echo "  http://www.hq.eso.org/~jpritcha/midas/sysglue.h.Developer.SDKs.MacOSX10.3.9"
      echo "Save as ${SRCDIR}/sysglue.h.Developer.SDKs.MacOSX10.3.9"
    fi
    case "${MIDVERS}" in
      06SEPpl1.0|06SEPpl1.1|06SEPpl1.2|06SEPpl1.3|07FEBpl1.1|07SEPpl1.1|08SEPpl1.0)
        if [ ! -e ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer} ]; then
        echo " "
        echo "  http://www.hq.eso.org/~jpritcha/midas/patch.${MIDVERS}.macOSX-${MacOSXMajVer}"
        echo "Save as ${SRCDIR}/patch.${MIDVERS}.macOSX-${MacOSXMajVer}"
      fi
      ;;
    esac
    if [ ! -z "${GCCok}" ]; then
      if [ ! -e ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch} ]; then
        echo " "
        echo "  http://www.hq.eso.org/~jpritcha/midas/patch.${MIDVERS}.${GCC}${_arch}"
        echo "Save as ${SRCDIR}/patch.${MIDVERS}.${GCC}${_arch}"
      fi
    else
      warningLog "GCC value not recognised."
    fi
    if [ ! -e "${SRCDIR}/installunix.ps.gz" ]; then
      echo " "
      echo "Optional downloads:"
      echo " "
      echo "  ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.ps.gz"
      echo "Save as ${SRCDIR}/installunix.ps.gz"
    fi
    if [ ! -e "${SRCDIR}/installunix.pdf" ]; then
      echo " "
      echo "Optional downloads:"
      echo " "
      echo "  ftp://${FTPURL}/${MIDVERS:0:5}/sources/installunix.pdf"
      echo "Save as ${SRCDIR}/installunix.pdf"
    fi
    echo " "
    read -p "Quit (q), Continue anyway (c), or re-check for wget and or the files (r)? [q] " yorn
    yorn=`echo $yorn | tr [:upper:] [:lower:]`
    case ${yorn:-q} in
      r) haveWGET=1 ; which wget > /dev/null 2>&1 ; estat=$? ;;
      c) estat=0 ;;
      *) exit 1
    esac
  done
## All required downloads are present so carry on...
else
  debugLog "All required src files found..."
fi

################################################################################
## Check for required downloads if wget command not available:
if [ $haveWGET -ne 1 ]; then
  checkForRequiredFiles
  [ $exstat -ne 0 ] && exit $exstat
fi

[ -z "${noFetch}" ]   && fetch
[ -z "${noExtract}" ] && extract
[ -z "${noPrep}" ]    && prep
[ -z "${noSelect}" ]  && selectPacks
[ -z "${noBuild}" ]   && build
[ -z "${noSetup}" ]   && setup
[ -z "${noVerify}" ]  && verify

exit ${exstat:-0}