#! /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='>${FUNCNAME:-mlp}> '

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

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

init() {
    PROJECT=gnulib
    EADDR=bug-${PROJECT}@gnu.org
    TARNAME=libposix
    UC_NAME=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 opts="--create-testdir --source-base=lib --dir=${ddir}"
    local mod_list=$(posix-modules | \
        columns --by-columns --width=105 --spread=1 | \
        sed 's/             \([a-z]\)/ \1/')

    gnulib-tool --libtool --lib=${TARNAME} ${opts} ${mod_list}
    cd ${TARNAME}
    rm -f configure config.h* Makefile.in */Makefile.in core* autom4te.cache

    set -- $(IFS=- ; set -- ${time_stamp} ; echo $*)
    local date=(xx January February March April May June July August September
        October November December)
    date=${date[$2]}\ ${3#0},\ $1
    
    local sedcmd='1,/^## *README/d
	/^## *END-README/Q
	s/@EDIT-DATE@/'"${date}/"
    exec 3> README
    sed "${sedcmd}" ${progpth} >&3
    echo "${mod_list}" >&3
    exec 3>&-

    test -d aclocal || mkdir aclocal || die cannot make aclocal directory
    sedcmd="1,/^## *${UC_NAME}-M4/d
	/^## *END-${UC_NAME}-M4/Q
	s/@UC-NAME@/${UC_NAME}/g
	s/@PACKAGE@/${TARNAME}/g"
    sed "${sedcmd}" ${progpth} > aclocal/${TARNAME}.m4

    sedcmd=$(egrep '^ *EXTRA_DIST *=' Makefile.am)
    test ${#sedcmd} -gt 0 && sedcmd='+=' || sedcmd='='
    mv -f gllib ${TARNAME}
    sed -i "s/gllib/${TARNAME}/g
	\$a\\
EXTRA_DIST ${sedcmd} README aclocal/${TARNAME}.m4\\
nobase_data_DATA = aclocal/${TARNAME}.m4
" Makefile.am

    cd -
    tar -czf ${TARNAME}.tar.gz ${TARNAME}
}

get_gnulib_dir() {
    test -d ${TARNAME} && {
        chmod -R u+rwx ${TARNAME}
        rm -rf ${TARNAME}
    }

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

    if test -f ${TARNAME}.tar.gz -a ${TARNAME}.tar.gz -nt ${sdir}/ChangeLog
    then tar -xzf ${TARNAME}.tar.gz
    else run_gnulib_tool
    fi

    time_stamp=$(echo $time_stamp | sed s/-//g)
}

fix_Makefile_am() {
    local headerlist=$(
        ls -1 *.h | grep -v '\.in\.h$'
        egrep '^[a-zA-Z0-9_/-]+\.h *:' Makefile.am | sed 's/ *:.*//' )

    local mod_list=$(sed '1,/^$/d' ../README)
    
    local headerlist=$' \\\n'$(
         echo "${headerlist}" | sort -u | columns -I4 --spread=1 --line=' \\\')
    #' emacs gets lost)

    # 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}${TARNAME}/Makefile.am-ori' '

    local headers_type=nobase_nodist_pkginclude_HEADERS

    sedcmd='/^EXTRA_DIST *= *$/s/$/ version.h version.c mk-'${TARNAME}'-pc-sh.in/
	/^noinst_LIBRARIES/d
	s/^noinst_LTLIBRARIES/lib_LTLIBRARIES/
	/^lib_LTLIBRARIES *=/a\
nobase_nodist_data_DATA = pkgconfig/'${TARNAME}'.pc\
pkgconfig/'${TARNAME}'.pc : mk-'${TARNAME}'-pc.sh\
	$(SHELL) mk-'${TARNAME}'-pc.sh	

	/^MOSTLYCLEANFILES *=/s@$@ core.* pkgconfig/'${TARNAME}'.pc@
	/^MOSTLYCLEANDIRS *=/s@$@ pkgconfig@
	/^noinst_HEADERS/s/noinst_H.*/'${headers_type}' = \\/
	s/^# .*//
	/^[ #]*$/d
	/_LDADD *=/s/libgnu\.l*a/'${TARNAME}".la -lrt/
	/^${headers_type} =/a${headerlist}"

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

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

    cd ${TARNAME}/${TARNAME} || die failed cd ${TARNAME}/${TARNAME}

    fix_Makefile_am

    sedcmd='1,/^## *LIBPOSIX.PC.IN/d
	s/\${TARNAME}/'${TARNAME}'/g
	/^## *END-LIBPOSIX.PC.IN/Q'

    sed "${sedcmd}" ${progpth} > mk-${TARNAME}-pc-sh.in
    test -d pgkconfig || mkdir pgkconfig || die "cannot mkdir pgkconfig"

    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}/
	s/@PACKAGE@/${TARNAME}/
	s/@UC-NAME@/${UC_NAME}/g
	/^#endif.*LIBPOSIX_VERSION/q"

    sed -e "${sedcmd}" ${progpth} > version.h
    (   sed '/^#ifndef/Q' version.h
        echo "int  const _${TARNAME}_version       = ${time_stamp};"
        echo "char const _${TARNAME}_git_version[] = \"${git_ver}\";"
    ) > version.c

    cd ..
}

mk_config() {
    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 mk_pc=${TARNAME}/mk-${TARNAME}-pc.sh
    local mk_src=${TARNAME}/mk-${TARNAME}-pc-sh.in
    local sedcmd="
	1,/^AC_INIT(/d
	s/dnl .*//
	/^\$/d
	/^#/d
	s/gllib/${TARNAME}/g
	s/LIBGNU_L/${UC_NAME}_L/g
	s/^AM_CONDITIONAL.*LIBTOOL.*/AC_PROG_LIBTOOL/
	/^gl_cond_libtool/d
	/^AC_OUTPUT/i\\
AC_CONFIG_FILES([${mk_pc}:${mk_src}])"

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

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

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

build_distro() {
    ulimit -S -c 0
    configure      || die 'configure failed'
    make           || die 'make failed'
    make distcheck || die 'make distcheck failed'
}

init
get_gnulib_dir
mk_version
mk_config
build_distro

exit 0

sed extracted text follows:

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

## LIBPOSIX_VERSION
/* Meta information about GNU @PACKAGE@.
  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 _@UC-NAME@_VERSION
/* Version number: (year * 10000) + (month * 100) + day */
#define _@UC-NAME@_VERSION     @DECVERSION@

#define _@UC-NAME@_GIT_VERSION "@GITVERSION@"

#ifdef __cplusplus
extern "C" {
#endif

extern int  const _@PACKAGE@_version;
extern char const _@PACKAGE@_git_version[];

#ifdef __cplusplus
}
#endif
#endif /* _@UC-NAME@_VERSION */

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

## README
This project is automatically derived from gnulib as of @EDIT-DATE@.
It is comprised of the following modules, plus any modules they require:

## END-README

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

## LIBPOSIX-M4
dnl -*- Mode: autoconf -*-
dnl
dnl  Checks to see if there is a working @PACKAGE@.
dnl  "have_@PACKAGE@" is set to "yes" if so.
dnl
AC_DEFUN([gl_CHECK_@UC-NAME@],
[AC_ARG_ENABLE([@PACKAGE@-prefix]
[  --enable-@PACKAGE@-prefix  select a particular @PACKAGE@],
[if test "X$enableval" = "X"
then
  gl_@PACKAGE@_cflags=''
  gl_@PACKAGE@_libs=''
elif test -f ${enableval}/share/pkgconfig/@PACKAGE@.pc
then
  enableval=${enableval}/share/pkgconfig/@PACKAGE@.pc
  gl_@PACKAGE@_cflags=`sed -n 's/^Cflags: *//p' $enableval`
  gl_@PACKAGE@_libs=`sed -n 's/^Libs: *//p' $enableval`
else
  gl_@PACKAGE@_cflags=''
  gl_@PACKAGE@_libs=''
fi
if test "X$gl_@PACKAGE@_cflags" = "X"
then have_@PACKAGE@=false
else have_@PACKAGE@=yes
fi],
[gl_@PACKAGE@_cflags=`pkg-config --cflags @PACKAGE@`
gl_@PACKAGE@_libs=`pkg-config --libs @PACKAGE@`])])
## END-LIBPOSIX-M4

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

## LIBPOSIX.PC.IN
#!@SHELL@

test -d pkgconfig || mkdir pkgconfig

if test -f ${TARNAME}.la
then . ${TARNAME}.la
elif test -f .libs/${TARNAME}.la
then . .libs/${TARNAME}.la
else
  echo you have not built the library yet >&2
  exit 1
fi

exec 3> pkgconfig/${TARNAME}.pc
test -f pkgconfig/${TARNAME}.pc || {
  echo could not create pkgconfig/${TARNAME}.pc >&2
  exit 1
}

sed "s%@dep-libs@%${dependency_libs}%g" >&3 <<\_EOF_
# pkg-config information for @PACKAGE_NAME@'s @PACKAGE@ sub-project
#
PACKAGE_VERSION="@PACKAGE_VERSION@"
PACKAGE_STRING="@PACKAGE_STRING@"
PACKAGE_BUGREPORT="@PACKAGE_BUGREPORT@"

prefix="@prefix@"
exec_prefix="@exec_prefix@"
libdir="@libdir@"
libexecdir="@libexecdir@/@PACKAGE@"
datadir="@datadir@"
includedir="@includedir@/@PACKAGE@"
dependency_libs="@dep-libs@"

Name:           @PACKAGE@
Description:    A package to provide a POSIX compliance glue layer
URL:            http://www.gnu.org/software/@PACKAGE_NAME@
Version:        @PACKAGE_VERSION@
Libs:           -L${libdir} -lposix
Cflags:         -I${includedir}
Libs.private:   @dep-libs@
_EOF_

exec 3>&-
exit 0
## END-LIBPOSIX.PC.IN
