#!/bin/bash
#
# Delete Tizen older directories based on policy
#

remove_old() {
path=$1
maxage=$(($2 * 86400))
dirlist=`find $path -type d -regextype posix-awk -regex $PURGE_PATTERN -not -regex '.*-base.*'`
now=`date +"%s"`
for dir in $dirlist; do
  dirn=`dirname $dir`
  basen=`basename $dir`
  latest=$dirn/latest
  if [ -L $latest ]; then
    link=`readlink $latest`
    [ $basen = ${link%/} ] && continue
  fi
  tsext="${dir##$path*/*_}"
  timestamp="${tsext%%.*}"
  reltime=`date --date=$timestamp +"%s"`
  if [ $((now - reltime)) -gt $maxage ]; then
    echo "# Remove $dir"
    [ $PURGE_DRY_RUN -eq "0" ] && rm -fr $dir
  fi
done
}

[ $PURGE_DRY_RUN != 0 ] && echo "Dry run, nothing will be deleted"

read -a paths <<< $PURGE_PATHS
read -a ages <<< $PURGE_AGES
for ((i=0;i<${#paths[@]};i++)); do
  remove_old ${paths[$i]} ${ages[$i]}
done
