#!/bin/bash
# -*- coding: utf-8; mode: sh; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:fenc=utf-8:ft=sh:et:sw=4:ts=4:sts=4

# Abort on undefined variables.
set -u

# shellcheck disable=SC2154
# Don't inherit any option variables from the calling environment.
unset "${!option_@}"

# Load function library
thisdir=$(cd "$(dirname "$0")" && pwd)
# shellcheck source=functions
. "$thisdir/functions" || exit

mpbb-usage() {
    # "prog" is defined in mpbb-help.
    # shellcheck disable=SC2154
    cat <<EOF
usage: $prog [<global options>] <command> [<args>]

Build MacPorts ports in a continuous integration environment.

Global options:

  --prefix=<path>
    The prefix of the MacPorts installation that will be used for
    building ports. Defaults to \`/opt/local'.

  --work-dir=<path>
    A working directory to be used for storing temporary files,
    accessible by the MacPorts installation specified with \`--prefix'.
    The directory should persist between runs of \`mpbb'. Defaults to
    the value of \$PWD or \`/tmp/mp-buildbot'.

Available commands:

  ${cmds[0]}$(printf ', %s' "${cmds[@]:1}")

Run \`$prog help <command>' for per-command help.
EOF
}

# Process options.
parseopt prefix:,work-dir: "$@" || exit

# Use sensible defaults for options that weren't set on the command line.
# shellcheck disable=SC2154
{
    : "${option_prefix=/opt/local}"
    : "${option_work_dir=${PWD:-/tmp/mp-buildbot}}"
}

# shellcheck disable=SC2034
# Not really options, but pretend they are because they're global.
{
    option_jobs_dir=${option_work_dir}/infrastructure/jobs
    option_log_dir=${option_work_dir}/logs
}
option_failcache_dir=${option_work_dir}/failcache

# Inform the user if old repositories are still present.
if [[ -d ${option_work_dir}/tools/.svn ]]; then
    msg "\`${option_work_dir}/tools' is no longer used for the jobs" \
        'tools and may be deleted'
fi
if [[ -d ${option_work_dir}/dports/.svn ]]; then
    msg "\`${option_work_dir}/dports' is no longer used for the ports" \
        'tree and may be deleted'
fi

# shellcheck disable=SC2086
# Set up the positional arguments for the subcommand. With "set -u"
# enabled, "${foo[@]}" doesn't work if foo is empty.
set -- ${args+"${args[@]}"}

# Load the subcommand implementations. Each sourced script "mpbb-FOO"
# must define functions "FOO" and "FOO-usage".
cmds=()
usages=(mpbb-usage)
for cmdfile in "$thisdir/mpbb-"*; do
    # Unfortunately ShellCheck does not currently support following multiple
    # files, so we'll just disable the warning.
    # shellcheck disable=SC1090
    if . "$cmdfile"; then
        cmd=${cmdfile##*/mpbb-}
        cmds+=("$cmd")
        usages+=("${cmd}-usage")
    else
        err "failed to load subcommand script \`$cmdfile'"
        exit 3
    fi
done

if (( $# < 1 )); then
    err "No command specified"
    echo >&2 "Try \`$0 help' for more information."
    exit 2
fi

subcmd=$1
shift

# This loop exits with 0 if cmds contains subcmd or is empty.
for cmd in "${cmds[@]}"; do
    [[ $cmd == "$subcmd" ]] && break
done
# shellcheck disable=SC2181
if (( $? != 0 || ${#cmds[@]} == 0 )); then
    err "Unknown command \`$cmd'"
    echo >&2 "Try \`$0 help' for more information."
    exit 2
fi

## Otherwise, run the command and deal with errors
PORTSRC=${option_work_dir}/macports.conf "$subcmd" "$@"
readonly rc=$?
case $rc in
    0)
        ;;
    *)
        err "\`$subcmd' failed to run successfully"
        ;;
esac
exit $rc