#!/bin/sh
#
# Copyright (c) 2015 Philip M. Gollucci <pgollucci@p6m7g8.com>
# All rights reserved.
#
# Shamelessly stolen from FreeBSD's poudriere with modifications.

LC_ALL=C
unset SHELL

usage() {
  cat << EOF
Usage: bz [-b backend] [-e] [-x] command [options]

Options:
    -b bend   -- use this backend to talk to bugzilla
    -x        -- enable debugging (set -x implies -e)
    -e        -- shit the bed on errors (set -e)
    -h        -- this help message, use help for a list of commands

backend defaults to pybugz and is the only one the maintainer supports.
EOF

    exit 1
}

SETE=""
SETX=""
BZ_BACKEND=pybugz
while getopts "b:ehx" FLAG; do
  case "${FLAG}" in
    b)
      BZ_BACKEND=$OPTARG
      ;;
    e)
      SETE="-e"
      ;;
    x)
      SETE="-e"
      SETX="-x"
      ;;
    *|-h)
      usage
      ;;
  esac
done

shift $((OPTIND-1))

[ $# -lt 1 ] && usage

if [ x"$1" != x"init" ]; then
  if [ ! -e $HOME/.fbcrc ]; then
    echo "must run init first"
    exit 1
  fi
  [ -z "$PORTSDIR" ] && PORTSDIR=/usr/ports
  [ -z "$SRCDIR" ]   && SRCDIR=/usr/src

  [ -z "$EDITOR" ] && EDITOR=vi
fi

BZ_PATH=$(realpath $0)
BZ_PREFIX=${BZ_PATH%\/bin/*}
BZ_SCRIPTDIR=${BZ_PREFIX}/share/bz
BZ_BACKENDDIR=${BZ_SCRIPTDIR}/${BZ_BACKEND}

CMD=${1##*/}
shift

BZ_SCRIPTPATH="${BZ_SCRIPTDIR}/${CMD}.sh"

path=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin
CMD_ENV="${CMD_ENV} BZ_SCRIPTDIR=${BZ_SCRIPTDIR}"
CMD_ENV="${CMD_ENV} BZ_BACKENDDIR=${BZ_BACKENDDIR}"
CMD_ENV="${CMD_ENV} BZ_BACKEND=${BZ_BACKEND}"
CMD_ENV="${CMD_ENV} PATH=${path}"
CMD_ENV="${CMD_ENV} PORTSDIR=${PORTSDIR}"
CMD_ENV="${CMD_ENV} SRCDIR=${SRCDIR}"
CMD_ENV="${CMD_ENV} HOME=${HOME}"
CMD_ENV="${CMD_ENV} USER=${USER}"
CMD_ENV="${CMD_ENV} EDITOR=${EDITOR}"
CMD_ENV="${CMD_ENV} TERM=${TERM}"
CMD_ENV="${CMD_ENV} ME=$0"

if [ -f ${BZ_SCRIPTPATH}  ]; then
  exec env -i ${CMD_ENV} sh ${SETE} ${SETX} "${BZ_SCRIPTPATH}" "$@"
  exit 0
else
  echo "Unknown command: ${CMD}"
  exit 1
fi
