#!/bin/bash
# This script will remove all by the latest file in your /p4/1/depots/ tree.
# It is designed to work with servers running with lbr.autocompress=1 set in the configurables.
export SDP_INSTANCE=${SDP_INSTANCE:-Undefined}
export SDP_INSTANCE=${1:-$SDP_INSTANCE}
if [[ $SDP_INSTANCE == Undefined ]]; then
   echo "Instance parameter not supplied."
   echo "You must supply the Perforce instance as a parameter to this script."
   exit 1
fi

replication=$($P4BIN configure show $SERVERID | grep lbr.replication | cut -d "=" -f 2)
retVal=$?
if [[ $retVal -ne 0 ]]; then
  exit 0
else
  replication=$(echo $replication)
fi

if [[ $replication == "shared" ]]; then
  exit 0
fi

if [[ -f /p4/${SDP_INSTANCE}/bin/skip_cache_clean.txt ]]; then
  exit 0
fi

AVAIL=$(df --output=avail /p4/${SDP_INSTANCE}/depots | tail -n 1)

# REQAVAIL is ~1TB in bytes
REQAVAIL=1000000000

if [[ -f /p4/${SDP_INSTANCE}/bin/cache_clean_reqavail.txt ]]; then
  REQAVAIL=$(cat /p4/${SDP_INSTANCE}/bin/cache_clean_reqavail.txt)
fi

if [[ $AVAIL -gt $REQAVAIL ]]; then
  exit 0
fi

ATIME=5

if [[ -f /p4/${SDP_INSTANCE}/bin/cache_clean_atime.txt ]]; then
  ATIME=$(cat /p4/${SDP_INSTANCE}/bin/cache_clean_atime.txt) 
fi

# Check to make sure that global shelves are enabled. If they are not, this script
# would most likely end up deleting someone's shelved files.
if [[ ! $(p4 -ztag -F %Value% configure show dm.shelve.promote) ]]; then
  echo "Global shelves are not enabled, aborting!"
  exit 1
fi

IFS=$'\n' depots=($(ls "/p4/${SDP_INSTANCE}/depots/"))
for depot in "${depots[@]}"
do
  if [[ !($depot =~ .*unload.*) && !($depot =~ .*spec.*) ]]; then
    find /p4/${SDP_INSTANCE}/depots/$depot/ -atime +${ATIME} -type f -exec rm {} \; & 
  fi
done
