#! /bin/sh

# Copyright (C) 2010 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/>.

me=`basename $0`

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

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

# get_outputs FILE
# ----------------
get_outputs()
{
  local outputs=
  local i=1
  # Use Perl instead of sed for portability reasons.
  for output in `perl -ne						    \
  "print if s|^\\s*doc::(p.m)save\\s*\\([^;]+,\\s*\"([^\"]+)\"\\);\$|\\2.\\1|" \
  "$1"`
  do
    # Add a number to the file name.
    # FIXME: Maybe we should let the Perl script above do this...
    num_output=`echo $output | sed "s,\\(.p.m\\),-$i\\1,"`
    if test -z "$outputs"; then
      outputs="$num_output"
    else
      outputs="$outputs $num_output"
    fi
    i=`expr $i + 1`
  done
  echo "$outputs"
}

# upcase STRING
# -------------
upcase()
{
  # Use enumerated sets to be portable.
  echo "$1" | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
}

# canonicalize STRING
# -------------------
canonicalize()
{
  echo "$1" | tr .- _
}

# 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"
}

# List of generated figures.
fig_vars=

# gen_var VARIABLE [ITEMS...]
# ---------------------------
# Generate a Make variable named VARIABLE containing ITEMS.
gen_var()
{
  local v
  {
    echo "$1 ="
    shift
    for v; do
      echo "  $v"
    done
  } | backslashify
}

# List of paths to PBM figures.
pbm_fig_paths=
# List of paths to PGM figures.
pgg_fig_paths=
# List of paths to PPM figures.
ppm_fig_paths=

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

## Figures depend on the timestamp associated with their generator.
## See also examples-outputs.mk.

EOF

for file in `inputs`; do
  # FIXME: Ugly hack to handle the case of examples/ima-save.cc, since
  # this program does not use a `doc::p?msave' routine...
  if test "X$file" = "Xexamples/ima-save.cc"; then
    # Hard-coded value.
    figures="ima_save.pbm"
  else
    figures=`get_outputs "$file"`
  fi

  if test -n "$figures"; then
    # 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$,,'`
    canonical_var=`canonicalize "$canonical_name"`
    fig_var="`upcase "$canonical_var"`_FIGURES"

    # Populate the list of variables of figures.
    fig_vars="$fig_vars \$($fig_var)"

    # Populate the list of paths to figures of a given format.
    for figure in $figures; do
      fig_path="  \$(srcdir)/figures/$figure"
      case "$figure" in
        *.pbm) pbm_fig_paths="$pbm_fig_paths $fig_path";;
        *.pgm) pgm_fig_paths="$pgm_fig_paths $fig_path";;
        *.ppm) ppm_fig_paths="$ppm_fig_paths $fig_path";;
      esac
    done

    # Generate a Make variable for the figures produced by FILE.
    {
      echo "$fig_var ="
      for figure in $figures; do
        fig_path="  \$(srcdir)/figures/$figure"
        echo "$fig_path"
      done
    } | backslashify

    # Generate a Make rule to regen the figures produced by FILE.
    base=`basename "$file" .cc`
    dir=`dirname "$file"`
    timestamp="\$(srcdir)/$dir/$base.stamp"
    cat <<EOF
\$($fig_var): $timestamp
## Recover from the removal of \$@
	@if test -f \$@; then :; else \\
	  rm -f \$<; \\
	  \$(MAKE) \$(AM_MAKEFLAGS) \$<; \\
	fi

EOF
  fi
done


# More Make variables.
echo "# The list of all generated figures."
gen_var FIGURES $fig_vars
echo
echo "# The list of all generated PBM figures."
gen_var PBM_FIGURES $pbm_fig_paths
echo
echo "# The list of all generated PGM figures."
gen_var PGM_FIGURES $pgm_fig_paths
echo
echo "# The list of all generated PPM figures."
gen_var PPM_FIGURES $ppm_fig_paths
