#!/bin/bash
#-------------------------- =+- Shell script -+= --------------------------
#
# @file      dh_wraporig
# @date      Tue Apr 25 17:09:12 2006
# @brief
#
# CVS version control block - do not edit manually
#  $RCSfile: dh_wraporig,v $
#  $Source: /home/cvs/yoh/soft/dh_wraporig,v $
#
# Created: Tue Apr 25 17:09:12 2006
#  Commited: $Date: 2007-06-27 18:16:23 +0200 (mer, 27 jun 2007) $
#  Revision: $Revision: 333 $
#
#  Yaroslav Halchenko                                      CS@UNM, CS@NJIT
#  web:     http://www.onerussian.com                      & PSYCH@RUTGERS
#  e-mail:  yoh@onerussian.com                              ICQ#: 60653192
#
# DESCRIPTION (NOTES):
#
#  A very simple script to wrap provided files into a tarball.
#  Can be used to be called by uscan whenever new .xpi for a mozilla
#  extension is available from the upstream. Also it can be used to checkout
#  upstream source from SVN, given the version to get and the path. Or to
#  repackage .zip files into .tar.gz
#
# COPYRIGHT: Yaroslav Halchenko 2006, 2007
#
# LICENSE:
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the
#  Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#
# On Debian system see /usr/share/common-licenses/GPL for the full license.
#
#-----------------\____________________________________/------------------
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
# CVS version control block - do not edit manually
WRO_SVN_ID='$Id: dh_wraporig 333 2007-06-27 16:16:23Z yoh-guest $'
WRO_SVN_REV='$Revision: 333 $'
WRO_SVN_DATE='$Date: 2007-06-27 18:16:23 +0200 (mer, 27 jun 2007) $'
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###

set -e

############
# Defaults #
############

# repackage version
wro_version=0.1.${WRO_SVN_REV//[A-Za-z :\$]/}

#
# modifications which need to be performed on the sources
#
# which files to remove. $delete_files might be a string
#  or an array
delete_files=''

# additional tar parameters for instance to exclude some files
# alternative to 'delete_files' which operates at all levels of
# hierarchy
additional_tar_params='--exclude *~'

# suffix for the repackaged tarball such as ~dfsg
# NOTE: debian/watch has to be adjusted to mangle debian version,
# eg
#   opts="dversionmangle=s/~dfsg\.\d+$//"
suffix_out=

# suffix_version_out would be computed later
# if not defined here
suffix_version_out=

upstream_version=
source_name=
post_command=svn-upgrade
uupdate_command=uupdate
dest_dir="../tarballs"
patches_list_file=debian/patches/00list

readme_file=debian/README.Debian-source
additional_readme_lines=
additional_readme_files=

# Miscelaneous flags
do_orig_symlink=
do_delete_originals=
do_create_readme=
do_uupdate=

print_help()
{
print_version
cat << EOT

Wrap original upstream archive into a tarball, or repackage upstream
archive optionally removing specified unwanted material (usually
Non-DFSG compliant), and finally call a specified command (if any).

Usage:
  $0 [OPTIONS] <package>

  Where <package> is a tarball fetched from online.

Options:
  -h, --help
    Print this help and exit.

  -V, --version
    Print version information and exit.

  -D, --delete-originals
    Delete original <package> file.

  -l, --orig-symlink
    Create .orig.tar.gz symlink. If post_command is defined
    that would not be necessary.

  -R, --create-readme-source
    Create debian/README.source to be installed along with
    the package to include the description of performed
    actions

  -d <files>, --delete-files <files>
    Space separated list of files to be removed.

  -s <name>, --source-name <name>
    Explicitly specified name of the source.

  -c <command>, --command <command>
    Command to execute on generated file.

  --upstream-version <version>
    Just to pass to command

  --uupdate
    Run uupdate after creating the new tarball
    If --create-readme-source is enabled, it will be created
    in the NEW directory (instead of the current one)
EOT
}

print_version()
{
cat << EOT
dh_wraporig (AKA repackage) $wro_version
Copyright (C) 2006-2007 Yaroslav Halchenko <debian@onerussian.com>
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

EOT
}

#
#
[ -f debian/dh_wraporig.local ] && source debian/dh_wraporig.local
# this script is a joint between dh_wraporig and repackage, so
# read both config files
[ -f debian/repackage.params ] && source debian/repackage.params

# for compatibility with older naming of variables -- asign if they got
# defined in .local
dest_dir=${ddir:-${dest_dir}}
source_name=${sname:-${source_name}}
post_command=${call:-${post_command}}

################################
# Commandline options handling #
################################

# Parse commandline options (taken from the getopt examples from the
# Debian util-linux package).
# Note that we use `"$@"' to let each command-line parameter expand to
# a separate word. The quotes around `$@' are essential!  We need
# CLOPTS as the `eval set --' would nuke the return value of getopt.
CLOPTS=`getopt -o h,V,l,R,D,s:,d:,c: --long help,version,source-name:,orig-symlink,delete-originals,upstream-version:,delete-files:,command:,uupdate -n '$0' -- "$@"`

if [ $? != 0 ] ; then
    echo "Terminating..." >&2
    exit 1
fi

# Note the quotes around `$CLOPTS': they are essential!
eval set -- "$CLOPTS"

while true ; do
    case "$1" in
        -h|--help) print_help; exit 0;;
        -V|--version) print_version; exit 0;;
        -c|--command) shift; post_command=$1; shift;;
        -l|--orig-symlink) shift; do_orig_symlink=1;;
        -R|--create-readme-source) shift; do_create_readme=1;;
        -s|--source-name) shift; source_name="$1"; shift;;
        -d|--delete-files) shift; delete_files="$1 $delete_files"; shift;;
		-D|--delete-originals) shift; do_delete_originals=1;;
        --upstream-version) shift; upstream_version="$1"; shift;;
        --uupdate) shift; do_uupdate=1;;
        --) shift ; break ;;
        *) echo "ERROR: Internal error! ($1)"; exit 1;;
    esac
