#!/bin/sh

# Copyright: (c) 2012, Thomas Goirand <zigo@debian.org>
# License: LGPL-2.1
# This library is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
# .
# This library 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 Lesser General Public License for more
# details.
# .
# You should have received a copy of the GNU Lesser General Public License along
# with this library; if not, write to the Free Software Foundation, Inc., 51
# Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# .
# On Debian systems, the complete text of the GNU Lesser General Public License
# (LGPL) may be found in /usr/share/common-licenses/LGPL-2.1

set -e

# Path to the pkg-php-tools script
PHPPKGINFO=/usr/share/pkg-php-tools/scripts/phppkginfo

# Default values
DO_INSTALL=no
PEAR_CHANNEL=pear.php.net
BUILD_DIR=./build-area
VERBOSE=no

######################################
### EVALUATION OF INPUT PARAMETERS ###
######################################
print_usage () {
	echo "$0 [options] <pear-package-name>"
	echo "Options are:"
	echo "            Specify build dir: --build-dir|-b <build-dir>"
	echo "              Be more verbose: --verbose|-v"
	echo "         Specify PEAR channel: --channel|-c <channel>"
	echo "              Specify tarball: --tarball|-t <tarball> --pkg-version|-pv <pkg-version>"
	echo "                               [--wget|-w <URL>]"
	echo "Install the resulting package: --install|-i"
}

echoIfVerbose () {
	if [ ${VERBOSE} = "yes" ] ; then
		echo ${1}
	fi
}

for i in $@ ; do
	case ${1} in
	"--channel"|"-c")
		echo "Channels other than pear.php.net aren't supported yet"
		exit 1
		PEAR_CHANNEL=${2}
		shift
		shift
		;;
	"--tarball"|"-t")
		TARBALL=${2}
		if ! [ -f "${TARBALL}" -a "${5}" != "--wget" ] ; then
			if [ "${5}" != "--wget" -a "${5}" != "-w" ] ; then
				echo "Cannot find specified tarball file."
				print_usage
				exit 1
			fi
		fi
		if [ "${3}" != "--pkg-version" -a "${3}" != "-pv" ] ; then
			echo "Please specify a package version when using --tarball|-t"
			print_usage
			exit 1
		fi
		if [ -z "${4}" ] ; then
			echo "No package version specified after --pkg-version|-pv"
			print_usage
			exit 1
		fi
		VERSION_STRING="${4}"
		shift
		shift
		shift
		shift
		if [ "${1}" = "--wget" -o "${1}" = "-w" ] ; then
			WGET_URL=${2}
			shift
			shift
		fi
		;;
	"--build-dir"|"-b")
		BUILD_DIR=${2}
		shift
		shift
		;;
	"--install"|"-i")
		DO_INSTALL=yes
		shift
		;;
	"--verbose"|"-v")
		VERBOSE=yes
		shift
		;;
	*)
		;;
	esac
done

