#!/bin/sh 
#
# POSIX shell script to install a build oil into the proper directory.
# Distributed with the source tarball.

# 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

log() {
  # indent it a bit
  echo "    $@" 1>&2
}

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

# NOTE: The configure step
main() {
  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
  #

  #local exec_filename=oil.ovm-dbg
  local exec_filename=oil.ovm
  local bin_dest="${DESTDIR}${PREFIX}/bin/"

  if ! install -v -d "$bin_dest"; then
    die "Couldn't create $bin_dest"
  fi

  if ! install -v "_bin/$exec_filename" "$bin_dest"; then
    die "Couldn't install oil binary"
  fi
  log "Installed executable"

  local working_dir=$PWD  # save for later

  cd "$bin_dest"
  for link in osh oil; do
    if ! ln -s -f "$exec_filename" "$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
  local man_dest="${DESTDIR}${DATAROOTDIR}/man/man1/"

  if ! install -v -d "$man_dest"; then
    die "Couldn't create $man_dest"
  fi
  log "Installed man page"

  # -t to install to a directory and make them, -m so it's not executable
  if ! install -v -m 644 doc/osh.1 "$man_dest"; then
    die "Couldn't install man page"
  fi
}

main "$@"
