#!/bin/bash
[ -f /etc/profile.d/10-java-caching-proxy.sh ] && . /etc/profile.d/10-java-caching-proxy.sh

function showhelp {
                           echo -e "\nusage:  clean-container-state  [-g <ghn_home>] [-s <fileName>] [-h] \n"
               echo    "  ghn_home           = the gHN directory.\n"
               echo    "  fileName           = the filename for volatile state.\n"      
                       echo -e "  h                  = shows this help.\n"
}

while getopts "h:g:s:" opt; do
  case $opt in
        g) ghnhome=$OPTARG;;
    h) showhelp
       exit 0 ;;
    s) filename=$OPTARG;;

        :)  echo -e "\nERROR:option -$OPTARG requires an argument." >&2 ;
                                showhelp;
                                echo -e "\naborting.\n"
                                exit 1;;
        \?) echo -e "\nERROR:invalid option: -$OPTARG";
                        showhelp;
                        echo -e "\naborting.\n"
                        exit 1 >&2 ;;
  esac
done

if [ -z "$ghnhome" ]; then
        if [ -z "$GHN_HOME" ]; then
                echo -e "\nERROR:please specify the gHN directory (-g) or define the GHN_HOME env var." >&2
                showhelp
                echo -e "\naborting.\n"
                exit 1
        else
                ghnhome=$GHN_HOME
        fi
fi

echo -e "\nRemoving resource profiles from the Information System\n"

source "$ghnhome"/scripts/load-env "$ghnhome"


RETVAL=
if [ -z "$filename" ]; then
      java $JAVA_OPTS org.gcube.smartgears.utils.sweeper.ContainerSweeperClient -G"$ghnhome" 1>/home/gcube/SmartGears/containerState.log
      RETVAL=$?
else
      java $JAVA_OPTS org.gcube.smartgears.utils.sweeper.ContainerSweeperClient $filename -G"$ghnhome" 1>/home/gcube/SmartGears/containerState.log
      RETVAL=$?
      if [ $RETVAL -eq 0 ] ; then
          echo -e "\nvolatile state saved in $ghnhome/$filename"
      fi
fi

if [ $RETVAL -ne 0 ]; then
    echo -e "\nCould no correctly sweep the profiles from the Information System"
    echo -e "\nIn case of production deployment please contact the production admin"
    echo -e "\nIn case of dev deployment you can remove the state by hand by removing the $GHN_HOME/state folder"
else
    echo "Removing container state $ghnhome"
    # removing folder
    rm -rf $ghnhome/state
fi

exit $RETVAL

