#!/bin/bash

# Copyright, license and documentation below

# List of commands used
CMD_REALPATH="readlink -f";

#############
# functions #
#############

usage() {
	[ -n "$1" ] && echo "ERROR: $1" && echo
	echo "Usage:"
	echo "  $(basename $0) -{VHMWCRQ|A|h} {-c | [-p pkg] topdir}"
	echo
	echo "  At least one parameter must be present."
	echo
	echo "  Parameters:"
	echo "  -V       - debian/control: add/fix _V_cs-(Git|Browser) fields;"
	echo "             remove XS-Vcs-(Svn|Git|Browser) fields"
	echo "  -H       - debian/control: add _H_omepage field; remove"
	echo "             pseudo-field Homepage"
	echo "  -M       - debian/control: check _M_aintainer field for"
	echo "             Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org>"
	echo "  -D       - debian/control: add \${misc:_D_epends} to Depends:"
	echo "  -d       - debian/copyright: Substitute Format-Specification URL for _D_EP5"
	echo "             revisions to anonscm.debian.org URL."
	echo "  -P       - debian/control: substitute occurrences of dependencies on perl"
	echo "             with ancient version requirement with a dependency without a version"
	echo "  -O       - debian/control: replace perl-m_o_dules with perl"
	echo "  -W       - debian/_w_atch: change CPAN URLs to"
	echo "             https://metacpan.org/release/Mod-Ule ;"
	echo "             update to ignore developer releases"
	echo "  -C       - if -W is given, create debian/watch if it does not"
	echo "             exist"
	echo "  -R       - debian/rules: _r_mdir /usr/\{lib,share\}/perl5 only if they exist;"
	echo "             switch 'dh --with foo \$@' to 'dh \$@ --with foo'"
	echo "  -Q       - add debian/README.source pointing to _Q_uilt's README.source"
	echo "             if the package uses quilt"
	echo "  -A       - all checks"
	echo
	echo "  -a       - automatic (used by takeover-for-pkg-perl.sh)"
	echo "  -n       - no automatic pushes"
	echo "             if neither pf -a or -n are given, ask"
	echo "  -p <pkg> - check only package <pkg>"
	echo "  -h       - this help"
	echo "  -c       - test only the package that is checked out in the"
	echo "             current working directory"
	exit 1
}

#
# Check the environnement to make sure we can work
#
# It returns:
#     0 if everything is fine
#     1 if an error occurred
#
sanity_check() {

	local retval=0;

	if [ ! -d "$WORK_DIR" ]; then
		echo "[*] Error: Could not find working directory: $WORK_DIR !";
		retval=1;

	elif [ ! -x "`which $CMD_REALPATH 2>/dev/null`" ]; then
		echo "[*] Error: Command $CMD_REALPATH not found!";
		retval=1;
	fi

	return $retval;
}

# given source directory, try to find out the cannonical distribution name
detect_dist() {
	DIR=$1
	local PERLNAME
	PERLNAME=''
	if [ -s $DIR/Build.PL ]; then
		PERLNAME=$(perl -n -e "print if s;^.*module_name.*=>.*['\"[]([a-zA-Z0-9:_-]+)[]'\"].*\$;\$1;" $DIR/Build.PL | sed -e 's/::/-/g' | head -n 1)
	fi
	if [ -s $DIR/Makefile.PL ]; then
		PERLNAME=$(perl -n -e "print if s;^.*(?:DIST)?NAME.*=>.*['\"[]([a-zA-Z0-9:_-]+)[]'\"].*\$;\$1;" $DIR/Makefile.PL | sed -e 's/::/-/g' | head -n 1)
	fi
	if [ -s $DIR/META.yml ]; then
		PERLNAME=$(perl -n -e "print if s;^name:.* ([a-zA-Z0-9:_-]+).*\$;\$1;" $DIR/META.yml | head -n 1)
	fi
	if [ -n "$PERLNAME" ]; then
		if curl --silent https://metacpan.org/release/$PERLNAME | grep '<title>' | grep --silent $PERLNAME; then
			echo $PERLNAME
		fi
	fi
}

