#!/bin/sh
#
# create [-m maintainer] package [...]
#
# Create an ia32-libs package source

set -e

if [ "$1" = "-m" ]; then
  MAINTAINER="$2"
  echo >maintainer "$MAINTAINER"
  shift
  shift
fi

DEBS="$@"

TOOLDIR="/usr/lib/ia32-libs-tools"

if [ -e debian/rules ]; then
  echo "debian/rules already exists. Please start with an empty dir."
  exit 1
fi

mkdir -p debian
cp "$TOOLDIR/rules" debian/
echo >packages "$DEBS"
"$TOOLDIR/fetch" $DEBS

if ! [ $(echo *.dsc | wc -w) -eq 1 ]; then
  echo "More than one source package. Please create seperate packages."
  exit 1
fi

dpkg-source -x *dsc

SOURCE="$(echo *dsc | cut -d_ -f1)"
VERSION=$(cd $SOURCE-*/ && dpkg-parsechangelog | grep-dctrl "" -s Version -n)
ORIGMAINT="$(grep-dctrl "" $SOURCE-*/debian/control -s Maintainer -n | head --lines 1)"
ORIGUP="$(grep-dctrl "" $SOURCE-*/debian/control -s Uploaders -n | head --lines 1)"

if [ -z "$MAINTAINER" ]; then
  MAINTAINER="$ORIGMAINT"
fi
#UPLOADERS="$(echo "$UPLOADERS, $ORIGMAINT, $ORIGUP" | sed 's/^, //' | sed 's/, $//' | sed 's/, ,/,/g')"

case "$SOURCE" in
    glibc|gcc-*|alsa-lib|ncurses|zlib) ARCHS="ia64"; RENAME_FLAGS="--arch ia64";;
    *) ARCHS="amd64 ia64";;
esac

cat >debian/control <<EOF
Source: ia32-$SOURCE
Section: libs
Priority: extra
Maintainer: $MAINTAINER
Uploaders: $UPLOADERS
Build-Depends: ia32-libs-tools (>= 8), debhelper (>= 5)
Standards-Version: 3.7.3
EOF

for DEB in $DEBS; do
  cat >>debian/control <<EOF

Package: $("$TOOLDIR/mangle" $RENAME_FLAGS --rename "$DEB")
Architecture: $ARCHS
Description: ia32-libs conversion
EOF
  if [ -r "$TOOLDIR/hooks/$DEB.hook" ]; then
    cp "$TOOLDIR/hooks/$DEB.hook" debian
    chmod a+x "debian/$DEB.hook"
  fi
done

# Unpack changelog and add entry
cp "$SOURCE"-*/debian/changelog* debian
if [ -e "debian/changelog.gz" ]; then
  gunzip "debian/changelog.gz"
fi
if [ -e "debian/changelog.Debian.gz" ]; then
  gunzip "debian/changelog.Debian.gz"
fi
if [ -e "debian/changelog" ]; then
  CHANGELOG="debian/changelog"
fi
if [ -e "debian/changelog.Debian" ]; then
  CHANGELOG="debian/changelog.Debian"
fi

export DEBFULLNAME="Debian ia32-libs Team"
export DEBEMAIL="pkg-ia32-libs-maintainers@lists.alioth.debian.org"
dch -b --preserve --multimaint --mainttrailer --newversion "${VERSION}~@VERSION@" "Automatic conversion from i386 by ia32-libs-tools (@VERSION@)"
sed -i "s/^$SOURCE/ia32-$SOURCE/" "$CHANGELOG"

# Debhelper compat level
echo 5 >debian/compat

rm -rf "$SOURCE"-*/
