#!/bin/sh
TREES=~/.trees;
line_ifs='
'

# debug mode
# set -x

temp_file="$1";
if [ ! -f "$temp_file" ]; then
	dialog --msgbox "patch file not found" 12 40;
	exit 1;
fi

if [ ! -s $TREES ]; then
	dialog --msgbox "$TREES not found or empty, create it and fill with your local trees" 12 40;
	exit 0;
fi

t="$(grep "^+++" $temp_file | cut -f 2 -d ' ' | cut -f 1 | cut -f 2- -d '/' |
     head -n 1)";
if [ -z "$t" ]; then
	dialog --msgbox "This email doesn't looks like it contains a patch" 12 40;
	exit 0;
fi

patch_file=$(cat $temp_file | grep "^Subject:" | sed -e "s/Subject: //");
patch_file=$(echo $patch_file | sed -e "s/\[.*\] //g");
patch_file=$(echo $patch_file | sed -e "s/\ /_/g");
patch_file=$(echo $patch_file | sed -e "s/__/_/g");
patch_file=$(echo $patch_file | sed -e "s/'//g");
patch_file=$(echo $patch_file | sed -e "s/:/-/g");
patch_file=$(echo $patch_file | sed -e "s/-_/-/g");
patch_file=$(echo $patch_file | sed -e "s/_-/-/g");
patch_file=$(echo $patch_file | sed -e "s/--/-/g");
patch_file=$(echo $patch_file | dd conv=lcase 2>/dev/null);
patch_file="$patch_file.patch";

string="";
for i in $(cat $TREES); do
	string+="$i \"\" ";
done

tree=$(eval "dialog --stdout --menu \"Choose the tree\" 12 65 5 $string");
if [ -z "$tree" ]; then
	exit 1;
fi

cd $tree
mkdir -p patches;
quilt pop -a;
if [ $? = 1 ]; then
	dialog --msgbox "Couldn't pop all the patches" 12 40;
	exit 1;
fi
quilt delete $patch_file;
quilt push -a;
if [ $? = 1 ]; then
	dialog --msgbox "Failed to push the patches back" 12 40;
	exit 1;
fi

quilt import -P $patch_file -f $temp_file;
quilt push;
if [ ! $? = 0 ]; then
	dialog --msgbox "The patch doesn't applies" 12 40;
	exit 1;
fi


