#! /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
    trap "" EXIT
    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

    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 ${TARNAME} && rm -rf ${TARNAME}
    if test -f ${TARNAME}.tar.gz -a ${TARNAME}.tar.gz -nt ${sdir}/ChangeLog
    then tar -xzf ${TARNAME}.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}> " sedcmd=''
    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=$(
        ls -1 *.h | grep -v '\.in\.h$'
        egrep '^[a-zA-Z0-9_/-]+\.h *:' Makefile.am | sed 's/ *:.*//' )

    headerlist=$' \\\n'$(
         echo "${headerlist}" | sort -u | columns -I4 --spread=1 --line=' \\\')
    #' )

    # Fix initial EXTRA_DIST assignment to include version.c & .h
    # Remove all non-libtool library stuff
    # Rename the libtool target
    # start the library sources with version.c
    # Install all headers
    #
    # NOTE: some of this is single quoted and other double.
    # double quoted text is evaluated by the shell, then sed and
    # finally the make program.  Single quoted text gets eval-ed twice.
    #
    mv Makefile.am Makefile.am-ori
    cleanup_list=${cleanup_list}Makefile.am-ori' '

    sedcmd='/^EXTRA_DIST *= *$/s/$/ version.[ch]/
	s/noinst_LTLIBRARIES/lib_LTLIBRARIES/
	/noinst_HEADERS/s/noinst_H.*/nobase_include_HEADERS = \\/
	s/^# .*//
	/^[ #]*$/d'"
	/^nobase_include_HEADERS =/a${headerlist}"

    sed -e "${sedcmd}" Makefile.am-ori > Makefile.am

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

    # Pull the version header from the end of this file and edit it.
    # Copy the boiler plate from that into the version code file
    # and insert the two global variables declared in the header.
    #
    sedcmd="1,/^## *LIBPOSIX_VERSION/d
	s/@YEAR@/${date_range}/
	s/@DECVERSION@/${time_stamp}/
	s/@GITVERSION@/${git_ver}/
	/^#endif.*LIBPOSIX_VERSION/q"

    sed -e "${sedcmd}" ${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 0

## 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 _LIBPOSIX_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 */
