#!/bin/sh
set -e

toplevel=$(pwd)/HydroGeoSphere-2898-Linux

chmod +x ./hgs-setup-core-2898
./hgs-setup-core-2898

posix_make_path() {
  {
    echo "export HGSDIR=${toplevel}"
    echo "export PATH=\$HGSDIR:\$PATH"
  } > ~/.hgspath.sh
  chmod +x ~/.hgspath.sh
}

posix_source_path() {
  if ! grep -Fx ". ~/.hgspath.sh" "$1" >/dev/null 2>&1; then
    echo ". ~/.hgspath.sh" >> "$1"
  fi
  echo "Run \`. $1' to get your new \$PATH in this shell"
}

printf "Would you like to add HGS executables to your \$PATH? [Y/n] "
read -r answer
case $answer in
  [yY]* | "" )
    case $SHELL in
      */fish)
        echo "fish detected; adding new \$PATH"
        fish -c "
set user_paths (echo \$fish_user_paths | sed -E 's#[^ ]+/HydroGeoSphere-\w+-Linux ?##g')
set -U fish_user_paths ${toplevel} \$user_paths"
        ;;
      */zsh)
        zshrc=${ZDOTDIR:-$HOME}/.zshrc
        echo "Zsh detected; adding new \$PATH to $zshrc"
        posix_make_path
        posix_source_path "$zshrc"
        ;;
      *)
        echo "Bash assumed; adding new \$PATH to ~/.bashrc"
        posix_make_path
        posix_source_path ~/.bashrc
        ;;
    esac
    ;;
esac

oldpath=$(pwd)
cd "$toplevel"
chmod +x rlmhost.sh rlmhostid
./rlmhost.sh
cp hgs phgs
cd "$oldpath"
echo "Installation complete"
echo "Please email the hostid.txt file in the installation directory to info@aquanty.com to receive your hgs.lic license file. You should put your license file into the installation directory."