done

if [ -z "$upstream_version" ]; then
	echo "ERROR: Please provide upstream version, so I didn't have to guess"
	exit 1;
fi

if [ -z "$source_name" ]; then
	echo "WARNING: Source name wasn't given -- trying to guess"
	source_name=`grep -h ^Source: debian/control control 2>/dev/null | awk '{print $2;}'`
	if [ -z $source_name ]; then
		echo "ERROR: Couldn't guess -- must be no {debian/,}control file"
		exit 1
	fi
	echo "Source name: $source_name"
fi

work_dir="${source_name}-${upstream_version}"
debian_package_prefix="${source_name}_${upstream_version}"

fname=$1
full_fname=`readlink -f "$fname"`
ofile="${work_dir}.tar.gz"

# Define file identity which might be reported into README
file_identity=$fname
which md5sum > /dev/null && file_identity="md5:"$(md5sum "$fname")

# remove directory if such exists -- must be leftovers...
rm -rf "$work_dir"

# handle different sources. 1st it is just SVN checkout
if   [[ "$source" =~ svn\ export.* ]]; then
	readme_lines+="* Exported files from VC using\n"
	readme_lines+=" `eval echo ${source}`\n"
    rm -rf "$full_fname"
	readme_lines+="* Provided file $fname was discarded.\n"
    eval $source ${work_dir}
