#!/bin/bash -e
# --------------------------------------------------------------------------- #
#                                                                             #
# Script for setting up (installing) WAVEWATCH III.                           #
#                                                                             #
# --------------------------------------------------------------------------- #

# --------------------------------------------------------------------------- #
# 0. Process command line arguments                                           #
# --------------------------------------------------------------------------- #

# 0.a Error message function
errmsg ()
{
  echo "" 2>&1
  while [ $# != 0 ]
  do
    echo "ERROR: $1" 2>&1
    shift
  done
  echo "" 2>&1
}

# 0.b Usage function
myname="`basename $0`"  #name of script
optstr="c:hqs:et:"  #option string for getopt function
usage ()
{
cat 2>&1 << EOF

Usage: $myname source_dir Options
Required:
  source_dir : path to model dir of WW3 source
Options:
  -c cmplr         : setup comp & link files for specified cmplr (see manual section 5.6)
  -s swtch         : setup switch file for specified swtch (see manual section 5.8)
  -h               : print usage and exit
  -q               : do not prompt for changes to existing WW3 environment
  -e               : edit switch file
  -t tdir          : set path for scratch directory to tdir

EOF
}

# 0.c Setup array of command-line arguments
args=`getopt $optstr $*`
if [ $? != 0 ]
then
  usage
  exit 1
fi
set -- $args

# 0.d Process command-line options
while :
do
  case "$1" in
  -c) shift; cmplr="$1" ;;
  -h) help=1 ;;
  -q) no_prompt=1 ;;
  -s) shift; swtch="$1" ;;
  -e) edit=1 ;;
  -t) shift; tdir="$1" ;;
  --) break ;;
  esac
  shift
done
shift #remove the trailing --
if [ $help ]
then
  usage
  exit 1
fi