testvcs() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# remove Vcs-Svn field
	if grep -q ^Vcs-Svn $DIR/debian/control; then
		echo "$PKG: removing Vcs-Svn field"
		sed -i -e "/^Vcs-Svn/ d" $DIR/debian/control
		MSG_CONTROL_RM="${MSG_CONTROL_RM:+$MSG_CONTROL_RM; }Vcs-Svn field (source stanza)"
		CHANGED=1
	fi

	# check for and add missing Vcs-Git field
	if ! grep -q ^Vcs-Git $DIR/debian/control; then
		echo "$PKG: adding missing Vcs-Git field"
		perl -pi -e "s;(Standards-Version:.+);\$1\nVcs-Git: https://salsa.debian.org/perl-team/modules/packages/$PKG.git;" $DIR/debian/control
		MSG_CONTROL_ADD="${MSG_CONTROL_ADD:+$MSG_CONTROL_ADD; }Vcs-Git field (source stanza)"
		CHANGED=1
	fi

	# Vcs-Browser svn -> git
	if grep -qE "^Vcs-Browser.*(wsvn|viewsvn)" $DIR/debian/control; then
		echo "$PKG: Vcs-Browser svn -> git"
		perl -pi -e "s;^Vcs-Browser:.+$;Vcs-Browser: https://salsa.debian.org/perl-team/modules/packages/$PKG;" $DIR/debian/control
		MSG_CONTROL_CH="${MSG_CONTROL_CH:+$MSG_CONTROL_CH; }Vcs-Browser field (source stanza)"
		CHANGED=1
	fi

	# check for and add missing Vcs-Browser field
	if ! grep -q ^Vcs-Browser $DIR/debian/control; then
		echo "$PKG: adding missing Vcs-Browser field"
		perl -pi -e "s;(^Vcs-Git:.+);\$1\nVcs-Browser: https://salsa.debian.org/perl-team/modules/packages/$PKG;" $DIR/debian/control
		MSG_CONTROL_ADD="${MSG_CONTROL_ADD:+$MSG_CONTROL_ADD; }Vcs-Browser field (source stanza)"
		CHANGED=1
	fi

	# remove old XS-Vcs-(Svn|Browser) fields
	if grep -q ^XS-Vcs- $DIR/debian/control; then
		echo "$PKG: removing old XS-Vcs-* fields"
		sed -i -e '/^XS-Vcs-/ d' $DIR/debian/control
		MSG_CONTROL_RM="${MSG_CONTROL_RM:+$MSG_CONTROL_RM; }XS-Vcs-Svn fields (source stanza)"
		CHANGED=1
	fi
}

testdep5url() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	if grep -E -q "Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn\?op=file&rev=" $DIR/debian/copyright; then
		echo "$PKG: Substitute DEP5 Format-Specification URL from svn.debian.org to anonscm.debian.org"
		perl -pi -e 's{Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn\?op=file&rev=(\d+)}{Format-Specification: http://anonscm.debian.org/viewvc/dep/web/deps/dep5.mdwn?view=markup&pathrev=\1}' $DIR/debian/copyright
		MSG_COPYRIGHT_CH="Replace DEP5 Format-Specification URL from svn.debian.org to anonscm.debian.org URL."
		CHANGED=1
	fi
}

