#!/bin/bash
# ditto.cleanup.sh - rotate out older builds (win, osx, and linux both release and debug)
# This script is called by Jenkins thus:
#  export DITTO_SOURCE_ROOT=${WORKSPACE}/src
#  export DEVFILES_URL=devfiles.cbu.rackspace.net
#  export DEVFILES_FOLDER=/srv/devfiles/www/ditto
#  scp ${DITTO_SOURCE_ROOT}/tools/ditto.cleanup.sh jenkins@${DEVFILES_URL}:${DEVFILES_FOLDER}/bin/.
#  ssh jenkins@${DEVFILES_URL} "export DEVFILES_FOLDER=${DEVFILES_FOLDER} && chmod 755 ${DEVFILES_FOLDER}/bin/ditto.cleanup.sh && ${DEVFILES_FOLDER}/bin/ditto.cleanup.sh"

function bannerfun {
  mystr=$1
  for i in 1 2; do for ((x=1; x<${#mystr} + 7; x++)); do echo -n =; done; echo ''; done
  echo -n '== '; echo -n ${mystr}; echo ' =='
  for i in 1 2; do for ((x=1; x<${#mystr} + 7; x++)); do echo -n =; done; echo ''; done
}

bannerfun 'devfiles DITTO CLEANUP'

function cleanupditto {
  [[ $# -lt 1 ]] && echo "syntax: ditto.cleanup.sh <folder-name>" && return 0
  [[ ! -d $1 ]] && echo "Warning! folder-name $1 does not exist" && return 0
  lines2delete=$(( `ls $1/ditto* | wc -l` - 200))
  [[ ${lines2delete} -lt 0 ]] && echo "Warning! Nothing to rotate out this time (${lines2delete})." && return 0
  echo "Number of lines to delete: ${lines2delete}"
  for i in `ls $1/ditto* | head -${lines2delete}`; do echo "rotating off $i"; rm "$i"; done
}

[[ ! -d "${DEVFILES_FOLDER}" ]] && ( ls -lad ${DEVFILES_FOLDER}; echo "WARNING! Cannot find ${DEVFILES_FOLDER}" ) && exit 0
cd "${DEVFILES_FOLDER}" && for x in linux osx win linux/debug osx/debug win/debug; do echo "Cleaning up $x"; cleanupditto $x; done

