if [ -z "$1" ]
then
    echo ""
    echo "no server [dev/tst/beta/prd] speficified!"
    echo ""
    exit
fi

if [ -z "$2" ]
then
   echo ""
   echo "no data version specified!"
   echo ""
   exit
fi

server=$1
ver=$2

wrk_dir="/data/shared/glygen/deployment"

db_name="glydb"
username="glydbadmin"
password="glydbpass"
api_cgi_dir="/var/www/cgi-bin/api/"
if [ $server == "beta" ]
then
    db_name="glydb_beta"
    username="glydb_betaadmin"
    password="glydb_betapass"
    api_cgi_dir="/var/www/cgi-bin/beta/api/"
fi


#########################################################
# PART-I: Update collections in tmpdb, and then 
# dump each tmpdb collection to disk. This step takes time
# but does not involve the targetdb
#########################################################
echo `date`" ... PART-I: started time stamp"
cd $wrk_dir

# Update collections in tmpdb 
dump_dir="/data/shared/glygen/mongodump/$server/"
archive_file="/data/shared/glygen/mongodump/$server/tmpdb_archive"

coll_list="c_species c_disease c_path c_searchinit c_motif c_glycan c_protein c_site c_alignment c_cluster c_idtrack c_list c_publication c_network c_stat"
#coll_list="c_glycan"

for collname in $coll_list
do
    python3 delete-tmpdb-objects.py -c $collname -v $ver
    python3 load-tmpdb-objects.py -c $collname -v $ver 
done

rm -f $archive_file
mongodump --username $username --password $password --db=tmpdb --archive=$archive_file

echo `date`" ... PART-I: end time stamp"



######################################################
# PART-II: restore dump of tmpdb to final targetdb, 
# this is the only time the targetdb will be busy
#######################################################
echo `date`" ... PART-II: started time stamp"
mongorestore --username $username --password $password --authenticationDatabase=$db_name --archive=$archive_file --drop --nsFrom="tmpdb.*" --nsTo="$db_name.*"


python3 upsert-version.py -v $ver -d $db_name -c "data"
sed -ri "0,/(\s*\"datarelease\"\s*:).*$/{s/(\s*\"datarelease\"\s*:).*$/\1\"$ver\"/}" $api_cgi_dir/conf/config.json

if [ $server != "dev" ]
then
    cd /home/rykahsay/glygen-backend-api/
    python update-search-init.py -s $server
fi

echo `date`" ... PART-II: end time stamp"