testhomepage() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# check for and remove old Homepage from long description
	OLDHP=$(egrep "^  Homepage: " $DIR/debian/control | egrep -o "http.+")
	if [ -n "$OLDHP" ] ; then
		echo "$PKG: removing Homepage: pseudo-field from Description"
		perl -e "undef \$/; my \$buf=<STDIN>; \$buf =~ s/\n \.\n  Homepage: .*//; print \$buf" < $DIR/debian/control > $DIR/debian/control.new
		mv $DIR/debian/control.new $DIR/debian/control
		MSG_CONTROL_RM="${MSG_CONTROL_RM:+$MSG_CONTROL_RM; }Homepage pseudo-field (Description)"
		CHANGED=1
		NEWHP=$OLDHP
	fi

	# check for and add missing new Homepage to source stanza
	if ! egrep -q "^Homepage: " $DIR/debian/control; then
		echo "$PKG: trying to add missing Homepage field to source stanza"

		# only construct new URL if we don't have a "real one"
		if [ -z "$NEWHP" ] || echo "$NEWHP" | grep -q cpan\.org; then
			PERLNAME=`detect_dist $DIR`
			if [ -n "$PERLNAME" ]; then
				NEWHP="https://metacpan.org/release/$PERLNAME"
			fi

			# get NEWHP from somewhere else? debian/watch? debian/copyright?

		fi

		if [ -n "$NEWHP" ]; then
			perl -pi -e "s;(Standards-Version:.+);\$1\nHomepage: $NEWHP;" $DIR/debian/control
			MSG_CONTROL_ADD="${MSG_CONTROL_ADD:+$MSG_CONTROL_ADD; }Homepage field (source stanza)"
			CHANGED=1
		fi
	fi

	# check for search.cpan.org URL and replace with metacpan.org URL
	if egrep -q "^Homepage: http://search\.cpan\.org" $DIR/debian/control; then
		echo "$PKG: trying to change search.cpan.org URL to metacpan.org URL"
		PERLNAME=`detect_dist $DIR`
		if [ -n "$PERLNAME" ]; then
			NEWHP="https://metacpan.org/release/$PERLNAME"
		fi

		if [ -n "$NEWHP" ]; then
			perl -pi -e "s{^Homepage:.+}{Homepage: $NEWHP};" $DIR/debian/control
			MSG_CONTROL_CH="${MSG_CONTROL_CH:+$MSG_CONTROL_CH; }Homepage field changed to metacpan.org URL"
			CHANGED=1
		fi
	fi

	# check if Source URL in debian/copyright points to search.cpan.org and replace
	# it with metacpan.org URL.
	if egrep -q "^Source: http://search\.cpan\.org/dist/" $DIR/debian/copyright; then
		PERLNAME=`detect_dist $DIR`
		if [ -n "$PERLNAME" ]; then
			NEWHP="https://metacpan.org/release/$PERLNAME"
		fi

		if [ -n "$NEWHP" ]; then
			perl -pi -e "s{^Source:.+}{Source: $NEWHP};" $DIR/debian/copyright
			MSG_COPYRIGHT_CH="${MSG_COPYRIGHT_CH:+$MSG_COPYRIGHT_CH; }Source URL changed to metacpan.org URL."
			CHANGED=1
		fi
	fi
}

testmaintainer() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# get Maintainer, check and change
	OLDMAINT=$(grep ^Maintainer: $DIR/debian/control | cut -f2- -d" ")
	if [ "$OLDMAINT" != "Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org>" ] ; then
		echo "$PKG: setting Maintainer to Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org>"
		perl -pi -e "s;^Maintainer:.+;Maintainer: Debian Perl Group <pkg-perl-maintainers\@lists.alioth.debian.org>;" $DIR/debian/control
		MSG_CONTROL_CH="${MSG_CONTROL_CH:+$MSG_CONTROL_CH; }Maintainer set to Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org> (was: $OLDMAINT)"
		# keep old Maintainer in Uploaders unless it's the group in some other form
		# TODO: remove DPG from Uploaders if we've added it to Maintainer
		if ! echo $OLDMAINT | grep pkg-perl-maintainers ; then
			if grep -q Uploaders $DIR/debian/control; then
				perl -pi -e "BEGIN { our \$m=shift @ARGV }; s;(Uploaders:.+>)(.*);\$1, \$m\$2;" "$OLDMAINT" $DIR/debian/control
			else
				perl -pi -e "BEGIN { our \$m=shift @ARGV }; s;(Maintainer:.+);\$1\nUploaders: \$m;" "${OLDMAINT}" $DIR/debian/control
			fi
			MSG_CONTROL_CH="${MSG_CONTROL_CH:+$MSG_CONTROL_CH; }$OLDMAINT moved to Uploaders"
		fi
		CHANGED=1
	fi
}

