#! /usr/bin/env bash

set -o errexit
set -o nounset

# source git-sh-setup for some helpers
set +o nounset
# shellcheck disable=SC2312
source "$(git --exec-path)"/git-sh-setup
set -o nounset

GIT_DIR="$(git rev-parse --git-common-dir)"
TEMP="${GIT_DIR}/$$.tags"
FINAL="${GIT_DIR}/tags"

trap 'rm -f "$TEMP"' EXIT

files() {
  git ls-files
}

# expects files on stdin
run_ctags() {
  local -a args=(
    # tags are relative to here
    --tag-relative=yes
    # where to get files
    -L -
    # output files
    -f "${TEMP}"
    # dont tag these languages
    --languages=-sql
  )
  ctags "${args[@]}" 2>/dev/null
}

finalize() {
  mv "${TEMP}" "${FINAL}"
}

main() {
  if files | run_ctags; then
    finalize
  fi
}

main
