#!/bin/bash

if [ "$1" = "" ]; then
  read -p "DATABASE INGRESSO (FreePlanet) ? " DBIN
else
  DBIN=$1
fi

if [ "$2" = "" ]; then
  PORTIN="27017"
else
  PORTIN=$2
fi

if [ "$3" = "" ]; then
  read -p "DATABASE USCITA (FreePlanet) ? " DBOUT
else
  DBOUT=$3
fi

if [ "$4" = "" ]; then
  PORTOUT="27017"
else
  PORTOUT=$4
fi

FILEMONGODB=tmp

rm -R $FILEMONGODB

echo "mongodump --db $DBIN --port=$PORTIN --out $FILEMONGODB"
mongodump --db $DBIN --port=$PORTIN --out $FILEMONGODB

echo "Copia di $DBIN ($PORTIN) Effettuata in $FILEMONGODB !"

sleep 1
cd $FILEMONGODB
mv $DBIN $DBOUT
cd ..


echo ""
echo ""
echo "*****************************************************************************************************"
echo "*** MONGODB COPIA DATABASE CANCELLANDOLO !!!!! "
echo "***"
echo "----> SEI SICURO DI VOLER ELIMINARE E SCRIVERE IL DATABASE: "
echo ""
echo "'$DBOUT' ? " 
echo ""
echo "File = $FILEMONGODB"
echo ""
echo "DBIN=$DBIN PORTIN=$PORTIN"
echo "DBOUT=$DBOUT PORTOUT=$PORTOUT"
echo "*****************************************************************************************************"
echo ""

OPTDB="$DBOUT"".*"
echo "ESEGUO -> mongo $DBOUT --port=$PORTOUT --eval \"db.dropDatabase()\""
echo "ESEGUO -> mongorestore --port=$PORTOUT --nsInclude $OPTDB $FILEMONGODB"
echo ""

read -p "SICURO DI CONTINUARE ? (Y/N) ? " risposta

if [[ $risposta == "Y" || $risposta == "y" ]]; then
  mongo $DBOUT --port=$PORTOUT --eval "db.dropDatabase()"

  mongorestore --port=$PORTOUT --nsInclude $OPTDB $FILEMONGODB    
  sleep 2
  
  rm -R $FILEMONGODB
fi 

echo "Fine"
