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

#set -x
temp_file=$1;
if [ ! -f "$temp_file" ]; then
	echo "file [$temp_file] doesn't exists";
	exit 1;
fi

if [ ! -f "$TREES" ]; then
	dialog --msgbox "$TREES wasn't found. please fill it with your kernel trees" 12 40;
	exit 1;
fi

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

if [ -z "$string" ]; then
	dialog --msgbox "$TREES is empty, please fill with your kernel trees" 12 40;
	exit 1;
fi

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 patches"; 12 40;
	exit 1;
fi
quilt delete mutt-test.patch;
quilt import -P mutt-test.patch -f $temp_file;
if [ ! $? = 0 ]; then
	dialog --msgbox "couldn't import" 12 40;
	exit 1;
fi

quilt push;
if [ ! $? = 0 ]; then
	dialog --msgbox "couldn't push. the patch doesn't applies" 12 40;
	quilt delete mutt-test.patch;
	exit 1;
fi
files="$(quilt files)";
for i in $files; do
	cp $i $i.changed;
done

quilt pop;
quilt delete mutt-test.patch;
for i in $files; do
	vimdiff $i $i.changed;
	rm $i.changed;
done
quilt push -a;