testmiscdepends() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# check for and add missing ${misc:Depends} to Depends
	if ! grep -q "misc:Depends" $DIR/debian/control; then
		echo "$PKG: trying to add missing \${misc:Depends} to Depends"
		sed -i -e 's;^Depends: ;Depends: ${misc:Depends}, ;' $DIR/debian/control
		MSG_CONTROL_ADD="${MSG_CONTROL_ADD:+$MSG_CONTROL_ADD; }\${misc:Depends} to Depends: field"
		CHANGED=1
	fi
}

testperldepends() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	if egrep -q "perl([[:space:]])+\(>=([[:space:]])*5\.6\.0-1[2,6]\)" $DIR/debian/control; then
		echo "$PKG: substitute dependency on ancient version of perl with a dependency on perl without a version"
		perl -pi -e "s:perl\s+\(>=\s*5\.6\.0-1[2,6]\):perl:" $DIR/debian/control
		MSG_CONTROL_CH="${MSG_CONTROL_CH:+$MSG_CONTROL_CH; }Replace (build-)dependency on ancient version of perl with a dependency on perl without a version (as permitted by Debian Policy 3.8.3)"
		CHANGED=1
	fi
}

testperlmodulesdepends() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	if egrep -q "perl-modules" $DIR/debian/control; then
		echo "$PKG: replace (build) dependency on perl-modules with perl"
		# remove perl-modules without a version
		perl -pi -e 's:perl-modules,?($?):$1:' $DIR/debian/control
		# replace perl-modules with perl
		perl -pi -e 's:perl-modules:perl:' $DIR/debian/control
		# try to catch "double-perl"
		perl -pi -e 's:([^-]+)perl([^\:,\n]*?),\s*perl([^\:,\n]*?):$1perl$2$3:' $DIR/debian/control
		MSG_CONTROL_CH="${MSG_CONTROL_CH:+$MSG_CONTROL_CH; }(build-)depend on perl instead of perl-modules"
		CHANGED=1
	fi
}

testwatchdist() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# watchfile
	if [ -e $DIR/debian/watch ] && ! grep -q metacpan\.org/release $DIR/debian/watch; then
		echo "$PKG: trying to change URL in debian/watch"
		if perl -i -e "my \$changed=1; while(<>){ \$changed=0 if s{(?:^|\s+)(?:ht|f)tp://.*cpan.+/\s*(\S+)-(?:[v(]\S+)(\s.+)?$}{https://metacpan.org/release/\$1   .*/\$1-v?(\\\\d[\\\\d.-]+)\\\\.(?:tar(?:\\\\.gz|\\\\.bz2)?|tgz|zip)\\$\$2}i; print;} exit \$changed" $DIR/debian/watch ; then
			perl -pi -e "s;^version=2;version=3;" $DIR/debian/watch
			MSG_WATCH="debian/watch: use metacpan-based URL."
			CHANGED=1
		fi
	elif [ -e $DIR/debian/watch ] && egrep -q "(d_\.|d\._)" $DIR/debian/watch && ! egrep -q "uversionmangle.+_.\." $DIR/debian/watch; then
		echo "$PKG: trying to remove developer versions from debian/watch"
		sed -i -e 's;\(d_\.\|d\._\);d.;' $DIR/debian/watch
		MSG_WATCH="debian/watch: update to ignore development releases."
		CHANGED=1
	elif [ ! -e $DIR/debian/watch ] && [ -n "$CREATE_WATCH" ]; then
		echo "$PKG: creating debian/watch"
		if dist_name=`detect_dist $DIR`; then
			version_re='v?(\d[\d.-]+)\.(?:tar(?:\.gz|\.bz2)?|tgz|zip)'
			echo "version=3" > $DIR/debian/watch
			echo "https://metacpan.org/release/$dist_name  .*/$dist_name-$version_re\$" >> $DIR/debian/watch
			git add $DIR/debian/watch

			MSG_WATCH="Add debian/watch."
			CHANGED=1
		else
			echo "ERROR: unable to find distribution name"
		fi
	fi
}

