#!/bin/sh

#
# Copyright (c) 2002-2003 Alexander Leidinger
# All rights reserved.
#
# 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 AND CONTRIBUTORS ``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 OR CONTRIBUTORS 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.
#


# This script parses a "cvs update"-logfile and extracts diffs and non
# "cvs add"-Port-patch-files into the destination directory and
# chowns them to the given user and group.
#
# I call it in my website build/transfer Makefile like:
# gen_patches.sh ${.CURDIR}/htdocs/FreeBSD/port-patches myusr:mygrp /usr/ports

# $1 = destdir
# $2 = chown parameter
# $3 = portsdir
# hardcoded: name of "cvs update"-logfile (update.log)

dest=$1
user=$2
PORTSDIR=$3

in_cvs_list=$(grep -E '^(C|M) ' ${PORTSDIR}/update.log \
	| cut -d ' ' -f 2 \
	| cut -d / -f 1,2 \
	| sort -u)

[ ! -d ${dest} ] && mkdir -p ${dest}
rm ${dest}/*

for i in ${in_cvs_list}; do
	patch=$(echo ${i} | sed 's@/@:@g').diff
	cd ${PORTSDIR} && cvs -R diff -u ${i} > ${dest}/${patch}
	# remove if empty
	[ ! -s ${dest}/${patch} ] && rm ${dest}/${patch}
done


no_cvs_list=$(grep -E '^\? .*patch-' ${PORTSDIR}/update.log \
	| cut -d ' ' -f 2 \
	| sort -u)

for i in ${no_cvs_list}; do
	file=$(echo ${i} | sed 's@/@:@g')
	cp ${PORTSDIR}/${i} ${dest}/${file}
	# remove if empty
	[ ! -s ${dest}/${file} ] && rm ${dest}/${file}
done

rm ${dest}/INDEX*.diff
chmod -R a+r ${dest}
chown -R ${user} ${dest}