elif [[ "$source" =~ repack ]] || [ ! -z "$delete_files" ]; then
	tmpdir=tmpdir$$
	mkdir $tmpdir
	echo -ne "Extracting original sources..."
	# extract from known archives
	if   [[ "$fname" =~ .*\.\(zip\|jar\)$ ]]; then
		unzip -q -d $tmpdir $1
	elif [[ "$fname" =~ .*\.tar\.gz$ ]]; then
		tar -xzf "$fname" -C $tmpdir
	elif [[ "$fname" =~ .*\.tar\.bz2$ ]]; then
		tar -xjf "$fname" -C $tmpdir
	else
		echo "\rERROR: Don't know how to extract from $fname"
		return 1
	fi
	echo -e "\rFiles extracted successfully           "
	readme_lines+="* Extracted files from\n $file_identity\n"
	# move/rename
	if [ x`/bin/ls $tmpdir/ | wc -l` = x1 ]; then
        # there was a directory - just move it under
        # appropriate name
		mv $tmpdir/* "$work_dir"
		rmdir $tmpdir
	else
        # there seems to be multiple files - rename $tmpdir
		mv $tmpdir "$work_dir"
	fi
elif [ ! -z "$source" ]; then
	echo "ERROR: Do not know how to handle source $source"
	exit 1
else
	# Otherwise simply wrap full original source into tarball
	readme_lines+="* Wrapped into a gzipped tarball provided file\n"
	readme_lines+=" ${file_identity}\n"
	mkdir "$work_dir"
	mv $* $work_dir
fi

# Delete some files if that was requested
if [ ! -z "${delete_files[*]}" ]; then
    # since $delete_files pattern might be a bit obscure
    # lets just cd into
	echo -n "Deleting requested files/directories"
	(builtin cd $work_dir ; eval rm -rf ${delete_files[*]} )
	echo -e "\rRequested files/directories has been deleted"
	readme_lines+="* Removed following files/directories:\n"
	readme_lines+=" ${delete_files[*]}\n"
	if [ -z "$suffix_out" ]; then
		echo "WARNING: Please provide suffix to use. Such alternation must be noted"
		echo "         in the package version (dfsg is the one commonly used)"
	fi
fi

# if suffix_version was defined - we need to version it
if [ ! -z "$suffix_out" ] && [ -z "$suffix_version_out" ]; then
	suffix_version_out=${suffix_out}.1
fi

# Create a tarball
output_fname="${work_dir}${suffix_version_out}.tar.gz"
output_full_fname="$dest_dir/${output_fname}"
orig_full_fname="$dest_dir/${debian_package_prefix}${suffix_version_out}.orig.tar.gz"

if [ ! -z "$additional_tar_params" ]; then
	readme_lines+="* Additional parameters for tar on tarball creation were:\n"
	readme_lines+="  $additional_tar_params\n"
fi

echo -ne "Creating tarball..."
tar $additional_tar_params -cf- "$work_dir" | gzip -9 > "$output_full_fname" 
rm -rf "$work_dir"
echo -e "\rResult saved as '$output_full_fname'. Enjoy"

# Create symlink if it was requested
if [ ! -z "$do_orig_symlink" ]; then
	echo "Symlink created at '$orig_full_fname'. Enjoy"
	ln -sf "$output_fname" "$orig_full_fname"
fi

# Delete original file if it was requested
if [ ! -z "$do_delete_originals" ]; then
	rm -f "$full_fname"
fi

# Run post_command if any was assigned
if [ ! -z "$post_command" ]; then
	params="--upstream-version $upstream_version$suffix_version_out"
	$post_command $params "$output_full_fname"
	readme_lines+="\n* Afterwards command '$post_command' was run"
fi

# Run uupdate if requested
if [ ! -z "$do_uupdate" ]; then
	params="--upstream-version $upstream_version$suffix_version_out"
	$uupdate_command $params "$output_full_fname"
	readme_lines+="\n* Afterwards command '$uupdate_command' was run"
fi

# Create debian/README.Debian-source
if [ ! -z "$do_create_readme" ]; then

	if [ -f $patches_list_file ]; then
		readme_lines+="\n\nAdditional information:"
		readme_lines+="\n* Following patches were present to be applied to the original source\n"
		readme_lines+=" at build time\n"
		readme_lines+="`cat $patches_list_file`"
	fi

	if [ ! -z "$do_uupdate" ]; then
		readme_file="../${source_name}-$upstream_version$suffix_version_out/$readme_file"
	fi
	readme_dir="`dirname $readme_file`"
	if [ ! -d "$readme_dir" ]; then
		echo "ERROR: Can't find $readme_dir directory to create $readme_file"
		exit 1
	fi

	cat >| $readme_file <<EOT
README on source packaging of $source_name:
--------------------------------------------------------------

The source tarball of the package was generated by
dh_wraporig v.$wro_version script which
can be obtained from alioth's exppsy project repository:
http://svn.debian.org/wsvn/pkg-exppsy/tools/dh_wraporig

For this package dh_wraporig performed following actions:
EOT
	echo -e "$readme_lines" >> $readme_file
	echo -e "$additional_readme_lines" >> $readme_file
	[ ! -z "$additional_readme_files" ] && \
		cat $additional_readme_files >> $readme_file
fi
