#!/bin/bash
## Wolfram Schlich <wolfram@schlich.org>

## program settings
prg_name="Mail-Archive"
prg_ver="0.1.5-20030525"
prg_copyright="(c) 2003 Wolfram Schlich <wolfram@schlich.org>, GPL'ed"
prg_self="${0##*/}" # like "basename $0"

## helper functions
function my_timestamp() { ## YYYMMDD-HHMMSS
	date +%Y%m%d-%H%M%S
}

## generic settings
start_time="$(my_timestamp)"
hostname="$(hostname -f)" # BSD: hostname, Linux: hostname -f

## prefs
mailfile_maxsize="4096k" # 4MB
maildir="${HOME}/mail"
archdir="${HOME}/mail.archive"
datefmt="%Y%m%d"
comp_prg="gzip --best -c" # or e.g. "bzip2 --best -c"
debug="no"
## functions
function my_archive() {
	local mailfile="$1" archfile archfile_dir
	test "${debug}" = "yes" && echo "mailfile: ${mailfile}"

	archfile="${mailfile}.$(date +${datefmt}).gz"
	test "${debug}" = "yes" && echo "archfile: ${archfile}"

	archfile_dir="${archdir}/${archfile}"
	archfile_dir="${archfile_dir%/*}" # get dirname
	test "${debug}" = "yes" && echo "archfile_dir: ${archfile_dir}"

	if [ ! -d "${archfile_dir}" ]; then
		echo "*** archfile_dir ${archfile_dir} does not exist - creating..."
		if ! mkdir -p "${archfile_dir}"; then
			echo "!!! cannot create archfile_dir ${archfile_dir} --- aborting."
			exit 1
		fi
	fi

	echo "<<< ${mailfile}"
	echo ">>> ${archfile}"

	if ! ${comp_prg} "${maildir}/${mailfile}" >"${archdir}/${archfile}" 2>/dev/null; then
		echo "!!! cannot compress mailfile ${maildir}/${mailfile} to archfile ${archdir}/${archfile} --- aborting."
		exit 1
	fi
	if ! rm -f "${maildir}/${mailfile}" 2>/dev/null; then
		echo "!!! cannot remove mailfile ${maildir}/${mailfile} --- aborting."
		exit 1
	fi
	if ! touch "${maildir}/${mailfile}" 2>/dev/null; then
		echo "!! cannot touch mailfile ${maildir}/${mailfile} --- aborting."
		exit 1
	fi

	echo
}
## start up
umask 077
echo "*** ${prg_name} ${prg_ver} started at ${start_time}."
echo "--- maildir: ${maildir}"
echo "--- archdir: ${archdir}"
echo
if [ ! -d "${maildir}" ]; then
	echo "!!! maildir ${maildir} does not exist --- aborting."
	exit 1
fi
if [ ! -d "${archdir}" ]; then
	echo "*** archdir ${archdir} does not exist --- creating."
	if ! mkdir -p "${archdir}" >/dev/null 2>&1; then
		echo "!!! cannot create archdir ${archdir} --- aborting."
		exit 1
	fi
fi
for f in $(find "${maildir}" -type f -size +${mailfile_maxsize} \( -not -iname "*.gz" -not -iname "*.bz2" -not -iname ".*" \) -printf "%P\n"); do
	my_archive "${f}"
done
echo "*** finished --- exiting."
