#!/bin/bash

set_path ()
{
cachePath=""
if [ -f $1 ];then
        cachePath=`grep -E "^temp_dir" $1 | awk -F= '{print $2"/$2"}'`
fi
if [ "x$cachePath" = "x" ]; then
        cachePath=$3
fi
echo "$cachePath"
}
tmpSUM=$(set_path hpsum.ini HPSUM /tmp/HPSUM)
echo "cleancahepath is $tmpSUM"
tmp8SUM=$(set_path sum.ini sum /var/tmp/sum)
echo "cleancahepath is $tmp8SUM"

pause_exit ()
{
  if [ $skip -eq 0 ]; then
    echo Press Enter to continue
    read foo
  fi
  exit 0
}

rm_temp_file ()
{
  if [ -f $1/$2 ] || [ -d $1/$2 ]; then
    echo Removing: $1/$2
    rm -rf $1/$2
  else
    echo $1/$2 already deleted
  fi
}

rm_temp_db_file ()
{
  echo Removing: $2
  dbfile=`find $1 -name $2`
  echo $dbfile
  find $1 -name $2 -type f -delete
}

clean_db_dir()
{
cmd=`dir -l $1  |  grep -Eo "[[:digit:]]_[[:digit:]]_[[:digit:]]_[[:digit:]]"`
for i in $cmd
   do
        echo Removing directory $1/$i
        rm -fr $1/$i
   done
}


if [ "x$1" = "x-h" ]; then
  echo syntax: $0 [-y] [-h]
  echo         -y = continue without pausing for prompts
  exit 0
fi
if [ "x$1" = "x-y" ]; then
  skip=1
else
  skip=0
fi

echo Smart Update Manager Repository cache delete script
echo                       -
echo Removing SUM cache files will require re-entering
echo all baseline locations, nodes and credentials.
echo                       -
echo This script should not be run while SUM is running.
echo                       -
# Look for SUM running
found=`ps -ef | grep -v grep | grep sum_service`
if [ "x$found" != "x" ]; then
  # run again to generate a clean list for the user to see
  ps -ef | grep -v grep | grep sum_service
  echo                       -
  echo ========================================================
  echo WARNING: SUM instances were found currently running.
  echo Please exit SUM using Logout and shutdown from the
  echo browser running SUM or use \'smartupdate shutdownengine\'
  echo before calling clean-cache to prevent file conflicts.
  echo ========================================================
  echo                       -
  # This is now only a warning because it might be a script or other process with smart update manager in the name (SIM)
  #pause_exit
fi

if [ $skip -eq 0 ]; then
  echo -n Are you sure you want to delete SUM cache files? [y or n] :
  read ok

  if [ "x$ok" != "xy" ]; then
    echo Exiting without deleting any files.
    pause_exit
  fi
fi

if [ -d $tmpSUM ]; then
  rm_temp_file $tmpSUM baseline
  rm_temp_db_file $tmpSUM hpsum.pdb
  rm_temp_db_file $tmpSUM hpsum.pdb-wal
  rm_temp_db_file $tmpSUM hpsum.pdb-shm
  rm_temp_db_file $tmpSUM hpsum_remote.pdb
  clean_db_dir $tmpSUM
fi

if [ -d $tmp8SUM ]; then
  rm_temp_file $tmp8SUM baseline
  rm_temp_file $HOME    sum
  rm_temp_db_file $tmp8SUM sum.pdb
  rm_temp_db_file $tmp8SUM sum.pdb-wal
  rm_temp_db_file $tmp8SUM sum.pdb-shm
  rm_temp_db_file $tmp8SUM sum_remote.pdb
  clean_db_dir $tmp8SUM
else
  echo No SUM temp directory found to delete at $tmp8SUM.
fi



pause_exit



