#!/bin/sh

case $1 in
    start )
	# Checkout original package to SOURCE/ORIG/repo/package:
	rm -rf SOURCE
	mkdir -p SOURCE/ORIG
	cd SOURCE/ORIG
	# This line extracts "link" tag and its two arguments:
	osc co $(grep '<link' ../../_link | sed 's/<link//;s/>//;s/project=//;s/package=//;s/["'\'']//g' )
	cp -a */*/* ..
	cd ..
	# Import all patches using quilt:
	# This line extracts "apply" tag and its argument:
	for PATCH in $(grep '<apply' ../_link | sed 's/<apply//;s/\/>//;s/name=//;s/["'\'']//g' ) ; do
	    # Let quilt apply patches and gets version control:
	    quilt import -p0 ../$PATCH
	    quilt push
	done
	echo "Done."
	echo "Please go to the SOURCE dir and make any changes using quilt patch management tool."
	echo "Add new patches with \"quilt new\", use refresh as \"quilt refresh -p0\"!"
	;;
    stop )
	cd SOURCE
	# Refresh patches (user should do it, but it's safe to do it again):
	quilt refresh -p0
	# Copy everything except "series" back:
	rm -f patches/*~
	cp -a patches/*.* ..
	# And this is an ugly command updating _link file with an actual patch list,
	# which is located in the series file:
	sed -i 's/\(<link .*\)\/>/\1>\n<patches>\n<\/patches>\n<\/link>/\n' ../_link
	sed <patches/series 's/ -p0//;s/.*/    <apply name="&" \/>/' >_link.ins
	sed -i '
	/<patches>/{
	    i\
  <patches>
	    r _link.ins
	    a\
  </patches>
	}
	/<patches>/,/<\/patches>/d
' ../_link
	rm _link.ins
	echo "Done."
	echo "Now you can remove SOURCE directory and call \"osc addremove ; osc ci\"."
	;;
    * )
	echo "Usage: oscquilt ( start | stop )"
	exit 1
	;;
esac
