#!/bin/sh
# bib-convert - convert between bibtex and refer database formats
#
# usage: bib-convert [-b | -r] [file]   (stdin if no file given)
#   -b  force refer -> bibtex
#   -r  force bibtex -> refer
#
# Without a flag the direction is detected from the input: text whose
# first record starts with @ is taken as bibtex, with % as refer.

usage() {
  printf 'usage: bib-convert [-b | -r] [file]\n' >&2
  exit 2
}

if [ -n "$BIBUTILS_LIB" ]; then
  LIB=$BIBUTILS_LIB
elif [ -d "$(dirname "$0")/lib" ]; then
  LIB=$(dirname "$0")/lib
else
  LIB=/usr/local/share/bibutils
fi

bibkey=$(dirname "$0")/bib-key
[ -x "$bibkey" ] || bibkey=bib-key

mode=auto
while getopts br opt; do
  case $opt in
    b) mode=tobib ;;
    r) mode=toref ;;
    *) usage ;;
  esac
done
shift $((OPTIND - 1))
[ $# -le 1 ] || usage

tmp=$(mktemp) || exit 1
trap 'rm -f "$tmp"' EXIT INT TERM
cat "$@" > "$tmp"

if [ "$mode" = auto ]; then
  # first line that is unambiguous wins: an @entry means bibtex, a
  # %X field means refer (a bare "% comment" decides neither)
  mode=$(awk '
    /^[ \t]*@/ { print "toref"; exit }
    /^%[A-Z] / { print "tobib"; exit }' "$tmp")
  if [ -z "$mode" ]; then
    printf 'bib-convert: cannot detect input format\n' >&2
    exit 1
  fi
fi

if [ "$mode" = toref ]; then
  exec awk -f "$LIB/bib-parse.awk" -f "$LIB/bib-canon.awk" \
           -f "$LIB/bib2ref.awk" "$tmp"
else
  awk -f "$LIB/ref2bib.awk" "$tmp" | "$bibkey"
fi
