# Back Up Mysql Database phproject By oTTo
#!/bin/bash

DATABASENAME=FreePlanet

function getfirstfile {
   myresult=$(ls -t | head -1)   
}

cd /root/backups


if [ "$1" = "" ]; then
  getfirstfile
  FF=$myresult
else
  FF=$1
fi

DIRBACKUP=/root/backups
DIRRESTORE=/root/restore

FILEMONGODB=$DIRBACKUP/$FF
FILEMONGODBWORK=$DIRRESTORE/$FF


echo ""
echo ""
echo "*****************************************************************************************************"
echo "*** MONGODB RESTORE DATABASE !!!!!   SEI SICURO DI VOLER RIPRISTINARE IL DATABASE '$DATABASENAME' ? " 
echo "File = $FILEMONGODB"
echo ""
echo "DIRBACKUP=$DIRBACKUP"
echo "DIRRESTORE=$DIRRESTORE"
echo "*****************************************************************************************************"

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

if [[ $risposta == "Y" || $risposta == "y" ]]; then

  if [[ $DIRRESTORE ]]; then
    rm -R $DIRRESTORE/*
  fi

  mkdir $DIRRESTORE

  cd $DIRRESTORE

  cp $FILEMONGODB $FILEMONGODBWORK

  echo "1) DECRIPTING : " + $FILEMONGODBWORK

  sleep 1

  mcrypt -d -f /root/batch/cfgfiles/mycfg.ini $FILEMONGODBWORK

  sleep 1

  rm $FILEMONGODBWORK

  getfirstfile
  FILEENCRYPTED=$myresult

  echo "1-OK) -> FILE ENCRYPTED: " $FILEENCRYPTED
  echo ""

  sleep 1

  if [[ "$FILEENCRYPTED" ]]; then

    echo "2) EXTRACTING " $FILEENCRYPTED
    echo ""

    sudo tar xvfz $FILEENCRYPTED 

    sleep 1

    rm $FILEENCRYPTED

    sleep 1

    getfirstfile
    DIRDATABASE=$myresult

    echo "2B) -> Extracted: " $DIRDATABASE

    # Restore

    OPTDB="$DATABASENAME"".*"
    echo "OPTDB=" $OPTDB

    echo "3) RESTORE MONGODB DATABASE: " mongorestore --nsInclude $OPTDB  $DIRDATABASE


    sleep 5 

    mongorestore --nsInclude $OPTDB $DIRDATABASE

  fi 

  echo "Fine"

fi


