#!/bin/sh
#
#        2023-07/22  Now includes the autoscale .bmo file.
#        2014-12/18  Now uses GIANT_DATA_DIR in addition to BIO_DATA_DIR
# 0.1.2  2014-04-28  Fixed a problem where the script was expecting GNU awk.
# 0.1.1  2013-08-13  Switched to using tarmdl to get all paths related to
#                    the model (i.e. textures).
# 0.1.0  2011-06-03  Added version number.
#

data_dir=${GIANT_DATA_DIR%/}

if [ "$data_dir" = "" ]; then
  data_dir=${BIO_DATA_DIR%/}
fi

fixup_fn() {
  fn=${1#$data_dir/}        # remove the substring equal to the workspace path
  fn=${fn#'$BIO_DATA_DIR'/} # remove the string "$BIO_DATA_DIR/"
  fn=${fn#'$GIANT_DATA_DIR'/} # remove the string "$BIO_DATA_DIR/"

  if [ -f "$fn" ]; then
    echo "$fn"
  elif [ -d "$fn" ]; then
    echo "$fn"
  elif [ -f "$fn.gz" ]; then
    echo "$fn.gz"
  else
    echo ""
  fi
}

full_path_name() {
  if [ ${1#/} = $1 ]; then
    # No leading /
    # must be an easier way to do this
    cwd=`pwd`
    dn=`dirname $1`
    cd $dn
    dir=`/bin/pwd`
    cd $cwd
    echo $dir/`basename $1`
  else
    # Has a leading /
    echo $1
  fi
}

list_main_files() {
  psp="$1"
  # remove the substring equal to the workspace directory
  local_psp=${psp#$data_dir/}
  echo $local_psp

  awk '
    function expand(x)
    {
      gsub("\\$BIO_DATA_DIR/","",x);
      gsub("\\$GIANT_DATA_DIR/","",x);
      gsub("\\$NU_DATA_DIR/","",x);
      return x;
    }

    / *PROBDEF:/ ||
    / *UNSCALEDBODYDEF:/ ||
    / *SCALEDEF:/ ||
    / *LIMITS:/ ||
    / *SEARCHPARAMETERS:/ {
      match($0,"[^:]*: *.*")
      pattern=substr($0,RSTART,RLENGTH)
      sub(/[^:]*: */,"",pattern)
      print expand(pattern)
    }
  ' <"$1"
}


list_files() {
  local psp=$1
  list_main_files "$psp"
  local model=`tagfile -getfile MODEL "$psp"`

  if [ x"$model" != x ]; then
    tarmdl -l "$model"
  fi

  local scaledef=`tagfile -getfile SCALEDEF "$psp"`

  if [ "$scaledef" != "" ]; then
    local bmo=`dirname $scaledef`/`basename $scaledef .sdf`.bmo

    if [ -f $bmo ]; then
      (
        cd $data_dir
        fixup_fn $bmo
      )
    fi
  fi
}


listonly=0

if [ x"$1" = x"-l" ]; then
  listonly=1
  shift
fi

if [ $# != 1 ]; then
  echo >&2
  echo "Usage: tarpsp <options> <psp file>" >&2
  echo >&2
  echo "Description:" >&2
  echo "  Creates a tar file with the entire contents a problem specification." >&2
  echo >&2
  echo "Options:" >&2
  echo "  -l	: Only lists the files that would go into the tar file." >&2
  echo >&2
  exit 1
fi

psp=`full_path_name "$1"`

if [ $listonly = 1 ]; then
  list_files "$psp"
else
  cwd=`pwd`
  cd $data_dir
  psp=`fixup_fn $psp`
  tarfile="$cwd"/`basename "$psp"`.tar.gz
  echo
  tar zcvf "$tarfile" `list_files "$psp"` || exit 1
  echo
  echo "Created $tarfile"
  echo
fi
