#!/usr/bin/env ksh
# -*-mode: shell-script-*-
#
# gen-plist
#
# Copyright (c) 2002, Alan Eldridge
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions 
# are met:
# 
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 
# * 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.
# 
# * Neither the name of the copyright owner nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
#
# $Id: gen-plist,v 1.1 2003/03/10 19:12:41 alane Exp $
#
# 2002-12-16 Alan Eldridge <alane@geeksrus.net>
#

############################################################
ALANESTD_VERSION="1.73"
############################################################
ORIGDIR=$(/bin/pwd); export ORIGDIR
APPNAME=${0##*/};APPNAME=${APPNAME#-}; export APPNAME
test -z "$TMPDIR" && TMPDIR=/tmp; export TMPDIR
test -z "$HOSTNAME" && HOSTNAME=$(hostname); export HOSTNAME
OS=$(uname -s); OSREV=$(uname -r); export OS OSREV
true ${UID:=$(id|sed -e 's|^[^=]*=\([0-9]*\).*$|\1|')}
warn() { echo "[$APPNAME:$$]" "****" "$@";}
status() { echo "[$APPNAME:$$]" "===>" "$@";}
error() { echo "[$APPNAME:$$]" "ERROR:" "$@";}
die() { echo "[$APPNAME:$$]" "FATAL:" "$@"; exit 1;}
unset echo_n; test "X`echo -n`" = "X-n" \
    && echo_n() { echo "$@\c"; } || echo_n() { echo -n "$@"; }
status_n() { echo_n "[$APPNAME:$$]" "===>" "$@";}
log() { local cmd=$1;shift;echo_n $(date "+%Y%m%d.%T") "";$cmd "$@";}
qexpr() { expr "$@" >/dev/null 2>&1;}
qw() { echo \""$@"\"; }
listfiles() { ls -1 ${1:+"$@"} 2>/dev/null; }
whichre() { local n=$#; local s="$1"; shift; while test $# -ge 1; do 
	qexpr "$s" : "$1"&& echo $(($n - $#)) && return 0; shift; done; 
    	echo 0; return 1;}
matchre() { test $(whichre "$@") -gt 0; }
streq() { local s="$1"; shift; while test $# -ge 1; do 
	test "X$s" = "X$1" && return 0; shift; done; return 1;}
strtest() { expr "$1" "$2" "$3" >/dev/null 2>&1; }
strupper() {
    echo "$@"|tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
}
strlower() {
    echo "$@"|tr ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
}
chdir() { cd "$1" || die cd $(qw $1) failed; }
absdir() { chdir "$1" && pwd; }
abspath() { local p=''; case "$1" in /*);; *)p="$(pwd)/";; esac; echo "$p$1"; }
case $OS in 
    *BSD) tmpfile() { mktemp -t .$APPNAME ${1:+"$@"}; };;
    *) tmpfile() { local b=$TMPDIR/.$APPNAME.$$. i=0 istr=''
	    while true; do istr=$(printf "%3d" $i | tr ' ' '0')
		test ! -f $b$istr && break; i=$(( $i + 1 )); done
	    cat /dev/null >$b$istr; echo $b$istr; };;
esac # case $OS
############################################################
# show version and exit
############################################################
VERSION='$Revision: 1.1 $'
VERSION=${VERSION#* }; VERSION=${VERSION% *}
version_() { 
    echo "This is '$APPNAME' v. $VERSION."
    echo "Copyright (c) 2002 Alan Eldridge <alane@geeksrus.net>."; echo
}
version() { version_; exit $1; }
############################################################
# show usage and exit
############################################################
usage() {
    version_
    cat <<EOF
Usage:	$APPNAME [options] [--] [install-plist [uninstall-plist]] [make opts]
Options:
	-h,--help	Show this help.
	-V,--version	Show version number.
	-x,--debug	Turn on shell command tracing.
	-m,--man <file>	Write Makefile man page entries here.
	-p,--prefix <dir>
			Installs to here [/usr/local].
	-v.--var	Variable containing top level dir [DESTDIR].
	--		Stop option processing.

NOTES:
1. If neither file is specified, writes the plist to stdout.
2. If only an install-plist file is specified, writes the uninstall part
   of the plist there, too.
3. If -m/--man is not specified, does not write any info about man pages.
EOF
    exit $1
}
############################################################
# set default vars here
############################################################
DEBUG=0
VERBOSE=0
VFLG=''
INSTALL="-"
UNINSTALL="-"
MANINFO="-"
PREFIX=/usr/local
TOPLEVEL=DESTDIR
############################################################
# do command line options
############################################################
while test $# -gt 0; do
    n=1; case "$1" in
	-h|--help) usage 0;;
	-V|--version) version 0;;
	-x|--debug) set -x;DEBUG=1;;
	-m|--man) n=2; MANINFO=$2;;
	-p|--prefix) n=2; PREFIX=$2;;
	-v|--var) n=2; TOPLEVEL=$2;;
	# catch end-of-opts and bad opt
	--) shift; break;; -*) usage 1;; *) break;;
    esac; shift $n
done

############################################################
# mkplist: brought in from standalone script
############################################################

mkplist() {
    INSTALL="-"
    UNINSTALL="-"
    MANINFO="-"
    PREFIX=/usr/local

    while test $# -gt 0; do
	n=1; case "$1" in
	    -m|--man) n=2; MANINFO=$2;;
	    -p|--prefix) n=2; PREFIX=$2;;
	    *) break;;
	esac; shift $n
    done

    test $# -gt 0 && INSTALL=$1 && shift
    test $# -gt 0 && UNINSTALL=$1 && shift

    tmpfiles="flist celist delist dlist excl tmp"
    # allocate tmp files
    for f in $tmpfiles; do eval $f=$(tmpfile); done

    RELSTART=$((${#PREFIX} + 2))

    # ignore man dirs
    {
	echo '^man($|/)'
	echo '^share/man($|/)'
    } >$excl

    # generate files
    find $PREFIX -type f | cut -c${RELSTART}- | egrep -v -f $excl >$flist

    if test $MANINFO != "-"; then
    # generate man files
	find $PREFIX -type f | cut -c${RELSTART}- | egrep -f $excl \
	    | while read f; do 
	    SUFFIX=${f##*.}
	    printf "MAN${SUFFIX}+=\t\t%s\n" $(basename $f)
	done | unexpand -a >$MANINFO
    fi

    # generate symlinks
    find $PREFIX -type l | cut -c${RELSTART}- | egrep -v -f $excl >>$flist

    if test $MANINFO != "-"; then
    # generate man files
	find $PREFIX -type l | cut -c${RELSTART}- | egrep -f $excl \
	    | while read l; do 
	    f=$(readlink $PREFIX/$l)
	    printf "MLINKS+=\t%s %s\n" $(basename $f) $(basename $l)
	done | unexpand -a >>$MANINFO
    fi

    sort -o $flist $flist

    {
    # redo excl list for dirs
	echo '^man($|/)'
	echo '^share/man($|/)'
	echo '^share$'
	echo '^share/doc$'
	echo '^etc$'
	echo '^etc/rc.d$'
    } > $excl

    # find empty dirs
    find $PREFIX -type d -mindepth 1 -empty | cut -c${RELSTART}- \
	| egrep -v -f $excl >$tmp

    # create empty dirs
    sort -o $tmp $tmp
    if test $(wc -l <$tmp) -gt 0; then
	cat $tmp | while read -r dir; do
	    echo "@exec /bin/mkdir -p %D/$dir"
	done >$celist
    fi

    test $INSTALL != "-" && exec >$INSTALL
    cat $flist $celist

    # maybe destroy empty dirs
    sort -r -o $tmp $tmp
    if test $(wc -l <$tmp) -gt 0; then
	cat $tmp | while read -r dir; do
	    echo "@unexec /bin/rmdir %D/$dir || true"
	done >$delist
    fi

    # don't remove these dirs
    {
	cat $tmp
	echo "^bin$"
	echo "^include$"
	echo "^lib$"
	echo "^share$"
	echo '^share/doc$'
	echo '^etc$'
	echo '^etc/rc.d$'
    } >> $excl

    # remove dirs except in $excl
    find $PREFIX -type d -mindepth 1 | cut -c${RELSTART}- | egrep -v -f $excl \
	| sort -r | while read -r dir; do echo "@dirrm $dir"; done >$dlist

    test $UNINSTALL != "-" && exec >$UNINSTALL
    cat $delist $dlist
    rm -f $flist $celist $delist $dlist $excl $tmp
}

############################################################
# main(): script execution begins here
############################################################

test $# -gt 0 && INSTALL=$1 && shift
test $# -gt 0 && UNINSTALL=$1 && shift

portdir=$(pwd)
portname=$(make -V PORTNAME)
DESTDIR=$(mktemp -d -t $portname)
wrksrc=$(make -V WRKSRC)
install_target=$(make -V INSTALL_TARGET)

echo '===>' WRKSRC is ${wrksrc##*/}
echo '===>' Installing to $DESTDIR ...
mkdir -p $DESTDIR$PREFIX

cd $portdir
make PREFIX=$DESTDIR$PREFIX pre-install

cd $wrksrc
test $# -eq 0 && set -- $TOPLEVEL=${DESTDIR}
eval env $(cd $portdir; make -V MAKE_ENV) gmake "$@" $install_target

cd $portdir
make PREFIX=$DESTDIR$PREFIX post-install

echo '===>' Creating plist ...
mkplist -m $MANINFO -p $DESTDIR$PREFIX $INSTALL $UNINSTALL

#EOF
