#!/bin/bash
set -e
set -u
CMD_RM="rm -f"
VAR_DIR=/home/edokumenty/public_html/apps/edokumenty
LOCK_FILE="/home/edokumenty/var/dirrotate-lock-file"
LOG_BACKUP="/var/log/backup_edokumenty"
DATESTART=$(date +"%Y-%m-%d %H:%M")


echo "Start: Czyszcenie folderów var ${DATESTART}"  >> ${LOG_BACKUP}/clear_log_tmp.log

function remove_lock_file()
{
        if [ -e "${LOCK_FILE}" ]; then
               ${CMD_RM}  "${LOCK_FILE}" || {
                        echo "Cannot remove lock file: ${LOCK_FILE}" >&2;
                        exit 4
                }
        fi
}
trap remove_lock_file SIGINT

if [ -e "${LOCK_FILE}" ]; then
echo "File lock found, another instance is running?" >&2;
exit 1
fi

touch "${LOCK_FILE}" || {
    echo "Cannot create lock file - exiting" >&2;
        exit 2
	}


for DIR in $(find "$VAR_DIR" -maxdepth 1 -mindepth 1 -type d -name "var*" | sort);do
    echo "usuwam pliki w $DIR/log" && $(find "$DIR/log/" -mindepth 1 -mtime +5 -type f -print0 | xargs -0 --no-run-if-empty rm -f)
done >> ${LOG_BACKUP}/clear_log_tmp.log

for DIR in $(find "$VAR_DIR" -maxdepth 1 -mindepth 1 -type d -name "var*" | sort);do
    echo "usuwam katalogi w $DIR/log" && $(find "$DIR/log/" -mindepth 1 -type d -empty | xargs --no-run-if-empty rm -rf)
done >> ${LOG_BACKUP}/clear_log_tmp.log

for DIR in $(find "$VAR_DIR" -maxdepth 1 -mindepth 1 -type d -name "var*" | sort);do
    echo "usuwam pliki w $DIR/tmp" && $(find "$DIR/tmp/" -mindepth 1 -mtime +2 -type f -print0 | xargs -0 --no-run-if-empty rm -f)
done >> ${LOG_BACKUP}/clear_log_tmp.log

for DIR in $(find "$VAR_DIR" -maxdepth 1 -mindepth 1 -type d -name "var*" | sort);do
    echo "usuwam katalogi w $DIR/tmp" && $(find "$DIR/tmp/" -mindepth 1 -type d -empty | xargs --no-run-if-empty rm -rf)
done >> ${LOG_BACKUP}/clear_log_tmp.log


remove_lock_file


DATEEND=$(date +"%Y-%m-%d %H:%M")
echo "Koniec: Czyszcenie folderów var ${DATEEND}" >> ${LOG_BACKUP}/clear_log_tmp.log

echo " "  >> ${LOG_BACKUP}/clear_log_tmp.log