#! /bin/sh

# Copyright (C) 2010, 2014 EPITA Research and Development Laboratory (LRDE).
#
# This file is part of Olena.
#
# Olena 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, version 2 of the License.
#
# Olena 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 Olena.  If not, see <http://www.gnu.org/licenses/>.

# To be used from milena/doc/'s source directory.

# FIXME: Factor gen-split-examples-mk and gen-split-outputs-mk.

me=`basename $0`

# Use the C locale to have a deterministic sort.
export LC_ALL=C

die ()
{
  echo >&2 "$me: $@"
  exit 1
}

# backslashify
# ------------
# Read lines from the standard input and write them on the standard
# output with an extra trailing backslash, except for the last line.
backslashify()
{
  # Set IFS to nothing to prevent `read' from trimming spaces or tabs.
  IFS= read last_line
  while IFS= read line; do
    echo "$last_line \\"
    last_line=$line
  done
  echo "$last_line"
}

# Get this list as argument?
inputs()
{
  # Remove the .cc extension before sorting file names.
  find examples -name \*.cc			\
    | sed 's/.cc$//'				\
    | sort					\
    | sed 's/$/.cc/'
}

output_dir=outputs/split

# Use a temporary file to dump rules at the end of the output.
tempfile=`mktemp /tmp/temp.XXXXXX`
# Set up automatic cleanup.
cleanup() { rm -f "$tempfile"; exit; }
trap cleanup 0 1 2 3 6 15

# Header.
cat <<EOF
## Generated by $me.  Do not edit by hand.

EOF

# Output target names in a variable.
{
  echo "SPLIT_OUTPUTS ="
  inputs | while read file; do

    # Count the number of opening and closing marks.
    nopening=`grep -c 'doc::begin_output' "$file"`
    nclosing=`grep -c 'doc::end_output'   "$file"`
    test "$nopening" -eq "$nclosing" \
      || die "Unbalanced marks in $file ($nopening vs $nclosing)"

    # If there is no mark, skip this file.
    test "$nopening" -eq 0 && continue

    # FIXME: Programs of which sources are located in a subdirectory of
    # examples/ take the path as prefix of their name.  This is a pain.
    # It'd be much simpler to have all sources in the same directory.
    canonical_name=`echo "$file"		\
                      | sed -e 's,examples/,,'	\
                            -e 'y,/,_,'		\
                            -e 's,\.cc$,,'`
    # Output file to be split.
    output="\$(srcdir)/outputs/$canonical_name.txt"
    # Timestamp split outputs depend on.
    timestamp="\$(srcdir)/$output_dir/$canonical_name.txt.stamp"
    # List of targets associated to FILE.
    targets=
    {
      i=1
      while test "$i" -le "$nopening"; do
        # i-th part of the split file.
        part="\$(srcdir)/$output_dir/$canonical_name-$i.txt"

        if test -z "$targets"; then
          targets="$part"
        else
          targets="$targets $part"
        fi
        echo "  $part"
        i=`expr $i + 1`
      done

    # Collect rules in a temporary file...
    cat >>"$tempfile" <<EOF


$timestamp: $output
	@rm -f \$@.tmp
	@touch \$@.tmp
	\$(srcdir)/tools/split_sample.sh $output txt "" \$(srcdir)/$output_dir
	@mv -f \$@.tmp \$@
EXTRA_DIST += $timestamp
MAINTAINERCLEANFILES += $timestamp

$targets: $timestamp
## Recover from the removal of \$@
	@if test -f \$@; then :; else \\
	  rm -f $timestamp; \\
	  \$(MAKE) \$(AM_MAKEFLAGS) $timestamp; \\
	fi
EOF
    }
  done
} | backslashify

# ...and output them at the end.
cat "$tempfile"