# 0.e Get required arguments
if [ ! $# = 0 ]
then
  path_s="$1" ; shift
else
  usage
  exit 1
fi


# --------------------------------------------------------------------------- #
# 1. Preparations                                                             #
# --------------------------------------------------------------------------- #


# 1.a ID header  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

  echo ' '
  echo '                *****************************'
  echo '              ***   WAVEWATCH III setup     ***'
  echo '                *****************************'
  echo ' '


# 1.b Convert source path from "relative" to "absolute"
if [ ! -d $path_s ]
then
  errmsg "$path_s not found"
  usage
  exit 1
fi
path_s="`cd $path_s 1>/dev/null 2>&1 && pwd`"

# 1.c Paths to source subdirectories
path_b="$path_s/bin"
if [ ! -d $path_b ]
then
  errmsg "$path_b not found"
  exit 1
fi
path_a="$path_s/aux"
if [ ! -d $path_a ]
then
  errmsg "$path_a not found"
  exit 1
fi


# --------------------------------------------------------------------------- #
# 2. Set up WWATCH3 environment                                               #
# --------------------------------------------------------------------------- #
# 2.a Environment file

if [[ "$0" = /* ]]
then
  path_bin=$(dirname $0)
else
  path_bin="${PWD}/$(dirname $0)"
fi
path_bin="`cd $path_bin 1>/dev/null 2>&1 && pwd`"

echo ' '
if [ -e $path_bin/wwatch3.env ]
then
  ww3_env=$path_bin/wwatch3.env
  echo "[INFO] local env file wwatch3.env found in $ww3_env"
elif [ -e ${HOME}/.wwatch3.env ]
then
  cp ${HOME}/.wwatch3.env $path_bin/wwatch3.env
  ww3_env=$path_bin/wwatch3.env
  echo "[INFO] global env file wwatch3.env copied in $ww3_env"
elif [ ! -z ${WWATCH3_ENV} ]
then
  ww3_env=${WWATCH3_ENV}
  echo "[INFO] user defined env file wwatch3.env found in $ww3_env"
else
  ww3_env=$path_bin/wwatch3.env
  echo "[INFO] local env file wwatch3.env created in $ww3_env"
fi

# 2.b Check for existing environment and set defaults
if [ -f $ww3_env ]
then
  sed -i "s/WWATCH3_F77/WWATCH3_F90/g" $ww3_env

  echo "   Setup file $ww3_env found"

  set `grep WWATCH3_LPR $ww3_env` ; shift
  prntr="$*"
  echo "      Printer (listings)          : $prntr"

  set `grep WWATCH3_F90 $ww3_env` ; shift
  comp_fc="$*"
  echo "      auxiliary FORTRAN compiler  : $comp_fc"

  set `grep WWATCH3_CC $ww3_env` ; shift
  comp_cc="$*"
  echo "      auxiliary C compiler        : $comp_cc"

  echo "      Source directory            : $path_s"

  set `grep WWATCH3_TMP $ww3_env` ; shift
  if [ $tdir ]
  then
    temp_dir=$tdir
  else
    temp_dir="$*"
  fi
  echo "      Scratch directory           : $temp_dir"

  set `grep WWATCH3_SOURCE $ww3_env` ; shift
  source="$*"
  echo "      Save source code            : $source"

  set `grep WWATCH3_LIST $ww3_env` ; shift
  list="$*"
  echo "      Save listings               : $list"

else
  echo "   Setup file $ww3_env not found"

  if [ $PRINTER ]
  then
    prntr=$PRINTER
  else
    prntr=printer
  fi
  comp_fc=gfortran
  comp_cc=gcc
  if [ $tdir ]
  then
    temp_dir=$tdir
  else
    temp_dir=$(dirname $path_bin)/tmp
  fi
  source=yes
  list=yes

    echo ' '
    echo "   Default set up :"
    echo "      Printer (listings)       : $prntr"
    echo "      Auxiliary FORTRAN comp.  : $comp_fc"
    echo "      Auxiliary C compiler     : $comp_cc"
    echo "      Scratch directory        : $temp_dir"
    echo "      Save sources             : $source"
    echo "      Save listings            : $list"
fi


if [ $no_prompt ]
then
  do_set='n'
else
  OK="$NULL"
  until [ "$OK" = 'y' ] || [ "$OK" = 'Y' ] || \
        [ "$OK" = 'n' ] || [ "$OK" = 'N' ]
  do
    echo -n "   Update settings ? [y/n] "
    read OK
    case $OK in
     'y'|'Y') do_set='y' ;;
     'n'|'N') do_set='n' ;;
    esac
  done
fi



# 2.c Get user input for new environment
if [ "$do_set" = 'y' ]
then

  # Get user input for new set-up
  echo ' '
  echo "   Creating new set-up :"
  OK="$NULL"
  until [ "$OK" = 'y' ] || [ "$OK" = 'Y' ]
  do
    echo ' '

    echo -n "      Printer for listings [$prntr] : "
    instr="$NULL" ; read instr
    if [ -n "$instr" ]
    then
      prntr="$instr"
    fi

    echo -n "      Auxiliary FORTRAN compiler [$comp_fc] : "
    instr="$NULL" ; read instr
    if [ -n "$instr" ]
    then
      comp_fc="$instr"
    fi

    echo -n "      Auxiliary C compiler [$comp_cc] : "
    instr="$NULL" ; read instr
    if [ -n "$instr" ]
    then
      comp_cc="$instr"
    fi

    OK="$NULL"
    until [ "$OK" = 'y' ]
    do
      echo -n "      Scratch space [$temp_dir] : "
      instr="$NULL" ; read instr
      if [ -n "$instr" ]
      then
        temp_dir="$instr"
      fi
      if [ -n "$temp_dir" ]
      then
        if [ -d $temp_dir ]
        then
          OK='y'
        else
          if `mkdir $temp_dir` 2> /dev/null
          then
            OK='y'
          fi
          rmdir $temp_dir
        fi
      fi
    done

    echo -n "      Save source code files (*.f)  [$source] : "
    instr="$NULL" ; read instr
    if [ -n "$instr" ]
    then
      if [ "$instr" = 'yes' ] || [ "$instr" = 'YES' ]
      then
        source='yes'
      else
        source='no'
      fi
    fi

    echo -n "      Save listing files  [$list] : "
    instr="$NULL" ; read instr
    if [ -n "$instr" ]
    then
      if [ "$instr" = 'yes' ] || [ "$instr" = 'YES' ]
      then
        list='yes'
      else
        list='no'
      fi
    fi

    echo ' '
    echo "   Modified set up :"
    echo "      Printer (listings)       : $prntr"
    echo "      Auxiliary FORTRAN comp.  : $comp_fc"
    echo "      Auxiliary C compiler     : $comp_cc"
    echo "      Scratch directory        : $temp_dir"
    echo "      Save sources             : $source"
    echo "      Save listings            : $list"
    echo -n "   New settings OK ? [y/n] "
    read OK
  done

fi

# 2.d Create new environment file
rm -f $ww3_env
echo '#'                                          > $ww3_env
echo '# Environment variables for wavewatch III' >> $ww3_env
echo '# ---------------------------------------' >> $ww3_env
echo '#'                                         >> $ww3_env
echo ' '                                         >> $ww3_env
echo "WWATCH3_LPR      $prntr"                   >> $ww3_env
echo "WWATCH3_F90      $comp_fc"                 >> $ww3_env
echo "WWATCH3_CC       $comp_cc"                 >> $ww3_env
echo "WWATCH3_DIR      $path_s"                  >> $ww3_env
echo "WWATCH3_TMP      $temp_dir"                >> $ww3_env
echo "WWATCH3_SOURCE   $source"                  >> $ww3_env
echo "WWATCH3_LIST     $list"                    >> $ww3_env
echo ' '                                         >> $ww3_env

# --------------------------------------------------------------------------- #
# 3. Set up other WWATCH3 files                                               #
# --------------------------------------------------------------------------- #
# 3.a Setup makefile for auxiliary programs
echo ' '
echo '   Setup makefile for auxiliary programs'
cd $path_a
cat > $path_a/makefile << 'EOF'
############################################################
# FC, CC & BIN must be defined when called
############################################################

BIN_LIST = $(BIN)/w3adc $(BIN)/w3list $(BIN)/w3prnt $(BIN)/w3split

all: $(BIN_LIST)

$(BIN)/w3adc: w3adc.f
	$(FC) -o $(BIN)/w3adc w3adc.f

$(BIN)/w3list: w3list.f
	$(FC) -o $(BIN)/w3list w3list.f

$(BIN)/w3prnt: w3prnt.f
	$(FC) -o $(BIN)/w3prnt w3prnt.f

$(BIN)/w3split: w3split.f
	$(FC) -o $(BIN)/w3split w3split.f

$(BIN)/w3xxx: w3xxx.c
	$(CC) -o $(BIN)/w3xxx w3xxx.c

clean:
	rm -f $(BIN_LIST)
EOF
echo ' '

# 3.b Compile auxiliary programs
echo ' '
echo '   Compile auxiliary programs'
if make -C $path_a FC=$comp_fc CC=$comp_cc BIN=$path_b
then :
else
  errmsg "Error occured during compile of auxiliary programs"
  exit 1
fi
echo ' '

# 3.c Setup comp & link files
if [ $cmplr ]
then
  echo ' '
  echo '   Setup comp & link files'
  if [ -f $path_b/comp.$cmplr ]
  then
    rm -f $path_b/comp
    cp -f $path_b/comp.$cmplr $path_b/comp
    echo "      copy $path_b/comp.$cmplr => $path_b/comp"
  elif [ "$cmplr" == "mpt" ] || [ "$cmplr" == "mpt_debug" ]                         || \
       [ "$cmplr" == "datarmor_mpt" ] || [ "$cmplr" == "datarmor_mpt_debug" ]       || \
       [ "$cmplr" == "intel" ] || [ "$cmplr" == "intel_debug" ]                     || \
       [ "$cmplr" == "so_intel" ] || [ "$cmplr" == "so_intel_debug" ]               || \
       [ "$cmplr" == "datarmor_intel" ] || [ "$cmplr" == "datarmor_intel_debug" ]   || \
       [ "$cmplr" == "gnu" ] || [ "$cmplr" == "gnu_debug" ]                         || \
       [ "$cmplr" == "theia" ] || [ "$cmplr" == "wcoss_cray" ]                      || \
       [ "$cmplr" == "hera" ] || [ "$cmplr" == "orion" ]                            || \
       [ "$cmplr" == "wcoss_phase2" ] || [ "$cmplr" == "wcoss_dell_p3" ]            || \
       [ "$cmplr" == "wcoss2" ]                                                     || \
       [ "$cmplr" == "datarmor_gnu" ] || [ "$cmplr" == "datarmor_gnu_debug" ]       || \
       [ "$cmplr" == "pgi" ] || [ "$cmplr" == "pgi_debug" ]                         || \
       [ "$cmplr" == "datarmor_pgi" ] || [ "$cmplr" == "datarmor_pgi_debug" ]       || \
       [ "$cmplr" == "ukmo_cray" ] || [ "$cmplr" == "ukmo_cray_debug" ]             || \
       [ "$cmplr" == "ukmo_cray_gnu" ] || [ "$cmplr" == "ukmo_cray_gnu_debug" ]; then
     source $path_b/cmplr.env
     sed -e "s/<optc>/$optc/" -e "s/<comp_seq>/$comp_seq/" -e "s/<comp_mpi>/$comp_mpi/" -e "s/<optomp>/$optomp/" -e "s/<err_pattern>/$err_pattern/" -e "s/<warn_pattern>/$warn_pattern/" $path_b/comp.tmpl > $path_b/comp
     echo "      sed $path_b/comp.tmpl => $path_b/comp"
  else
    errmsg "$path_b/comp.$cmplr not found"
    exit 1
  fi
  if [ -f $path_b/link.$cmplr ]
  then
    rm -f $path_b/link
    cp -f $path_b/link.$cmplr $path_b/link
    echo "      copy $path_b/link.$cmplr => $path_b/link"
  elif [ "$cmplr" == "mpt" ] || [ "$cmplr" == "mpt_debug" ]                         || \
       [ "$cmplr" == "datarmor_mpt" ] || [ "$cmplr" == "datarmor_mpt_debug" ]       || \
       [ "$cmplr" == "intel" ] || [ "$cmplr" == "intel_debug" ]                     || \
       [ "$cmplr" == "so_intel" ] || [ "$cmplr" == "so_intel_debug" ]               || \
       [ "$cmplr" == "datarmor_intel" ] || [ "$cmplr" == "datarmor_intel_debug" ]   || \
       [ "$cmplr" == "gnu" ] || [ "$cmplr" == "gnu_debug" ]                         || \
       [ "$cmplr" == "theia" ] || [ "$cmplr" == "wcoss_cray" ]                      || \
       [ "$cmplr" == "hera" ] || [ "$cmplr" == "orion" ]                            || \
       [ "$cmplr" == "wcoss_phase2" ] || [ "$cmplr" == "wcoss_dell_p3" ]            || \
       [ "$cmplr" == "wcoss2" ]                                                     || \
       [ "$cmplr" == "datarmor_gnu" ] || [ "$cmplr" == "datarmor_gnu_debug" ]       || \
       [ "$cmplr" == "pgi" ] || [ "$cmplr" == "pgi_debug" ]                         || \
       [ "$cmplr" == "datarmor_pgi" ] || [ "$cmplr" == "datarmor_pgi_debug" ]       || \
       [ "$cmplr" == "ukmo_cray" ] || [ "$cmplr" == "ukmo_cray_debug" ]             || \
       [ "$cmplr" == "ukmo_cray_gnu" ] || [ "$cmplr" == "ukmo_cray_gnu_debug" ]; then
     source $path_b/cmplr.env
     sed -e "s/<optl>/$optl/" -e "s/<comp_seq>/$comp_seq/" -e "s/<comp_mpi>/$comp_mpi/" -e "s/<optomp>/$optomp/" $path_b/link.tmpl > $path_b/link
    echo "      sed $path_b/link.tmpl => $path_b/link"
  else
    errmsg "$path_b/link.$cmplr not found"
    exit 1
  fi
  chmod 775 $path_b/comp $path_b/link
fi
# 3.d Setup switch file
if [ $swtch ]
then
  echo ' '
  echo '   Setup switch file'
  if [ -f $path_b/switch_$swtch ]
  then
    rm -f $path_b/switch
    cp -f $path_b/switch_$swtch $path_b/switch
    echo "      $path_b/switch_$swtch => $path_b/switch"
  else
    errmsg "$path_b/switch_$swtch not found"
    exit 1
  fi
fi

# 3.e Edit switch file
if [ $edit ] 
  then
  echo "      Edit $path_b/switch"
  if [ ! -f $path_b/switch ]
  then
    errmsg "$path_b/switch not found"
    exit 1
  fi
  if [ $EDITOR ]
  then
    if $EDITOR $path_b/switch
    then :
    else
      errmsg "Error occured during edit of $path_b/switch"
      exit 1
    fi
  else
    errmsg "the EDITOR environment variable must be set"
    exit 1
  fi
fi

# --------------------------------------------------------------------------- #
# 4. Create WWATCH3 required model subdirectories                             #
# --------------------------------------------------------------------------- #
echo ' '
echo '   Create required model subdirectories'
if [ ! -d $path_s/exe ]
then
  mkdir $path_s/exe
fi
if [ ! -d $path_s/obj ]
then
  mkdir $path_s/obj
fi
if [ ! -d $path_s/mod ]
then
  mkdir $path_s/mod
fi

# --------------------------------------------------------------------------- #
echo ' '
echo 'Finished setting up WAVEWATCH III'
echo ' '

# --------------------------------------------------------------------------- #
# End of script                                                               #
# --------------------------------------------------------------------------- #