#!/bin/bash

here=`dirname $0`
export PATH="$here:$PATH"


maindir="$1"
pdbdir="$2"
syncpdbdir=0
if [ "$3" ]; then
  syncpdbdir="$3"
fi

if ! [ "$maindir" ]; then
  me="${0%%*/}"
  echo "USAGE: $me <imemdb_root_dir> [pdb_mirror_dir [sync?]]

  <imemdb_root_dir>    Contains subdirectories 'cgdb' and date-stamped imemdb
                       directories. If it does not exist it will be created.
                       
  [pdb_mirror_dir]     (Optional) Contains a local mirror of the Protein Data
                       Bank. If it does not exist it will be created. If it
                       exists it will be left unchanged, unless the 'sync?'
                       option is set to 1.
  
  [sync?]              (Optional) Should the pdb dirctory be synced with the PDB
                       online? (1 or 0, default:0)
" 1>&2
  exit 1
fi

mkdir -p "$maindir"

if ! [ -d "$maindir" ]; then
  echo "Directory does not exist: $maindir" 1>&2
  exit 1
fi


if [ "$pdbdir" ]; then
  if ! [ -e "$pdbdir" ] || (( syncpdbdir > 0 )); then
    echo "Syncing PDB"
    mkdir -p "$pdbdir"
    rsync -a --port=33444 "rsync.wwpdb.org::ftp_data/structures/divided/pdb/" "$pdbdir"
  else
    echo "Leaving PDB directory unchanged (NOT syncing it with the PDB online)."
  fi
else
  echo "No PDB directory provided. Will attempt to fetch PDBs online as required."
fi



cd $maindir >/dev/null



echo "Syncing CGDB"
cgdb_syncdb cgdb > changed_pdbs.txt

newpdbs=(`cat changed_pdbs.txt | grep -A1 'added' | tail -n1 | tr -d "[],'"`)
removedpdbs=(`cat changed_pdbs.txt | grep -A1 'deleted' | tail -n1 | tr -d "[],'"`)
rm -f changed_pdbs.txt


if (( "${#removedpdbs[*]}" > 0 )); then
  echo "NOTICE: Some PDBs were removed from the CGDB database. They will NOT be removed from the local copy."
  #echo "${removedpdbs[*]}"
fi

#if (( "${#newpdbs[*]}" == 0 )); then
#  echo "NOTICE: No new PDBs. Leaving database unchanged. Exiting."
#  exit
#fi

echo "New PDBs: ${newpdbs[*]}"



datestamp=`date '+%Y-%m-%d'`
mkdir -p "$datestamp"
cd "$datestamp" >/dev/null



echo "Building iMemDB root"
imem_builddb ../cgdb 0

success=$?
if (( $success != 0 )); then
  echo "Building iMembrane database from CGDB failed" 1>&2
  exit 88
fi



echo "Projecting iMemDB onto the PDB"
imem_projectdb 0 1 "$pdbdir"

success=$?
if (( $success != 0 )); then
  echo "Projecting iMembrane database onto the PDB failed" 1>&2
  exit 99
fi



ln -sf 1/entries
ln -sf 1/seq
ln -sf 1/representatives.table
cd .. >/dev/null
rm -f current && ln -s "$datestamp" current
