#!/bin/bash
set -e
user=$(whoami)
if [ "$user" != "www-data" ];
	then
		echo 'Error: run as www-data'
		exit 1
	fi

if [ -f /tmp/repack-archive-logs.lock ]; then
	if [ "$(ps -p `cat /tmp/repack-archive-logs.lock` | wc -l)" -gt 1 ]; then
		echo repack-archive-logs process is still running
		exit 1
	else
		# process not running, but lock file not deleted?
		rm /tmp/repack-archive-logs.lock
	fi
fi
echo $$ >/tmp/repack-archive-logs.lock

function signalExitCaught() {
 #Clean up in-process repack
 if [ "${file}" ]; then
   if [ -f "${file}" -a -f "${file%gz}xz" ]; then
     echo cleaning up in-process repack ${file%gz}xz
     rm ${file%gz}xz
   fi
 fi 
 exit 1
}

trap signalExitCaught INT QUIT TERM

for file in $(find /store/logs/ -mtime +60 -type f -name '*.gz'); do
    (gzip -dc "${file}" | xz -9e > "${file%gz}xz") && (touch --no-create --reference="${file}" "${file%gz}xz" && rm "${file}") || (rm "${file%gz}xz")
done

rm /tmp/repack-archive-logs.lock
exit 0