#!/bin/csh -f

if($1 == "-h" || $1 == ""  || $#argv != 1) then
 echo " "
 echo "Usage:   "
 echo  "  >> add_bank idname"
 echo  "     add new bank bankid"
 echo " "
 exit 0
endif

set idname = $1

rm -f tmp.txt
echo " "                                                                    > tmp.txt
echo " Adding new bank:  $idname "                                   >> tmp.txt
echo " "                                                                   >> tmp.txt
echo " ------------------------------------------------------------------" >> tmp.txt
echo " "                                                                   >> tmp.txt
echo " Bank Name                                   ==  $idname"            >> tmp.txt
echo " Bank Id                                     ==  "                   >> tmp.txt
echo " Bank Element name   max number of elements  ==  "                   >> tmp.txt
echo " "                                                                   >> tmp.txt
echo " ------------------------------------------------------------------" >> tmp.txt

$EDITOR tmp.txt

set idname      = (`cat tmp.txt | grep "Bank Name"       | awk -F"==" '{print $2}'`)
set Id          = (`cat tmp.txt | grep "Bank Id"         | awk -F"==" '{print $2}'`)
set identifiers = (`cat tmp.txt | grep "Bank Element"    | awk -F"==" '{print $2}'`)

echo
echo Bank Name:                                   $idname
echo Bank Id:                                     $Id
echo Bank Element name   max number of elements:  "$identifiers"
echo
echo 'Proceed? y/n'
echo 
set confirm = $<

if($confirm == "y") then
  
  checkid:
  # checking that bank ID doesn't exist yet. 
  rm -rf tmp4.txt
  echo  'use user_geometry;'                              > tmp4.txt
  echo  "select name, id from SDId where id =  $Id ;"   >> tmp4.txt;
  set out = `mysql -h $GEMC_HOST -u $GEMC_USER        < tmp4.txt  | grep $Id` 

  # if bank id is taken, you must pick another one 
  if("$out" != "") then
    echo 
    echo "Bank id $Id already exists. Please enter a new bank id. "
    set Id = $<
    goto checkid
  endif

  insert_identifier:
    rm -f tmp3.txt
    echo  "use user_geometry;"                                > tmp3.txt
    echo  'insert into SDId values("'$idname'", '$Id', "'"$identifiers"'");' >> tmp3.txt;
    set out = `mysql -h $GEMC_HOST -u $GEMC_USER < tmp3.txt` 
    echo Bank  $idname added.
  
endif

rm -rf tmp.txt tmp4.txt tmp3.txt



