#! /bin/sh

_usage()
{
    cat << EOF
Usage: $prog [-p] dir list

-p    Use ptools and quilt, default is to use quilt import
dir   Directory containing patches
list  List of patches to apply
EOF
    exit 1
}

ptools=false

while getopts "p" c
do
    case $c in
	p) ptools=true;;
	\?) _usage
	    exit 1
	    break;;
    esac
done

shift `expr $OPTIND - 1`

if [ $# -ne 2 ]
then
    _usage
    exit 1
fi

dir=$1
list=$2

if [ ! -d $dir ]
then
    echo "$prog: Unable to open $dir"
    exit 1
fi

if [ ! -r $list ]
then
    echo "$prog: Unable to read from $list"
    exit 1
fi

for i in `cat $list`
do
    if [ ! -r $dir/$i ]
    then
	echo "$0: Unable to open $dir/$i"
	exit 1
    fi
    echo ""
    echo "$i"
    if $ptools
    then
	if pq_patch -Q $i -p 1 $dir/$i
	then
	    :
	else
	    echo "$0: Failed to apply $i"
	    exit 1
	fi
    else
	if quilt import -P $i -p 1 $dir/$i
	then
	    if quilt push
	    then
		:
	    else
		echo "$0: Failed to push $i"
	   	exit 1
	    fi
	else
	    echo "$0: Failed to import $i"
	    exit 1
        fi
    fi
    sleep 1
done

