#!/bin/sh
#
# bootstrap - update generated files by invoking autoreconf, autogen and perl
# Copyright (C) 2015  Alex Vong
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
# Process this file with autoconf to produce a configure script.

# Use error
set -e

ERR_MISSING=127

# Obtain DIRNAME by tranforming `foo/bar' to `foo/'
# Otherwise, assume it is the current working directory
case "$0" in
    */*)
	DIRNAME=`echo "$0" | sed -e 's/\/[^\/]*$/\//g'`
	;;
    *)
	DIRNAME='./'
	;;
esac

# Change to the script's directory
cd "$DIRNAME"

# Prepare the missing script
chmod +x missing

# Generate ChangeLog and NEWS
chmod +x scripts/gen-ChangeLog-NEWS
cat <<'EOF' > ChangeLog
				      Hey, EMACS: -*- text -*-
EOF
scripts/gen-ChangeLog-NEWS >> ChangeLog
scripts/gen-ChangeLog-NEWS > NEWS

# Generate man page
./missing perl < /dev/null
chmod +x scripts/manpage.pl
mkdir doc > /dev/null 2>&1 || true
scripts/manpage.pl > doc/mlucas.1

# Invoke autogen
cd am
../missing autogen main.def

# Invoke autotools
cd ..
./missing autoreconf -f -i

# Make sure host has patch installed
patch < /dev/null > /dev/zero 2>&1 || \
    {
	cat <<'EOF' >&2
WARNING: 'patch' is missing on your system.
         You should need it to patch files generated by the autotools.
         The 'patch' program is part of the GNU patch package:
         <http://www.gnu.org/software/patch>
EOF
	exit $ERR_MISSING
    }

# Patch the generated missing script
cp missing missing.orig
patch -p1 -N \
      < patch/0001-missing-add-autoreconf-autogen-and-perl-as-supported.patch \
    || true
if test -f missing.rej
then
    rm -f missing missing.rej
    mv missing.orig missing
else
    rm -f missing.orig
fi
