#!/bin/sh 
#
# POSIX shell script to install oils-for-unix into the proper directory.
# Distributed with the source tarball.
#
# Also shared with the old "oil.ovm" build.

# NOTE: 'install' is part of coreutils and busybox.

# The variable DESTDIR allows staged installs, where the installed files are
# not placed directly into the location they're expected to be executed from.
# They are placed in a temp dir first, which they are NOT expected to run out of.
#
# https://www.gnu.org/prep/standards/html_node/DESTDIR.html
#
# Staged installs are the default method of installation by package managers
# such as gentoo-portage.
#
# https://devmanual.gentoo.org/quickstart/index.html

# old tarball

readonly OVM_NAME=oil.ovm
readonly OVM_PATH=_bin/$OVM_NAME

readonly OILS_PATH=_bin/cxx-opt-sh/oils-for-unix.stripped


log() {
  # 4 space indent
  echo "    $@" >& 2
}

die() {
  echo "FATAL install error: $@" >& 2
  exit 1
}

my_install() {
  ### A bit like install -v.  OpenBSD doesn't have -v

  echo "  + install $@" >& 2
  install "$@"
}

install_bin_and_links() {
  ### Install an executable and symlinks.

  bin_src=$1
  bin_new_name=$2
  shift 2

  # symlinks are the remaining args

  # NOTE: The configure step generates this
  if ! . _build/detected-config.sh; then
    die "Can't find _build/detected-config.sh.  Run './configure'"
  fi
  # Now $PREFIX should be defined

  #
  # Install the shell binary
  #

  bin_dest_dir="${DESTDIR}${PREFIX}/bin"
  bin_dest="$bin_dest_dir/$bin_new_name"

  if ! my_install -d "$bin_dest_dir"; then
    die "Couldn't create $bin_dest_dir"
  fi

  if ! my_install "$bin_src" "$bin_dest"; then
    die "Couldn't install $bin_src -> $bin_dest"
  fi
  log "Installed $bin_dest"

  working_dir=$PWD  # save for later

  cd "$bin_dest_dir"
  for link in "$@"; do
    if ! ln -s -f "$bin_new_name" "$link"; then  # -f to overwrite
      die "Couldn't create $link symlink"
    fi
    log "Created '$link' symlink"
  done

  #
  # Install man page
  #

  # Relevant:
  # https://unix.stackexchange.com/questions/90759/where-should-i-install-manual-pages-in-user-directory
  # https://www.freebsd.org/cgi/man.cgi?query=install

  cd "$working_dir"

  # e.g. /usr/local/share/man/man1
  man_dest_dir="${DESTDIR}${DATAROOTDIR}/man/man1"

  if ! my_install -d "$man_dest_dir"; then
    die "Couldn't create $man_dest_dir"
  fi

  # -m so it's not executable
  if ! my_install -m 644 doc/osh.1 "$man_dest_dir"; then
    die "Couldn't install man page"
  fi
  log "Installed man page"
}

if test -f "$OVM_PATH"; then
  # Python tarball keeps 'oil' for compatibility
  install_bin_and_links "$OVM_PATH" "$OVM_NAME" osh ysh oil
elif test -f "$OILS_PATH"; then
  # new name is 'ysh', which points at oils-for-unix
  install_bin_and_links "$OILS_PATH" 'oils-for-unix' osh ysh
else
  die "Couldn't find $OVM_PATH or $OILS_PATH"
fi