testrules() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# handle rmdir /usr/{share,lib}/perl5
	if egrep -m 1 -C 1 "(rmdir.*ignore-fail-on-non-empty|rm -r.*usr/(lib|share)(/perl5)?$)" $DIR/debian/rules | perl -pe 's/\n//g' | grep -q -v "\[ \! -d"; then
		ARCH=$(grep -m 1 -h "Architecture:" $DIR/debian/control | awk '{print $2;}')
		case $ARCH in
			any)
				DELDIR="/share/perl5"
				;;
			all)
				DELDIR="/lib/perl5"
				;;
			*)
				;;
		esac
		echo "$PKG: trying to make rmdir /usr${DELDIR} conditional"
		if perl -i -e "my \$changed=1; while(<>){ \$changed=0 if s{rmdir.*ignore-fail-on-non-empty.*\s(\S+)$DELDIR}{[ ! -d \$1${DELDIR} ] || rmdir --ignore-fail-on-non-empty --parents --verbose \$1${DELDIR}}; print;} exit \$changed" $DIR/debian/rules ; then
			MSG_RULES="debian/rules: delete /usr${DELDIR} only if it exists." && \
			CHANGED=1
		fi
		if perl -i -e "my \$changed=1; while(<>){ \$changed=0 if s{-?rm -r.* (.*usr)/(?:lib|share)(?:/perl5)?\$}{[ ! -d \$1${DELDIR} ] || rmdir --ignore-fail-on-non-empty --parents --verbose \$1${DELDIR}}; print;} exit \$changed" $DIR/debian/rules ; then
			MSG_RULES="debian/rules: delete /usr${DELDIR} only if it exists." && \
			CHANGED=1
		fi
		if perl -i -e "my \$changed=1; while(<>){ \$changed=0 if s{-?find.+xargs.+rmdir.+}{[ ! -d \\\$(CURDIR)/debian/\\\$(shell dh_listpackages)/usr${DELDIR} ] || rmdir --ignore-fail-on-non-empty --parents --verbose \\\$(CURDIR)/debian/\\\$(shell dh_listpackages)/usr${DELDIR}}; print;} exit \$changed" $DIR/debian/rules ; then
			MSG_RULES="debian/rules: delete /usr${DELDIR} only if it exists." && \
			CHANGED=1
		fi
	fi

	# switch dh --with foo $@ to dh $@ --with foo
	if egrep "dh\s+\--with" $DIR/debian/rules ; then
		echo "$PKG: trying to change order of dh arguments."
		if perl -pi -e 's;dh\s+--with\s+(.+)\s+\$@;dh \$@ --with $1;g' $DIR/debian/rules ; then
			MSG_RULES="debian/rules: switch order of arguments to dh." && \
			CHANGED=1
		fi
	fi
}

testreadmesource() {
	DIR=$1
	PKG=$(basename $($CMD_REALPATH $DIR))
	# add debian/README.source for quilt using packages
	if grep -q quilt $DIR/debian/control && [ ! -e $DIR/debian/README.source ] ; then
		echo "$PKG: adding debian/README.source"
cat <<- EOF > $DIR/debian/README.source
	This package uses quilt to manage all modifications to the upstream
	source.  Changes are stored in the source package as diffs in
	debian/patches and applied during the build.

	See /usr/share/doc/quilt/README.source for a detailed explanation.
EOF
	git add $DIR/debian/README.source
	MSG_READMESOURCE="Add debian/README.source to document quilt usage, as required by Debian Policy since 3.8.0."
	CHANGED=1
	fi
}

