#!/bin/bash

# reads the bibfile one line at a time  transforming
# each bibtext entry into an SQL INSERT statement
# Pipe the entire result into 'sed' to replace the table
# name variable %TABLE% with the table name parameter
# This script can therefore work with a generic BIBTEXT
# file!
format_recs () 
{ 
bibfile=$1
outfile="$1.sql"
table=$2
awk '$0 !~ /^[\@}]/ {num=split($0, arr, "=") 
       f1=trim(arr[1])
       f2=trim(arr[2])
       #only processes the second parameter if split was successful
       if (num > 1) { 
         # remove the last comma
         sub(/,$/, "", f2)
         # remove enclosing quotes
         sub(/^"/, "", f2)
         sub(/"$/, "", f2)
         # escape all single quotes in the value
         f2=escapestr(f2)
         # remove curly brackets around numeric fields
         if (f1 == "year" && substr(f2,1,1) == "{") {
           sub(/^\{/, "", f2)
           sub(/\}$/, "", f2)
         }
         if (f1 != "year") {
          # enclose within single quotes except for year field
          if (substr(f2,1,1) != "\47") {
             f2=("\47" f2 "\47")   
          }
         }
       } else {       
         # remove the last comma
         sub(/,$/, "", f1)
         sub(/"$/, "", f1)
         f1=escapestr(f1)
       }
       # author entry marks the beginning of a new record
       if (num > 1) {
         if (f1 == "author") {
          # Override data file with the formatted records
          if (r1 != "") {
            r1=(r1 " ) ")
            r2=(r2 " ) ")
            r=((r1) (r2) ";")
            #print r > FILENAME 
            print r
           }          
           r1=("INSERT INTO %TABLE% ( " f1)
           r2=("VALUES( " f2)
         } else {
          r1=((r1) "," (f1))
          r2=((r2) "," (f2))
         }
       } else {
        # append this line to the previous value
        f1=(" " f1 "\47")
        sub(/\47$/, f1, r2)
       }
     }
     END { 
       # the last record
       r1=(r1 " ) ")
       r2=(r2 " ) ")
       r=((r1) (r2) ";")
       # print r > FILENAME 
       print r
     }
     # user-defined functions
     function ltrim(s) {
       sub(/^ */, "", s);
       return s
     }
     function rtrim(s) {
       sub(/ *$/, "", s);
       return s
     }
     function trim(s) {
       return rtrim(ltrim(s));
     }
     function escapestr(s) {
       # escape all single-quote chars in a string
       gsub(/(\\\47|\47)/, "\\\47", s)
       return s
     }
     ' $bibfile | sed -n -e "s/%TABLE%/$table/gp" > $outfile

return 0
}

##############################################
# START PROGRAM 
##############################################
# Usage: bin/parsebib bibfile
#
#

if [ -z "$1" ] ; then
 echo "Usage: bin/parsebib bibfile"
 exit 1
fi
  
bin_dir=`dirname $0` 
output_dir=`dirname $1`

bib_file=$1

proceedings="\@inproceedings{"
books="\@book{"
articles="\@article{"

file1=$output_dir/articles.bib
file2=$output_dir/books.bib
file3=$output_dir/proceedings.bib

#extract article and book entries from the bib file
sed -n -e "/$articles/,/^}/p" $bib_file > $file1
sed -n -e "/$books/,/^}/p" $bib_file > $file2
sed -n -e "/$proceedings/,/^}/p" $bib_file > $file3

#read in the extracted files and create db entries from them
#format_recs $file1 "article"
format_recs $file2 "book"
format_recs $file3 "article"

