#!/bin/sh

#
# tar2rpm.sh
#
# This file is part of webCDwriter - Network CD/DVD Writing.
#
# Copyright (C) 2003-2004 Jörg P. M. Haeger
#
# webCDwriter is free software. See CDWserver.cpp for details.
#

RPM=rpm
RPMBUILD=rpmbuild
VERSION=2.6.4

if [ -z "$1" ]; then
	echo "$0 file.tar.gz"
	exit 1
fi

# get the pure name of the product without version and suffix
# (on awk see http://www.introcomp.co.uk/scripts/awk_sed_scripts.html)
PRODUCT=`basename $1 \
	| awk -F\- '{print substr($0,1,length($0)-length($NF)-1)}'`

echo
echo "tar2rpm-$VERSION $PRODUCT"
echo

echo -n "Get the user ID... "
ID=`id -u`
if [ $ID = "0" ]; then
	echo "$ID -> Do not run $0 as root!"
	exit 1
fi
echo $ID

echo -n "Trying to run \"g++ -v\"... "
if g++ -v > /dev/null 2>&1; then
	echo "OK"
else
	echo "failed. Install the \"GNU C++ compiler\"!"
	exit 1
fi

echo -n "Trying to run \"make -v\"... "
if make -v > /dev/null 2>&1; then
	echo "OK"
else
	echo "failed. Install \"GNU Make\"!"
	exit 1
fi

echo -n "Has $RPMBUILD... "
if $RPMBUILD --help > /dev/null 2>&1; then
	echo "yes"
else
	RPMBUILD=$RPM
	echo "no -> will use \"$RPMBUILD -tb\""
fi

echo -n "Trying to run \"$RPM --help\"... "
if $RPM --help > /dev/null 2>&1; then
	echo "OK"
else
	echo "failed"
	exit 1
fi

echo -n "Looking for an already installed $PRODUCT... "
upgrade=0
if $RPM -q $PRODUCT > /dev/null 2>&1; then
	upgrade=1
	installed=`$RPM -q $PRODUCT`
	echo $installed
else
	echo "no"
fi

echo
echo "$PRODUCT - building RPM..."
echo

DIR=/tmp/$PRODUCT
rm -rf $DIR/ || exit 1
mkdir -p $DIR/{BUILD,RPMS,SOURCES,SPECS,SRPMS}
if $RPMBUILD -tb \
		--define "_topdir $DIR/" \
		--define "_unpackaged_files_terminate_build 0" \
		$1 --nodeps; then
	echo
	echo Success
	echo
else
	echo
	echo "I am sorry, but building the RPM failed :-("
	if [ "$RPMBUILD" = "$RPM" ]; then
		echo
		echo "There is no \"rpmbuild\" on your system."
		echo "Ask your package manager (like rpmdrake, yast2, ...) for"
		echo "\"rpm-build\" or a package containing \"/usr/bin/rpmbuild\"."
		echo
	fi
	echo "If you cannot solve the above problem yourself,"
	echo "you may mail the above output to feedback@JoergHaeger.de"
	echo "Perhaps I can refine this installer in a future release ..."
	echo
	exit 1
fi
RESULT=`ls $DIR/RPMS/*/*`
RESULT=`basename $RESULT`
mv -iv $DIR/RPMS/*/* .

echo
echo "To do:"
echo
echo "1. Become root (enter \"su\")"
echo
if [ $upgrade = 0 ]; then
	echo "2. Install $RESULT by"
	echo "        $RPM -ihv $RESULT"
else
	echo "2. Upgrade to $RESULT by"
	echo -n "        $RPM -Uhv"
	if [ "$installed" \> "$RESULT" ]; then
		echo -n " --oldpackage"
	fi
	echo " $RESULT"
fi
echo