########
# main #
########

# parse options

[ $# -ge 1 ] || usage "No parameter."

ONLY_CURDIR=""
AUTO=ask

while getopts p:acnVHMDdPOWCRQAh O; do
	case "$O" in
		a)
			AUTO=yes
			;;
		n)
			AUTO=no
			;;
		p)
			PKG=$OPTARG
			;;
		c)
			ONLY_CURDIR=1
			;;
		V)
			TESTVCS=1
			;;
		H)
			TESTHOMEPAGE=1
			;;
		M)
			TESTMAINTAINER=1
			;;
		D)
			TESTMISCDEPENDS=1
			;;
		d)
			TESTDEP5URL=1
			;;
		P)
			TESTPERLDEPENDS=1
			;;
		O)
			TESTPERLMODULESDEPENDS=1
			;;
		W)
			TESTWATCHDIST=1
			;;
		C)
			CREATE_WATCH=1
			;;
		R)
			TESTRULES=1
			;;
		Q)
			TESTREADMESOURCE=1
			;;
		A)
			TESTVCS=1
			TESTDEP5URL=1
			TESTHOMEPAGE=1
			TESTMAINTAINER=1
			TESTMISCDEPENDS=1
			TESTPERLDEPENDS=1
			TESTWATCHDIST=1
			TESTRULES=1
			TESTREADMESOURCE=1
			;;
		h)
			usage
			;;
		*)
			usage "Unknown parameter."
			;;
	esac
done
shift $(($OPTIND - 1)) # bash: shift $((OPTIND - 1))


