#!/bin/bash

FILES_TO_KEEP=5

DIR=`dirname $0`
BACKUP_FOLDER=""
TMP=""

if [ -e "/opt/pos/.hardlock" ]; then
  TMP=`cat /opt/pos/.hardlock`
fi

if [ "$TMP" = "" ]; then
  echo "No /opt/pos/.hardlock found... maybe POS isn't running with an hardlock..."
  exit
else
  FF=`dirname $TMP`
  BACKUP_FOLDER="$FF/data/backups"
fi

if [ "$BACKUP_FOLDER" = "" ]; then
  echo "Can't find backup folder to put backups in... check why /opt/pos/.hardlock isn't created..."
  exit
fi

HRD_FOLDER=`echo $TMP | cut -f3 -d/`

if [ ! -d "/media/$HRD_FOLDER/pos" ]; then
  echo "Hardlock should be in /media/$HRD_FOLDER but isn't... aborting..."
  exit
fi

if [ ! -d "$BACKUP_FOLDER" ]; then
  mkdir -p "$BACKUP_FOLDER"
fi

if [ -e "/tmp/server_error.txt" ]; then
  echo "Can't backup to hardlock, /tmp/server_error.txt exists..."
  exit
fi

if [ -e "/tmp/server_db_error.txt" ]; then
  echo "Can't backup to hardlock, /tmp/server_db_error.txt exists..."
  exit
fi

"$DIR/backup" "$BACKUP_FOLDER" 1

COUNT=0

find "$BACKUP_FOLDER" -type f | grep "\.zip" | sort -n -r | while read -r file
do
  COUNT=$(($COUNT+1))

  if [ $COUNT -gt $FILES_TO_KEEP ]; then
    rm -rf "$file"
  fi
done

sync

echo "OK"

