#!/bin/sh

PORTS_DIR=/usr/ports
PRIVATE_DIR=private
ASTERISK_DIR=asterisk16

echo "Copying Asterisk port..."
rm -rf ${PORTS_DIR}/${PRIVATE_DIR}/${ASTERISK_DIR}
cp -R -f -p ${PORTS_DIR}/net/${ASTERISK_DIR} ${PORTS_DIR}/${PRIVATE_DIR}/
echo "Patching the Makefile..."
sed -i '' 's/CATEGORIES=	net/CATEGORIES=	private net/' ${PORTS_DIR}/${PRIVATE_DIR}/${ASTERISK_DIR}/Makefile
echo "Fetching the patch..."
VERSION=`sed -n 's/PORTVERSION=	\(.*\)/\1/p' ${PORTS_DIR}/${PRIVATE_DIR}/${ASTERISK_DIR}/Makefile`
echo "Version is: ${VERSION}"
PATCH_URL=http://usecallmanager.nz/includes/cisco-usecallmanager-${VERSION}.patch
fetch $PATCH_URL

while [ -s cisco-usecallmanager-${VERSION}.patch ]
  do

    FILENAME=`sed -n '
	1 { 
	    s/diff -durN asterisk-'"${VERSION}"'.orig\/\(.*\) asterisk-'"${VERSION}"'\/.*/patch-\1/
	    t format
	    b
	    :format
		s/_/__/g
		s/\//_/g
		p
	}
' cisco-usecallmanager-${VERSION}.patch`
    echo "Extracting patch \"${FILENAME}\"..."
    sed -i '' '
	1,/diff / {
	    1 d
	    s/^--- asterisk-'"${VERSION}"'.orig\/\(.*\)	\(.*\)/--- \1\.orig	\2/
	    s/^+++ asterisk-'"${VERSION}"'\/\(.*\)	.*/+++ \1/
	    /diff / !{
		w '"${FILENAME}"'
		d
	    }
	}
' cisco-usecallmanager-${VERSION}.patch
    mv ${FILENAME} ${PORTS_DIR}/${PRIVATE_DIR}/${ASTERISK_DIR}/files/
  done

rm -f cisco-usecallmanager-${VERSION}.patch

echo "Patching patch-channels_chan__sip.c"
sed -i '' 's/^+	\(add_content(&resp, "<dialog usage=\\"hook status\\">\)/+	\/\/\1/' ${PORTS_DIR}/${PRIVATE_DIR}/${ASTERISK_DIR}/files/patch-channels_chan__sip.c

echo "Done!"