check_package()
{
	# reset variables
	p=$1
	OLDHP=
	PERLNAME=
	NEWHP=
	OLDMAINT=
	MSG_CONTROL=
	MSG_CONTROL_ADD=
	MSG_CONTROL_RM=
	MSG_CONTROL_CH=
	MSG_COPYRIGHT_CH=
	MSG_WATCH=
	MSG_RULES=
	MSG_READMESOURCE=

	# TESTVCS - -V debian/control: add _V_cs-(Git|Browser) fields; remove XS-Vcs-(Svn|Git|Browser) field
	[ "$TESTVCS" = 1 ] && testvcs $p

	# TESTDEP5URL - -d debian/copyright: Substitute Format-Specification URL for _D_EP5 revisions to anonscm.debian.org URL.
	[ "$TESTDEP5URL" = 1 ] && testdep5url $p

	# TESTHOMEPAGE - -H debian/control: add _H_omepage field; remove pseudo-field Homepage
	[ "$TESTHOMEPAGE" = 1 ] && testhomepage $p

	# TESTMAINTAINER - -H debian/control: check _M_aintainer field for "Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org>"
	[ "$TESTMAINTAINER" = 1 ] && testmaintainer $p

	# TESTMISCDEPENDS - -D debian/control: add ${misc:Depends} to Depends:
	[ "$TESTMISCDEPENDS" = 1 ] && testmiscdepends $p

	# TESTPERLDEPENDS - -P debian/control remove occurrences of perl (>= 5.6.0-{12,16}) from Build-Depends
	# and Build-Depends-Indep if present
	[ "$TESTPERLDEPENDS" = 1 ] && testperldepends $p

	# TESTPERLMODULESDEPENDS - -O debian/control: replace perl-modules with perl"
	[ "$TESTPERLMODULESDEPENDS" = 1 ] && testperlmodulesdepends $p

	# TESTWATCHDIST - -W debian/_w_atch: change CPAN URLs to https://metacpan.org/release/Mod-Ule
	[ "$TESTWATCHDIST" = 1 ] && testwatchdist $p

	# TESTRULES - -R debian/rules: _r_mdir /usr/\{lib,share\}/perl5 only if they exist;
	# switch dh --with foo $@ to dh @ --with foo
	[ "$TESTRULES" = 1 ] && testrules $p

	# TESTREADMESOURCE - -Q add debian/README.source for _Q_uilt-using packages
	[ "$TESTREADMESOURCE" = 1 ] && testreadmesource $p

	# changelog
	if [ -n "$MSG_CONTROL_ADD" -o -n "$MSG_CONTROL_RM" -o -n "$MSG_CONTROL_CH" ] ; then
		MSG_CONTROL="debian/control:"
		[ -n "$MSG_CONTROL_ADD" ] && MSG_CONTROL="$MSG_CONTROL Added: $MSG_CONTROL_ADD."
		[ -n "$MSG_CONTROL_RM" ] && MSG_CONTROL="$MSG_CONTROL Removed: $MSG_CONTROL_RM."
		[ -n "$MSG_CONTROL_CH" ] && MSG_CONTROL="$MSG_CONTROL Changed: $MSG_CONTROL_CH."
		dch --mainttrailer --release-heuristic=changelog --changelog $p/debian/changelog "$MSG_CONTROL"
	fi
	if [ -n "$MSG_WATCH" ] ; then
		dch --mainttrailer --release-heuristic=changelog --changelog $p/debian/changelog "$MSG_WATCH"
	fi
	if [ -n "$MSG_RULES" ] ; then
		dch --mainttrailer --release-heuristic=changelog --changelog $p/debian/changelog "$MSG_RULES"
	fi
	if [ -n "$MSG_READMESOURCE" ] ; then
		dch --mainttrailer --release-heuristic=changelog --changelog $p/debian/changelog "$MSG_READMESOURCE"
	fi
	if [ -n "$MSG_COPYRIGHT_CH" ] ; then
		dch --mainttrailer --release-heuristic=changelog --changelog $p/debian/changelog "debian/copyright: $MSG_COPYRIGHT_CH"
	fi
}

# start the game

CHANGED=0
TOP=$1

if [ -n "$ONLY_CURDIR" ]; then
	WORK_DIR="."
elif [ -n "$PKG" ]; then
	if [ -z "$TOP" ]; then
		echo "-p requires topdir" >&2
		exit 1
	fi
	WORK_DIR=$TOP/packages/$PKG
else
	if [ -z "$TOP" ]; then
		echo "No -c is given and there is no topdir" >&2
		exit 1
	fi
	WORK_DIR=$TOP
fi

sanity_check;
[ "$?" -ne "0" ] && exit 1;

if [ $AUTO = 'yes' ]; then
	echo "Running mr up $WORK_DIR ..."
	mr up $WORK_DIR
fi

if [ -n "$ONLY_CURDIR" ]; then
	check_package $WORK_DIR
elif [ -n "$PKG" ]; then
	check_package $WORK_DIR