if [ $# != 1 ] ; then
	echo "No PEAR package given as parameter: exiting"
	print_usage
	exit 1
fi
PEAR_PKG_NAME=$1

if [ -z "${PEAR_PKG_NAME}" ] ; then
	echo "No PEAR package defined: exiting"
	print_usage
	exit 1
fi

###########################
### START OF THE SCRIPT ###
###########################
echoIfVerbose "debpear ===> Preparing build area in ${BUILD_DIR}"
DEB_PKG_NAME=`${PHPPKGINFO} debian_pkgname ${PEAR_CHANNEL} ${PEAR_PKG_NAME}`

if ! [ -d "${BUILD_DIR}" ] ; then
	mkdir ${BUILD_DIR}
fi
if [ -n "${TARBALL}" ] ; then
	if [ -n "${WGET_URL}" ] ; then
		if ! [ -f ${TARBALL} ] ; then
			wget ${WGET_URL} -O ${TARBALL}
		fi
	fi
	cp ${TARBALL} ${BUILD_DIR}/${PEAR_PKG_NAME}-${VERSION_STRING}.tgz
fi
cd ${BUILD_DIR}

if [ -z "${TARBALL}" ] ; then
	pear download ${PEAR_PKG_NAME}
fi

### CALCULATION OF VERSIONS AND NAMES ###
DOWNLOADED_PEAR_PKG=`ls | grep ${PEAR_PKG_NAME}`
FILENAME_LEN=`echo ${DOWNLOADED_PEAR_PKG} | awk '{printf length($0)}'`
PEAR_PKG_NAME_LEN=`echo ${PEAR_PKG_NAME} | awk '{printf length($0)}'`
VERSION_START=$((PEAR_PKG_NAME_LEN + 2))
VERSION_LEN=$((${FILENAME_LEN} - ${PEAR_PKG_NAME_LEN} - 5))
VERSION_STRING=`echo ${DOWNLOADED_PEAR_PKG} | awk '{printf substr($0,'${VERSION_START}','${VERSION_LEN}')}'`
DEB_SRC_FOLDER="${DEB_PKG_NAME}-${VERSION_STRING}"
DEB_PKG_RESULT="${DEB_PKG_NAME}_${VERSION_STRING}-1_all.deb"

cp ${DOWNLOADED_PEAR_PKG} ${DEB_PKG_NAME}_${VERSION_STRING}.orig.tar.gz

if ! [ -d "${DEB_SRC_FOLDER}" ] ; then
	mkdir ${DEB_SRC_FOLDER}
fi

echo "debpear ===> Extracting orig tarball"
if [ ${VERBOSE} = "yes" ] ; then
	TAR_OPT="v"
fi
tar -C ${DEB_SRC_FOLDER} -xzf${TAR_OPT} ${DOWNLOADED_PEAR_PKG}

cd ${DEB_SRC_FOLDER}
#########################################
### GENERATION OF THE ./debian FOLDER ###
#########################################
echo "debpear ===> Building ${DEB_PKG_RESULT}"
mkdir -p debian/source
echo "3.0 (quilt)" >debian/source/format
echo "8" >debian/compat
if ! [ -f debian/changelog ] ; then
	EDITOR=touch dch --create --package ${DEB_PKG_NAME} --distribution unstable --urgency low -v ${VERSION_STRING}-1
fi
echo "Source: ${DEB_PKG_NAME}
Section: php
Priority: optional
Maintainer: Debian PHP PEAR Maintainers <pkg-php-pear@lists.alioth.debian.org>
Build-Depends: debhelper (>= 8), pkg-php-tools
Build-Depends-Indep: php-pear
Standards-Version: 3.9.3
Vcs-Browser: http://git.debian.org/?p=pkg-php/${DEB_PKG_NAME}.git
Vcs-Git: http://git.debian.org/git/pkg-php/${DEB_PKG_NAME}.git
Homepage: http://pear.php.net/package/${PEAR_PKG_NAME}

Package: ${DEB_PKG_NAME}
Architecture: all
Depends: \${misc:Depends}, php-pear, \${phppear:Debian-Depends}
Recommends: \${phppear:Debian-Recommends}
Breaks: \${phppear:Debian-Breaks}
Description: \${phppear:summary}
 \${phppear:description}
" >debian/control

echo "Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: ${PEAR_PKG_NAME}
Source: http://pear.php.net/package/${PEAR_PKG_NAME}

Files: debian/*
Copyright: Generated by debpear
License: BSD-2-clauses

Files: *
Copyright: <please-fill>
License: <please-check>

License: BSD-2-clauses
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 .
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 .
 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.
 .
 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

">debian/copyright

echo "#!/usr/bin/make -f
%:
	dh \$@ --buildsystem=phppear --with phppear
" >debian/rules

echo "version=3
http://pear.php.net/package/${PEAR_PKG_NAME}/download http://download.pear.php.net/package/${PEAR_PKG_NAME}-(.*).tgz
" >debian/watch

###############################
### BUILDING AND INSTALLING ###
###############################
dpkg-buildpackage
cd ..

if [ "${DO_INSTALL}" = "yes" ] ; then
	if ! [ `whoami` = "root" ] ; then
		sudo dpkg -i ${DEB_PKG_RESULT}
	else
		dpkg -i ${DEB_PKG_RESULT}
	fi
fi
