#!/bin/sh

set -e
set -u

# Run this script from the top-level source directory *after a build*
# to update debian/install and debian/links.  This should be done with
# a new upstream release when a file and/or a component is being
# added/removed and dh_install/dh_missing fail.

# My apologies to Eric who wrote this but it doesn't scale: for the
# gnustep-multiarch transition, I had to manually update install/links
# files in order to get a successful build so that I can run it to
# ensure these files correspond to the script's output.  It doesn't
# work with compat 13 either because the build will fail if a bundle
# is added/removed upstream.  It also doesn't work when there are
# joint releases of rsskit/grr.app where rsskit breaks ABI and the new
# grr.app version requires the new rsskit version (not a hypothetical
# example).  Some maintainers wouldn't want to install the new library
# version just to run this script; it's better to do what the script
# does programmatically in debian/rules, like we do for cenon.app or
# gorm.app (to name a few).

MULTIARCH=$(dpkg-architecture --query DEB_HOST_MULTIARCH)
base_dir=`pwd`
g_app="debian/grr.app"
GNUSTEP_SYSTEM_APPS="usr/lib/$MULTIARCH/GNUstep/Applications"
usrshare="usr/share/GNUstep"

cat <<EOF >$base_dir/$g_app.install.temp
usr/bin
debian/Grr.desktop usr/share/applications
Grr.png            usr/share/pixmaps/GNUstep
usr/lib/*/GNUstep/Applications/Grr.app/[!R]*
EOF

rm -f $base_dir/$g_app.links.temp

append1()
{
    cd $base_dir/debian/tmp
    for i in `ls -A -d --color=never $GNUSTEP_SYSTEM_APPS/Grr.app/Resources/$1`
    do
	echo "$i $usrshare/Grr.app" >>$base_dir/$g_app.install.temp
	echo "$usrshare/Grr.app/`basename $i` $i" >>$base_dir/$g_app.links.temp
    done
}

append2()
{
    cd $base_dir/debian/tmp
    for i in `ls -A -d --color=never $GNUSTEP_SYSTEM_APPS/Grr.app/Resources/$1`
    do
	if test -d $base_dir/debian/tmp/$i
	then
	    echo "$i/Resources/* $usrshare/Grr.app/`basename $i`" >>$base_dir/$g_app.install.temp
	    echo "$usrshare/Grr.app/`basename $i` $i/Resources" >>$base_dir/$g_app.links.temp
	    for j in ls `ls -A -d --color=never $i/*`
	    do
		if test -f $base_dir/debian/tmp/$j
		then 
		    echo "$j" >>$base_dir/$g_app.install.temp
		fi
	    done
	fi
    done
}

append1 *.tiff
append1 *.plist
append1 *.lproj
append2 *.grrc
append2 *.grrdb

sed -e "s|lib/$MULTIARCH|lib/\${DEB_HOST_MULTIARCH}|g" \
    $base_dir/$g_app.install.temp > $base_dir/debian/install
sed -e "s|lib/$MULTIARCH|lib/\${DEB_HOST_MULTIARCH}|g" \
    $base_dir/$g_app.links.temp > $base_dir/debian/links
