#!/bin/bash

TOMCAT_USER=tomcat7
METACAT_VAR=/var/metacat
METACAT_VAR_SUBDIRS="logs data inline-data documents expanded-archives temporary"
#PASSWORD=none

#usage()
#{
#	echo "resetMetacat -p|--password ldap-password"
#	exit
#} 
#
#set -- `getopt -n$0 -u --options="p:" --longoptions="password:" -- "$@"` || usage
#[ $# -lt 3 ] && usage ;
#
#while [ $# -gt 0 ]
#do
#	case "$1" in
#		-p|--password)   PASSWORD=$2; shift;;
#		-h)        usage;;
#		--)        shift;break;;
#		-*)        usage;;
#		*)         break;;            #better be the crawl directory
#	esac
#	shift
#done

/etc/init.d/tomcat7 stop

## drop metacat schema and user
echo "Droping metacat database"
su postgres -c "dropdb metacat"
echo "Droping metacat database use metacat"
su postgres -c "psql --command \"DROP USER metacat\""

## create metacat schema and user
echo "Creating metacat database schema"
su postgres -c "createdb metacat"

echo "Creating metacat user" 
su postgres -c "psql -c \"CREATE USER metacat WITH UNENCRYPTED PASSWORD 'metacat'\""

## Create the dataone logging directory
for SUBDIR in ${METACAT_VAR_SUBDIRS}
do
	FULL_VAR_SUBDIR=${METACAT_VAR}/${SUBDIR}
	if [ -d ${FULL_VAR_SUBDIR} ]
	then
	  echo "Removing Metacat application directory: ${FULL_VAR_SUBDIR}"
	  rm -rf ${FULL_VAR_SUBDIR}
	fi
	echo "Making Metacat application directory: ${FULL_VAR_SUBDIR}"
	mkdir ${FULL_VAR_SUBDIR}
	echo "changing ownership of ${FULL_VAR_SUBDIR}  to ${TOMCAT_USER}"
	chown ${TOMCAT_USER}.${TOMCAT_USER} ${FULL_VAR_SUBDIR}
done

# delete logging files
rm  /var/log/dataone/daemon/*
rm  /var/log/dataone/synchronize/*
rm  /var/log/dataone/replicate/*
rm  /var/log/dataone/logAggregate/*

#delete solr index
rm -rf /var/lib/solr/data/d1-cn-log/*
rm -rf /var/lib/solr/data/d1-cn-index/*

# dropping the index schema and user
su postgres -c "dropdb d1-index-queue"
su postgres -c "psql --command \"DROP USER indexer\""
# re-creating the index schema and user
su postgres -c "createdb d1-index-queue"
su postgres -c "psql -c \"CREATE USER indexer WITH UNENCRYPTED PASSWORD 'indexer'\""

/etc/init.d/tomcat7 start
echo "Updating last modified"
/usr/local/bin/CnScripts/ldapUpdateLastHarvested.pl --all
echo "Updating last aggregated"
/usr/local/bin/CnScripts/ldapUpdateLastAggregated.pl --all

echo "Run /usr/share/metacat/debian/createObjectFormat after metacat administrative Configuration"