#! /bin/bash -e

# This shell script cleans the Debianized source and makes a
# proper .orig upstream source in a parallel directory.  The script
# must be invoked from the Debianized source's top directory.

SELF=mkorig
DEBONLY=( debian helper )

function usage {
  cat <<END
usage: debian/$SELF [-fh]
    -f  force a new .orig even if it means overwriting an old one
    -h  print this help message and exit
END
}

# Require that the script be invoked from the top source directory.
if [[ ! ( $PWD/debian/$SELF -ef $0 ) ]] ; then
  echo 1>&2 "$0: must be invoked from the top source directory"
  exit 1
fi

# Read options from the command line.
FORCE=0
HELP=0
while getopts 'fh' OPT ; do
  [[ $OPT == 'f' ]] && FORCE=1
  [[ $OPT == 'h' ]] && HELP=1
  if [[ $OPT == '?' ]] ; then
    usage 1>&2
  fi
done

if [[ $HELP == 1 ]] ; then
  usage
else

  # Ensure that the target .orig does not already exist.
  DIRNAME=$(  dirname  $PWD )
  BASENAME=$( basename $PWD )
  ORIG=$DIRNAME/$BASENAME.orig
  if [[ $FORCE == 0 && -e $ORIG ]] ; then
    echo 1>&2 "$0: $ORIG already exists (use -f to force)"
    exit 1
  fi

  # Clean the source and prepare the target.
  fakeroot debian/rules clean >/dev/null
  rm -Rf $ORIG
  mkdir  $ORIG

  # Copy to the target.
  for A in $( find . -mindepth 1 -maxdepth 1 ) ; do
    BNA=$( basename $A )
    ISORIG=0
    for I in $( seq 0 $(( ${#DEBONLY[*]} - 1 )) ) ; do
      [[ $( basename $A ) == ${DEBONLY[$I]} ]] && ISORIG=1
    done
    if [[ $ISORIG == 0 ]] ; then
      cp -a $A $ORIG/$BNA
    fi
  done

fi