else
	# loop over packages

	echo "Grepping through packages ..."
	for PKG in $(ls -d $TOP/packages/*); do

		PKG=$(basename $PKG)
		PKG=${PKG%/}
		[ -d "$TOP/packages/$PKG" ] && check_package $TOP/packages/$PKG

	done
fi

# work is done. git diff? git commit?

if [ "$CHANGED" = "1" ]; then
	if [ $AUTO = ask ]; then
		read -p "Show git diff $WORK_DIR (y|N)? " DIFF
		case $DIFF in
			y|Y)
				( cd $WORK_DIR; mr diff | less -R )
				;;
			*)
				;;
		esac
	fi
	COMMIT_MSG="[packagecheck] fixed Vcs-(Git|Browser)/Homepage field(s) in debian/control and/or URL in debian/watch and/or rmdir /usr/{lib|share}/perl5 in debian/rules."
	if [ $AUTO = ask ]; then
		read -p "Commit $WORK_DIR (y|N)? " COMMIT
		case $COMMIT in
			y|Y)
				# TODO: mr commit automatically pushes too!
		                #       commit and push for every single repository
				( cd $WORK_DIR; mr commit -m "$COMMIT_MSG" )
				;;
			*)
				;;
		esac
	elif [ $AUTO = yes ]; then # AUTO
		# TODO: mr commit automatically pushes too!
		#       commit and push for every single repository
		cd $WORK_DIR && mr commit -m "$COMMIT_MSG"
	else	# no auto
		echo "packagecheck: changes weren't committed."
	fi
else
	echo "Nothing changed."
fi

exit 0

POD=<<'EOF'
=head1 NAME

dpt-packagecheck -- check package source for group policy consistency

=head1 SYNOPSIS

B<dpt packagecheck> -c I<check-option>...

B<dpt packagecheck> -p I<package> I<top-directory> I<check-option>...

=head1 DESCRIPTION

B<dpt packagecheck> performs various checks of package sources and tries to
correct them in accordance with the policies of the Debian Perl Group.

=head2 Package selection options

B<dpt packagecheck> can operate either on a single package, or on all packages
maintained by the group.

To run the checks on all group packages, use the B<-c> option with working
directory containing F<packages/> directory.

To run the checks on individual package, use B<-p> I<package> I<top-directory>,
where I<top-directory> is the directory containing the F<packages/> directory.

=head2 Repository interaction

If the B<-a> option is given, changes are committed to the repository by
calling C<mr commit>.

If the B<-n> option is given, no changes are committed.

If neither option is given, B<dpt packagecheck> asks for confirmation before
calling C<mr commit>.

Note that C<mr commit> also pushes the changes to the remote repository.

=head2 Check selection options

=over

=item B<-A>

Run all the checks.

=item B<-V>

Add/fix C<Vcs-Git> and C<Vcs-Browser> fields in F<debian/control> and remove
C<XS-Vcs-(Svn|Git|Browser)> fields.

=item B<-H>

Add C<Homepage> field to F<debian/control> and remove C<Homepage> pseudo-field.

=item B<-M>

Check the C<Maintainer> field of F<debian/control> and make sure it is
C<< Debian Perl Group <pkg-perl-maintainers@lists.alioth.debian.org> >>.

=item B<-D>

F<debian/control>: add C<${misc:Depends}> to C<Depends>.

=item B<-d>

F<debian/copyright>: Substitute C<Format-Specification> URL for DEP-5 revisions
to anonscm.debian.org URL.

=item B<-P>

F<debian/control>: substitute occurrences of dependencies like
C<< perl (>= 5.6.0-{12,16}) >> with dependencies on C<perl> without a version.

=item B<-O>

F<debian/control>: replace C<perl-modules> with C<perl>

=item B<-W>

F<debian/watch>: change CPAN URLs to L<https://metacpan.org/release/Mod-Ule>
and update to ignore developer releases

=item B<-C>

If B<-W> is given, create F<debian/watch> if it does not exist

=item B<-R>

F<debian/rules>: rmdir /usr/\{lib,share\}/perl5 only if they exist;
switch C<dh --with foo \$@> to C<dh \$@ --with foo>

=item B<-Q>

add F<debian/README.source> pointing to L<quilt(1)>'s F<README.source> if the
package uses quilt

=back

=head1 COPYRIGHT & LICENSE

=over

=item Copyright 2011-2013, Salvatore Bonaccorso L<carnil@debian.org>

=item Copyright 2007, 2008, 2009, 2011 gregor herrmann L<gregoa@debian.org>

=item Copyright 2007, 2008 Damyan Ivanov L<dmn@debian.org>

=item Copyright 2007 David Paleino L<d.paleino@gmail.com>

=back

Released under the terms of the GNU GPL version 2

=cut
EOF
# vi: set noet sts=0 sw=8:
