#!/bin/bash
if [ "$#" != "3" ]; then
       echo    "Syntax: $0 [directory] [oauth key] [oauth secret]"
       exit
fi
cd $1
KEY=$2
SECRET=$3
testf() {
       for T in $*; do
               if [ ! -e $T ]; then
                       echo "File $T does not exist"
                       exit 1
               fi
       done
}
ln -s input-0 input.gjf
ln -s output-1.fchk.gz checkpoint.fchk.gz
ln -s output-0 logfile.log
ln -s output-3 inchi.txt
ln -s output-4 smiles.txt
cat *xml > cml.xml
testf input.gjf checkpoint.fchk.gz logfile.log inchi.txt cml.xml
STOICH=`grep Stoi logfile.log  | head -1 | sed "s/Stoichiometry//g" | sed "s/\s*//g" | sort | uniq `
if [ "$STOICH" == "" ] ;then
       echo "Stoichiometry not found"
       exit 2
fi
INCHI=`head -1 inchi.txt`
INCHIKEY=`tail -1 inchi.txt`
SMILES=`head -1 smiles.txt`
R=""
for ROUTE in `grep -e "^ #" logfile.log  | sed "s/^ # //" | sort | uniq `; do
       R="$R -g $ROUTE"
done
lookup_inchikey.sh $INCHIKEY > urls
echo "http://www.imperial.ac.uk/ict/services/teachingandresearchservices/highperformancecomputing" >> urls
echo "http://www.ch.ic.ac.uk/rzepa/rzepa.xrdf" >> urls
babel -i g09 logfile.log -o pdb structure.pdb
URLS=`tac urls | awk '{print "-u "$0}' `
create.py \
               -f input.gjf \
               -f checkpoint.fchk.gz \
               -f cml.xml \
               -f logfile.log \
               -f structure.pdb \
               -t "Gaussian Job Archive for $STOICH" \
               -d "Archive of work produced using the resources of the Imperial College High Performance Computing Service." \
               -g "$INCHI" \
               -g "$INCHIKEY" \
               -g "$SMILES" \
               -g "$STOICH" $R \
         -c 37 \
               -k $KEY \
               -s $SECRET \
               $URLS