#!/bin/sh

# Usage: dasource [-r REPOS] [PACKAGENAME ...]

# Originally from the MIT Athena 10 project.

# Creates or updates a checkout and source package for each listed
# PACKAGENAME, or for all regular packages if no PACKAGENAME is
# specified.

# If REPOS is specified, it is used in preference to the canonical
# Athena repository trunk.

# Package subdirectories are created in the cwd.  The source checkout
# will reside in PACKAGENAME/PACKAGENAME-VERSION and the source
# package will be created in PACKAGENAME.

set -e

die() {
  echo "$@" >&2
  exit 1
}

do_package() {
  dir=$1

  version=$(echo $dir | sed 's/[^-]*-//' | sed 's/\.alpha/~alpha/' | sed 's/\.rc/~rc/')
  upver=$(echo $version | sed 's/\(.*\)-\([^-]*\)/\1/')
  if dpkg --compare-versions "$upver" '>>' "20000000"; then
      # send to 0.0.x
      upver="0.0.$upver"
  fi
  if [ "$upver" = "$version" ]; then
      dver=0sage1
  else
      dver=0sage$(echo $version | sed 's/\(.*\)-\([^-]*\)/\2/')
  fi
  sver="$upver-$dver"

  # Extract the package name from the changelog
  pkgname=$(cd $dir && dpkg-parsechangelog | sed -n 's/Source: //p')

  # Rename the source checkout if necessary.
  correctdir=${pkgname}-$upver
  if [ $dir != $correctdir ]; then
    echo "Renaming $dir to $correctdir"
    mv $dir $correctdir
    dir=$correctdir
  fi

  # make sure we're running with a clean upstream
  (cd $dir && debuild clean)

  # If the version has a debian component then we need an orig archive.
  if [ $sver != $upver ]; then
    tarfile=${pkgname}_$upver.orig.tar.gz
    if [ ! -e $pkgname/$tarfile ]; then
        echo "Creating original source archive"
        (tar --exclude=.svn --exclude=CVS --exclude=debian $correctname -czf \
         $tarfile ${pkgname}-$upver)
    fi
  fi

  # Add a changelog entry updating to the current version number.
  (cd $dir && dch -v "$sver" "Build with new SAGE spkg $dir.spkg")

  # Build an unsigned package, ignoring version control subdirs in the source.
  echo "Creating source package"
  (cd $dir && DEB_AUTO_UPDATE_DEBIAN_CONTROL=yes debuild -S -i -I -sa -us -uc)
}

if [ $# -gt 0 ]; then
    do_package "$1"
fi
