#!/bin/sh -efu
# ***** BEGIN LICENSE BLOCK ***** 
# * Copyright (C) 2006 Alexey Gladkov <legion@altlinux.org> 
# * 
# * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 
# ***** END LICENSE BLOCK ***** 

PROG="${0##*/}"

usage() {
	printf %s\\n "Usage: $PROG <old-php.ini> <new-php-version> [<sed-otions>]"
	exit 0
}

back=
handler() {
	local rc=$?
	trap - EXIT
	[ ! -f "$back" -o ! -s "$back" ] ||
		mv -f -- "$back" "${back%/php.ini.bak*}/php.ini"
	exit $rc
}

quote_sed_regexp()
{
	local out="$*"
	if [ -z "${out##*[\[\].^\$\\/]*}" ]; then
		out="$(printf %s "$out" |sed -e 's/[].^$[\/]/\\&/g')" ||
			return 1
	fi
	printf %s "$out"
}

[ "$#" -ge 2 ] || usage

oldini="$1" && shift
newver="$1" && shift

if [ ! -r "$oldini" ]; then
	printf %s\\n "$PROG: old php.ini not found" >&2
	exit 1
fi

phpini=`basename $oldini`

sapi="${oldini%/$phpini}"
sapi="${sapi##*/}"

destdir="/etc/php/$newver/$sapi"
readlink -ev "$destdir" > /dev/null

oldver="${oldini%/$sapi/$phpini}"
oldver="${oldver##*/}"

trap handler HUP PIPE INT QUIT TERM

newini="$destdir/php.ini"
if [ -s "$newini" ]; then
	back="$(mktemp "$destdir/php.ini.bakXXXXXX")"
	mv -f -- "$newini" "$back"
fi

newver="$(quote_sed_regexp "$newver")"
oldver="$(quote_sed_regexp "$oldver")"

sed -e "s#/$oldver/#/$newver/#g" $@ "$oldini" > "$newini"
