#!/bin/bash
#
# Sets up MacPorts-based stuff on this machine.
#
# This assumes you already have MacPorts installed. It just installs apjanke's
# preferred packages using MacPorts.

# Load JXL. See "Loading JXL" in dots/README.md.
source "$(cd "$(dirname "$0")" && pwd -P)/../dots/all-os/flat/dotlib/jxl-lib.sh" \
    || { echo >&2 "ERROR: failed to load jxl-lib.sh"; exit 1; }

jxl::init_script
jxl::use_short_names

OPT_TRACE=0

function usage() {
  cat <<EOF
$PROGRAM_NAME - Install apjanke's preferred MacPorts packages on this machine

Usage:
  $PROGRAM_NAME [--trace]
  $PROGRAM_NAME --help

Options:
    -x, --trace     trace program execution
$(jxl::std_options_help)
EOF
}

function main() {
  if [[ $OPT_TRACE = 1 ]]; then set -o xtrace; fi

  THISDIR="$( dirname "${BASH_SOURCE[0]}" )"
  my_macports_cfg_dir="$THISDIR/macports"
  _read_lines "$my_macports_cfg_dir/macports-ports-standard"
  ports=( ${_read_lines_out[@]+"${_read_lines_out[@]}"} )

  sudo port selfupdate
  sudo port -N install ${ports[@]+"${ports[@]}"}
}

function parse_cli() {
  local arg

  while [[ $# -ge 1 ]]; do
    arg="$1"; shift
    case "$arg" in
      --trace | -x)                 OPT_TRACE=1 ;;
      *)
        jxl::std_opt "$arg" \
            || die "Unexpected argument: ${arg}. See '$PROGRAM_NAME --help' for usage"
        if [[ $_JXL_WANT_HELP == 1 ]]; then usage; exit 0; fi
        ;;
    esac
  done

  readonly OPT_TRACE
}

# shellcheck disable=SC2329
function _do() {
  echo "$@"
  "$@"
}

function _read_lines() {
  # Read FILE's non-blank lines into the global array $_read_lines_out.
  #
  # bash 3.2 (what /bin/bash is on macOS) has no mapfile, and `read -d ''` returns 1 at
  # EOF, which errexit catches. The `|| [[ -n ... ]]` picks up a last line that has no
  # trailing newline, which a plain `while read` drops silently.
  _read_lines_out=()
  local line
  while IFS= read -r line || [[ -n "$line" ]]; do
    if [[ -n "$line" ]]; then _read_lines_out+=("$line"); fi
  done < "$1"
}

parse_cli "$@"
main
exit 0
