#!/bin/dash
# run this once only

run_in_my_dir() {
	mydir=$(readlink -f "$0")
	mydir=${mydir%/*}
	cd $mydir
}

###
[ $# -lt 2 ] && << EOF cat && exit
Usage: migrate fd700-pkg-dir fd700-patches-dir [migration-dir]
If not specified, migration dir is /tmp/migrated-pkg
EOF
PKG700="$(readlink -f "$1")"
PAT700="$(readlink -f "$2")"
MIGRATION_DIR=${3:-/tmp/migrated-pkg}

run_in_my_dir
mkdir -p $MIGRATION_DIR

find $PKG700 -type f | sed "s|$PKG700/||" | 
while read -r pkg; do
	src=$pkg
	PKGSUBDIR=${pkg%/*} pkg=${pkg##*/}
	[ $PKGSUBDIR = $pkg ] && PKGSUBDIR=""
	# simple pkg name breakdowns, we know our packages have compliant naming
	PKGBUILD=${pkg##*-} pkg=${pkg%-*};   [ $PKGBUILD = $pkg ] && pkg=""
	PKGARCH=${pkg##*-} pkg=${pkg%-*};    [ $PKGARCH = $pkg ] && pkg=""
	PKGVER=${pkg##*-} PKGNAME=${pkg%-*};
	[ -z "$PKGNAME" ] && PKGNAME=$PKGBUILD && PKGVER=1.0 && PKGBUILD=1 && PKGARCH=x86_64
	#echo #echo $PKGNAME^$PKGVER^$PKGARCH^$PKGBUILD
	
	echo migrating $PKGNAME
	TGT=$MIGRATION_DIR/$PKGSUBDIR/$PKGNAME	
	mkdir -p $TGT
	if [ -e $TGT/recipe ]; then
		TGT=$TGT-$PKGVER
		mkdir -p $TGT
		if [ -e $TGT/recipe ]; then
			TGT=$TGT-$PKGARCH-$PKGBUILD
			mkdir -p $TGT
		fi
	fi
	
	# copy and fix the recipe
	cp $PKG700/$src $TGT/recipe
	sed -i -e "2 iPKGVER=$PKGVER" -e "2 iPKGBUILD=$PKGBUILD" -e "2 iPKGARCH=$PKGARCH" $TGT/recipe
	
	# copy the extra files and fix recipe
	sed '/\$PATCHES_DIR/!d; s|.*\$PATCHES_DIR/||; s/[ \t].*$//;' \
	$TGT/recipe | sed "s|^|$PAT700/|" | xargs cp -t $TGT 2>/dev/null
	sed -i -e 's|\$PATCHES_DIR|\$CHROOT_DIR/tmp/pkg|' $TGT/recipe
	
done
