#!/bin/bash

set -eo pipefail

if [ -z "$1" ] || [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
  echo "Usage: $0 maildir";
  exit
fi

if [ ! -d "$1" ]; then
  echo "No such directory: $1" >&2
  exit 1
fi

MAILDIR="$1"

echo "Gathering files ..." >&2
FILES="$(find "$MAILDIR" -type f | grep -E '(cur|new|tmp)/')"

echo "Finding gzips ..." >&2
for file in $FILES; do
  if [ "$(file $file | grep gzip | awk '{print $1}' | sed 's/:$//g' | sed 's/^$//g')" ]; then
     echo "Gunzipping $file";
     mv "$file" "$file.gz"
     gunzip "$file"
  fi
done
