#! /bin/sh
#
# This script should not need to be run directly,
# but will be automatically executed via "sympow -new_data []"
#
# example direct usages
# sh new_data /bin/sh /usr/bin/gp '-sp 3 -dv 2'
# sh new_data /bin/sh /usr/bin/gp '-cm -sp 4'
# sh new_data /bin/sh /usr/bin/gp '-sp 2'
# sh new_data /bin/sh /usr/bin/gp '-hecke -sp 3 -dv 1'

set -e

if [ -z $SYMPOW_INVOCATIONNAME ];
then
echo "**ERROR**: unset environment variable SYMPOW_INVOCATIONNAME"; exit;
fi

if [ $# != 3 ];
then
echo "**ERROR**: Wrong number of input parameters"; exit;
fi

SYMPOW="$SYMPOW_INVOCATIONNAME ${SYMPOW_OPTS_VERBOSITY:--quiet}"

echo "Running the new_data script for $3"

SH=$1
GP=${SYMPOW_GP:-$2}

echo "Making the datafiles for $3"
echo ""
$SYMPOW -rewarp
$SYMPOW -shell1 "$3" | $SH
echo "Running the gp script"
echo ""
$SYMPOW -pari "$3" | $GP -s 268435456 -f -q > /dev/null
echo ""
for datafiles in "$SYMPOW_CACHEDIR/datafiles" "$SYMPOW_CACHEDIR/sympow/datafiles"; do
  [ -d "$datafiles" ] || continue
  for mesh in "$datafiles"/P*.txt; do
    [ -f "$mesh" ] || continue
    cleaned="${mesh}.sagelite-clean"
    sed -e '/^[[:space:]]*\[logfile is /d' -e '/^[[:space:]]*logfile = /d' "$mesh" > "$cleaned"
    mv "$cleaned" "$mesh"
  done
done
$SYMPOW -shell2 "$3" | $SH
$SYMPOW -rewarp
echo "Finished with $3"

exit 0
