#!/bin/bash -e
#     DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#                    Version 2, December 2004

# Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

# Everyone is permitted to copy and distribute verbatim or modified
# copies of this license document, and changing it is allowed as long
# as the name is changed.

#            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
#   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

#  0. You just DO WHAT THE FUCK YOU WANT TO.


# Author: Gautier Pelloux-Prayer <gautier@damsy.net>
# Date: January 2017
# Use this script to find emails difference between eml files and Geary
# This script expects to be invoked from a folder with a subdirectory eml/
# containing mails using EML format. You can export them from Icedove, using
# "Save as" procedure. You should provide the script user (first argument) and
# Geary account number (second argument) to comparing with these files.

if [ ! -d eml ]; then
	echo 'invalid folder, eml/ not found'
	exit 1
fi

user=${1:-$USER}
account_nb=${2:-1}


total=$(find eml -maxdepth 1 -type f | wc -l)

if [ ! -f eml.txt ] || [ $(cat eml.txt | wc -l) != "$((4 * total))" ] ; then
	(cd eml && rename 's/[^a-zA-Z0-9_\.\-]*//g' *)
	(cd eml && rename 's/^[\-\.]*//g' *)

	current=0
	while read file; do
		((++current)) ; printf "\r%.2f%% (%d / %d)" $((current * 100 / total)) $current $total

		adate="$(grep -i -- '^Date:' "$file" | head -n1 | tr -d '\n\r\t' | cut -d':' -f 2-)"
		message_id="$(grep -i -- '^Message-ID:' "$file" | head -n1 | tr -d '\n\r\t' | cut -d':' -f 2-)"
		subject="$(grep -i -- '^Subject:' "$file" | head -n1 | tr -d '\n\r\t' | cut -d':' -f 2-)"

		[ -z "$adate" ] && echo "date not found for $file"
		[ -z "$message_id" ] && echo "message_id not found for $file"
		[ -z "$subject" ] && echo "subject not found for $file"
		printf "%s\n%s\n%s\n%s\n" "$(basename $file)" "$adate" "$message_id" "$subject" >> eml.txt
	done <<< $(find eml -maxdepth 1 -type f)
fi

# obviously counts do not match overwise we would not be here
if [ ! -f geary.txt ]; then # || [ $(cat geary.txt | wc -l) != "$((total))" ]; then
	db_file="/home/$user/.local/share/geary/account_0${account_nb}/geary.db"
	if [ ! -f "$db_file" ]; then
		echo "invalid user and or account number: '$db_file' does not exist. Please use $0 <user> <account_number>"
		exit 1
	fi

	sqlite3 $db_file "select name from FolderTable"
	read folder_name
	sqlite3 $db_file "select m.id, date_field, m.message_id from MessageTable m, MessageLocationTable ml, FolderTable f where m.id == ml.message_id and ml.folder_id == f.id and f.name == '$folder_name'" > geary.txt
fi

curid=$(date +%H-%M-%S)

working_geary=${curid}geary.txt
working_eml=${curid}eml.txt

cp eml.txt $working_eml
cp geary.txt $working_geary

current=0
while read afile; do
	read adate
	read message_id
	read subject

	((++current)) ; printf "\r%.2f%% (%d / %d)\n" $((current * 100 / total)) $current $total

	if [ ! -z "$message_id" ] && grep -q "$message_id" $working_geary; then
		sed -i -e "0,/${message_id//\//\\\/}/{//d;}" $working_geary
		line=$(grep -Fn -- "$afile" $working_eml | head -n1 | cut -d ':' -f 1)
		sed -i "$line,$(($line + 3))d" $working_eml
	elif [ ! -z "$adate" ] && grep -q "$adate" $working_geary; then
		sed -i -e "0,/$adate/{//d;}" $working_geary
		line=$(grep -Fn -- "$afile" $working_eml | head -n1 | cut -d ':' -f 1)
		sed -i "$line,$(($line + 3))d" $working_eml
	else
		echo "Cannot find '$afile' in geary"
	fi
done < eml.txt

mkdir $curid

if [ -s "$working_eml" ]; then
	echo "Still in eml folder:"
	cat $working_eml
	cp $working_eml $curid
fi

if [ -s "$working_geary" ]; then
	echo "Still in Geary:"
	cat $working_geary
	cp $working_geary $curid
fi

rm -d $curid 2>/dev/null

rm $working_geary
rm $working_eml
