#!/bin/bash

# Author: sonatype.com Support
# https://support.sonatype.com/hc/en-us/articles/360000722207

set -e # exit on error
# set -x # debug
set -f # no bash glob expansion

display_usage() {
  
echo "This script needs two arguments:" 
echo " Arg 1: absolute path to Nexus 2.x application directory"
echo " Arg 2: absolute path to Nexus 2.x work directory"
} 
	
if [ ! $# == 2 ]; then 
  display_usage
  exit 1
fi

if [ ! -d "$1" ]; then
  display_usage
  exit 1	
fi

if [ ! -d "$2" ]; then
  display_usage
  exit 1	
fi

nexus_app_dir="$1"
nexus_work_dir="$2"
sql="DROP TABLE PACKAGES, LASTUPDATES, VERSION_HISTORY;SHUTDOWN COMPACT;"


echo "#############################################################"
echo "# This script will attempt to drop data from your Nexus Repository Manager 2.x"
echo "# NuGet H2 database tables. It will not remove NuGet API keys." 
echo "#"
echo "# Database Directory: ${nexus_work_dir}/nuget/"
echo "#"
echo "# Type 'Y' to continue."
echo "#############################################################"
read -p "" -n 1 -r
echo 
if [[ $REPLY =~ ^[Y]$ ]]
then

echo 
echo "# Making a backup"
echo 
backup_dir="${nexus_work_dir}/nuget/reset-backup-$(date +%F-%H%M%S)"
mkdir "$backup_dir"
find "${nexus_work_dir}/nuget" -maxdepth 1 -type f | xargs cp -p -n -v -t "$backup_dir/"
h2jarname="h2-*.jar"
h2jar="$(find "${nexus_app_dir}/nexus/WEB-INF/plugin-repository" -type f -name "h2-*.jar")"

echo 
echo "# Modifying database"
echo 
# reset - the SQL statement will fail if the database is already in use by Nexus
java -cp "$h2jar" org.h2.tools.Shell -url "jdbc:h2:${nexus_work_dir}/nuget/odata" -user sa -sql "${sql}";
java -cp "$h2jar" org.h2.tools.Shell -url "jdbc:h2:${nexus_work_dir}/nuget/odata" -user sa -sql "SHUTDOWN DEFRAG;";

echo 
echo 
echo "#################### If you see 2 'Database is already closed' messages ###"
echo "# This message is expected/normal and not an error - see:"
echo "# https://groups.google.com/d/msg/h2-database/xI91Fk2RY4Y/70PxZ3DmgYUJ"
echo "#"
echo "#################### If this script makes problems worse ##################"
echo "# You can restore the backed up databases files from:"
echo "#"
echo "# $backup_dir"
echo "#"
echo "#################### IF SUCCESS - IMPORTANT NEXT STEPS ###################"
echo "# 1. Start Nexus"
echo "# 2. Run a Rebuild NuGet Feed task against each NuGet hosted repository, one at a time."
echo "# 3. After all tasks are finished, run NuGet operations verifying NuGet builds work and"
echo "#    your old NuGet API keys still work."
echo "##########################################################################"  

else
echo "Y was not entered - therefore we did nothing."   
fi

