#!/bin/sh -u

#
# Build rpm distribution
#
# Helpful URLs:
# http://www.rpmdp.org/rpmbook/
#

umask 022

# Common code and variables
. util/build_common

echo ''
case "`id`" in
*root*) ;;
*)
    echo    "Warning! 'rpm' may core dump if you are not root."
    echo -n "Hit enter to continue: "
    read junk
    ;;
esac

distro=RedHat
rev=6.1
echo -n "Linux distribution [$distro]: "
read ans
if test "$ans" != ""; then
    distro=$ans
fi
echo -n "Version [$rev]: "
read ans
if test "$ans" != ""; then
    rev=$ans
fi

release=1
rpms=${TMPDIR}/RPMS
build=${TMPDIR}/BUILD
perlrev=`rpm -q perl | awk -F- '{print $2}'`
serial=`echo $VERSION $release | awk '{print $1 * 1000 + $2}'`
summary=`grab_summary`
spec=${TMPDIR}/${PKGNM}-${VERSION}-${release}.spec
doc_files="README README.html COPYING Changes"
group=Development/Languages
arch=`rpm --showrc | awk '/build arch/ {print $NF; exit}'`
os=${distro}-$rev

mkdir $rpms $rpms/$arch $build

cp ${doc_files} ${build}

# Write the spec file
(
    cat <<-END
	Summary: $summary
	Name: $PKGNM
	Version: $VERSION
	Release: $release
	Serial: $serial
	Copyright: $COPYRIGHT
	Group: $group
	Requires: perl = $perlrev
	Prefix: $PREFIX
	URL: $URL
	Vendor: $VENDOR
	%define _topdir $TMPDIR
	BuildRoot: $TMPDIR
	%description
	END

    # Insert the description from PM file
    grab_description | sed 's/^/\: /'

    cat <<-END
	%install
	find $STD_FILES $MODULE -depth -print | cpio -pmd \$RPM_BUILD_ROOT
	%files
	END

    # Insert the file names
    for f in $STD_FILES; do echo        $f; done
    for f in $doc_files; do echo '%doc' $f; done

    # Apache module
    cat <<-END
	%package $MODNM
	Summary: $APACHE_DESC
	Group: $group
	Requires: speedycgi = ${VERSION}, $MODNM
	%description $MODNM
	$APACHE_DESC
	%files $MODNM
	$MODULE
	%post $MODNM
	END

    # Apache install script
    apache_install_script '$RPM_INSTALL_PREFIX' 'rpmsave'

    # Apache uninstall script
    cat <<-END
	%preun $MODNM
	END
    apache_uninstall_script
) >$spec &&

# Build the rpms from the spec
rpm -bb $spec
if test $? -ne 0; then
    adios $?
fi

# Copy the rpms from the TMPDIR
for f in `cd $rpms/$arch; echo *.rpm`; do
    o=$OUTDIR/${os}-$f
    cp $rpms/$arch/$f $o
    case $f in
    *${MODNM}*)
	add_desc $o 1 $os $arch "Apache Web Server"
	;;
    *)
	add_desc $o 0 $os $arch "Perl $perlrev"
	;;
    esac
done
