#!/usr/bin/env bash
set -euo pipefail

script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd -- "${script_dir}/.." && pwd)"
prefix="${PREFIX:-${HOME}/.local}"
profile="release"
build=1

usage() {
  cat <<'USAGE'
usage: scripts/install.sh [--prefix <dir>] [--debug] [--no-build]

Installs the Slovo toolchain layout:

  <prefix>/bin/glagol
  <prefix>/share/slovo/std/*.slo
  <prefix>/share/slovo/runtime/runtime.c

Set PREFIX instead of --prefix if preferred.
USAGE
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --prefix)
      if [ "$#" -lt 2 ]; then
        echo "--prefix requires a directory" >&2
        exit 2
      fi
      prefix="$2"
      shift 2
      ;;
    --debug)
      profile="debug"
      shift
      ;;
    --no-build)
      build=0
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unexpected argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [ "${build}" -eq 1 ]; then
  cargo build --manifest-path "${repo_root}/compiler/Cargo.toml" --profile "${profile}"
fi

binary="${repo_root}/compiler/target/${profile}/glagol"
if [ ! -x "${binary}" ]; then
  echo "missing built compiler binary: ${binary}" >&2
  echo "run cargo build --manifest-path compiler/Cargo.toml --profile ${profile}" >&2
  exit 1
fi

bin_dir="${prefix}/bin"
std_dir="${prefix}/share/slovo/std"
runtime_dir="${prefix}/share/slovo/runtime"
doc_dir="${prefix}/share/doc/slovo"

install -d "${bin_dir}" "${std_dir}" "${runtime_dir}" "${doc_dir}"
install -m 755 "${binary}" "${bin_dir}/glagol"
install -m 644 "${repo_root}/runtime/runtime.c" "${runtime_dir}/runtime.c"

find "${repo_root}/lib/std" -maxdepth 1 -type f -name '*.slo' -print0 |
  while IFS= read -r -d '' module; do
    install -m 644 "${module}" "${std_dir}/$(basename "${module}")"
  done

install -m 644 "${repo_root}/README.md" "${doc_dir}/README.md"
install -m 644 "${repo_root}/LICENSE-MIT" "${doc_dir}/LICENSE-MIT"
install -m 644 "${repo_root}/LICENSE-APACHE" "${doc_dir}/LICENSE-APACHE"

cat <<EOF
installed Slovo toolchain to ${prefix}
  ${bin_dir}/glagol
  ${std_dir}
  ${runtime_dir}/runtime.c
EOF
