#! /usr/bin/env bash

set -x
typeset -r prog=$(basename "$0" .sh)
typeset -r program=$(basename "$0")
typeset -r progdir=$(\cd $(dirname "$0") && pwd -P)
typeset -r progpth=${progdir}/${program}
typeset -r progpid=$$
PS4='>mlp> '

die() { 
    echo "${prog} error:  $*" >&2
    kill -TERM ${progpid}
    exit 1
}

cleanup() {
    test ${#cleanup_list} -gt 0 && \
        rm -rf ${cleanup_list}
}

init() {
    local PS4=">${FUNCNAME}> "

    PROJECT=gnulib
    EADDR=bug-gnulib@gnu.org
    TARNAME=libposix
    PROJURI=http://www.gnu.org/software/gnulib
    export PROJECT EADDR TARNAME PROJURI

    \cd ${progdir}
    PATH=$(\cd .. ; pwd -P):${PATH}
    ddir=${PWD}/${TARNAME}
    sdir=$(which gnulib-tool | sed 's@/gnulib-tool@@')
    test ${#sdir} -eq 0 && die "cannot locate gnulib-tool"

    cleanup_list=''
    trap 'cleanup' EXIT
}

run_gnulib_tool() {
    local PS4=">${FUNCNAME}> "
    test -d "$ddir" && rm -rf $ddir
    if test -f "$ddir.tar.gz" -a "$ddir.tar.gz" -nt ${sdir}/ChangeLog
    then tar -xzf "$ddir.tar.gz"
    else
        local opts="--create-testdir --source-base=lib --dir=${ddir}"

        gnulib-tool --libtool --lib=libposix ${opts} $(posix-modules)
        cd ${TARNAME}
        rm -f configure config.h* Makefile.in */Makefile.in core*
        cd -
        tar -czf ${TARNAME}.tar.gz ${TARNAME}
    fi

    time_stamp=$(
        egrep '^2[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]  ' ${sdir}/ChangeLog | \
            sed 's/-//g;s/ .*//;1q')
}

mk_version() {
    set -e
    local PS4=">${FUNCNAME}> "
    local date_range=${time_stamp%????}
    test "X${date_range}" = X2010 || date_range=2010-${date_range}

    cd ${TARNAME} || die failed $(history | tail -2 | head -1)
    mv gllib ${TARNAME}
    sed -i "/SUBDIRS/s/gllib/${TARNAME}/" Makefile.am

    cd ${TARNAME}
    local headerlist=$' \\\n'$(
        ls -1 *.h | sed 's/\.in\.h$/.h/' | columns -I4 --spread=1 --line=' \\\')
    #'

    sed -i -e "/^EXTRA_DIST *= *$/s/$/ version.[ch]/" \
        -e "/^noinst_LTLIB/d" \
        -e "/^noinst_LIBRARIES/s/noinst_L/lib_LTL/g" \
        -e "/noinst_HEADERS/s/noinst_H.*/nobase_include_HEADERS = \\\\/" \
        -e "/^nobase_include_HEADERS =/a${headerlist}" \
        -e "s/^libgnu_a_SOURCES *=.*/${TARNAME}_la_SOURCES = version.c/g" \
        -e "s/libgnu_a_/${TARNAME}_la_/g" \
        -e "/^lib_LTLIBRARIES *=/s/=.*/= ${TARNAME}.la/" \
        -e "/^lib_LTLIBRARIES *+/d" \
        -e "s/libgnu\\.a/libposix.la/" \
        Makefile.am

    local git_ver=$(\cd $sdir ; ./build-aux/git-version-gen /dev/null | \
        sed -e 's/-dirty/-modified/')

    sed -e "1,/^## *LIBPOSIX_VERSION/d" \
        -e "s/@YEAR@/${date_range}/" \
        -e "s/@DECVERSION@/${time_stamp}/" \
        -e "s/@GITVERSION@/${git_ver}/" \
        -e "/^#endif.*LIBPOSIX_VERSION/q" ${progpth} \
        > version.h
    (   sed '/^#ifndef/,$d' version.h
        echo "int  const _libposix_version = ${time_stamp};"
        echo "char const _libposix_git_version[] = \"${git_ver}\";"
    ) > version.c

    cd ..
}

mk_config() {
    local PS4=">${FUNCNAME}> "
    mv configure.ac configure.ac-saved
    exec 3> configure.ac

    VERSION=$(echo "${time_stamp}" | \
        sed 's/\(....\)\(..\)/\1.\2./')
    export VERSION
    eval local $(egrep '^gl_m4_base=' configure.ac-saved)
    test ${#gl_m4_base} -gt 1 || gl_m4_base=m4

    printf 'AC_INIT([%s],[%s],[%s],[%s],[%s])\n' \
        ${PROJECT} ${VERSION} ${EADDR} ${TARNAME} ${PROJURI} >&3
    printf 'AC_CONFIG_SRCDIR([%s/version.c])\nAC_CONFIG_MACRO_DIR([%s])\n' \
        ${TARNAME} ${gl_m4_base} >&3

    local sedcmd="
	1,/^AC_INIT(/d
	s/dnl .*//
	/^\$/d
	/^#/d
	s/gllib/${TARNAME}/g
	s/LIBGNU_L/LIBPOSIX_L/g
	s/^AM_CONDITIONAL.*LIBTOOL.*/AC_PROG_LIBTOOL/
	/^gl_cond_libtool/d"

    sed -e "${sedcmd}" configure.ac-saved >&3

    exec 3>&-
    cleanup_list=${cleanup_list}configure.ac-saved' '

    # Make certain that any installed programs (viz. pt_chown) is not
    # built in two conflicting ways
    #
    sedcmd=$'/^$/d\n/^# /d'
    for f in $(egrep '_PROGRAMS *=' ${TARNAME}/Makefile.am | sed 's/.*= *//')
    do
        sedcmd=${sedcmd}$'\n'"/^EXTRA_${TARNAME}_la_SOURCES *+= *${f}\\.c/d"
    done
    sed -i -e "${sedcmd}" ${TARNAME}/Makefile.am

    autoreconf -i || die 'autoreconf -i failed'
}

build_distro() {
    local PS4=">${FUNCNAME}> "
    configure || die 'configure failed'
    make      || die 'make failed'
    make dist || die 'make dist failed'
}

init
run_gnulib_tool
mk_version
mk_config
build_distro

exit $?

## LIBPOSIX_VERSION
/* Meta information about GNU libposix.
  Copyright (C) @YEAR@ Free Software Foundation, Inc.

  This program is free software: you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as published
  by the Free Software Foundation; either version 3 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
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

#ifndef _LIBPOSIX_VERSION
/* Version number: (year * 10000) + (month * 100) + day */
#define _LIBPOSIX_VERSION @DECVERSION@

#define _GIT_VERSION      "@GITVERSION@"

#ifdef __cplusplus
extern "C" {
#endif

extern int  const _libposix_version;
extern char const _libposix_git_version[sizeof(_GIT_VERSION)];

#ifdef __cplusplus
}
#endif
#endif /* _LIBPOSIX_VERSION */
