#!/bin/sh

init_variables() {
  progname=${0##*/}

  query=repo
  commit=HEAD
  remote=$(git config --default origin browse.remote)
  file=
}

parse_command_line() {
  while getopts 'c:r:t:' opt; do
    # shellcheck disable=SC2249
    case "${opt}" in
      c) commit="${OPTARG}" ;;
      r) remote="${OPTARG}" ;;
      t) query="${OPTARG}" ;;
      ?) exit_error ;;
    esac
  done

  shift "$((OPTIND - 1))"

  file="$1"
}

validate_command_line() {
  if [ "${query}" != 'repo' ] \
    && [ "${query}" != 'commit' ] \
    && [ "${query}" != 'issue' ] \
    && [ "${query}" != 'file' ] \
    && [ "${query}" != 'review' ]; then
    exit_error "invalid type argument '${query}'"
  fi

  if [ "${query}" = 'file' ] && [ -z "${file}" ]; then
    exit_error 'missing file argument'
  fi

  if ! git rev-parse -q --verify "${commit}^{commit}" >/dev/null; then
    exit_error "invalid commit '${commit}'"
  fi

  if ! git remote | grep -q "${remote}"; then
    exit_error "invalid remote '${remote}'"
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${progname}: $1"
  exit 1
} >&2

display_url() {
  remote_alias=$(
    git config "remote.${remote}.url" \
      | sed 's/:.*//'
  )

  repo_path_sed=$(
    git config "browse.${remote_alias}.repoPathSed"
  )
  [ -z "${repo_path_sed}" ] && exit_error 'remote does not use a valid URL alias for browsing'

  repo_path=$(
    git config "remote.${remote}.url" \
      | sed "${repo_path_sed}"
  )

  url=$(
    git config "browse.${remote_alias}.${query}Url" \
      | sed "s|{repo_path}|${repo_path}|"
  )
  [ -z "${url}" ] && exit_error 'remote does not support this type of URL for browsing'

  # shellcheck disable=SC2249
  case "${query}" in
    repo)
      echo "${url}"
      ;;
    commit)
      commit_id=$(git rev-parse "${commit}")
      echo "${url}" | sed "s/{commit_id}/${commit_id}/"
      ;;
    issue)
      issue_id=$(git commit-issue-id "${commit}")
      [ -z "${issue_id}" ] && exit_error 'commit has no issue id linked to it'
      echo "${url}" | sed "s/{issue_id}/${issue_id}/"
      ;;
    review)
      review_id=$(git commit-review-id "${commit}")
      [ -z "${review_id}" ] && exit_error 'commit has no review id linked to it'
      echo "${url}" | sed "s/{review_id}/${review_id}/"
      ;;
    file)
      echo "${url}" | sed "s|{file}|${file}|"
      ;;
  esac
}

init_variables
parse_command_line "$@"
validate_command_line

display_url
