#!/bin/bash

tmpHPSUM=""
if [ -f hpsum.ini ];then 
	tmpHPSUM=`grep -E "^temp_dir" hpsum.ini | awk -F= '{print $2"/HPSUM"}'`
fi
if [ "x$tmpHPSUM" = "x" ]; then
	tmpHPSUM=/tmp/HPSUM
fi

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

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

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

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 HP Smart Update Manager Repository cache delete script
echo                       -
echo Removing HP SUM cache files will require re-entering
echo all baseline locations, nodes and credentials.
echo                       -
echo This script should not be run while HP SUM is running.
echo                       -
# Look for HP SUM running
found=`ps -ef | grep -v grep | grep hpsum`
if [ "x$found" != "x" ]; then
  # run again to generate a clean list for the user to see
  ps -ef | grep -v grep | grep hpsum
  echo                       -
  echo ========================================================
  echo WARNING: HP SUM instances were found currently running.
  echo Please exit HP SUM using Logout and shutdown from the 
  echo browser running HP SUM or use \'hpsum 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 hpsum in the name (SIM)
  #pause_exit
fi

if [ $skip -eq 0 ]; then
  echo -n Are you sure you want to delete HP 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 $tmpHPSUM ]; then
  rm_temp_file baseline
  rm_temp_db_file hpsum.pdb
  rm_temp_db_file hpsum.pdb-wal
  rm_temp_db_file hpsum.pdb-shm
  rm_temp_db_file hpsum_remote.pdb
else
  echo No HP SUM temp directory found to delete at $tmpHPSUM.
fi


cmd=`dir -l $tmpHPSUM  |  grep -Eo "[[:digit:]]_[[:digit:]]_[[:digit:]]_[[:digit:]]"`
for i in $cmd
   do
	echo Removing directory $tmpHPSUM/$i
	rm -fr $tmpHPSUM/$i 
   done



pause_exit

