#!/bin/bash

if [[  "$#" != 1  &&  "$#" != 2   ]]; then
  echo "Usage: xrep <directory> [<image>]"
  echo "Compress and move all output files into <directory>, then copy the last image into images/<directory>.png."
  echo "When <image> is specified, the file <image> is copied instead of the last image."
  exit
fi

if [ -e "$1" ]; then
  echo "sorry, this directory already exists !"
  exit
fi

COM_FILE="comment.txt"
if [ ! -f $COM_FILE ]; then
  vi $COM_FILE
fi

echo "creating $1"
mkdir $1

if [ "$#" == 2 ]; then
  IMG=$1/$2
fi

LOG_FILE="RESCAL.log"
if [ -f $LOG_FILE ]; then
  echo "log file: $LOG_FILE"
  PAR_FILE=$(awk '/\.par$/ {print $NF; exit}' $LOG_FILE )
  echo "parameter file: $PAR_FILE"
  WIND_FILE=$(awk -F'=' '/^Wind_file/ {print $NF}' $PAR_FILE )
  echo "wind file: $WIND_FILE"
  echo "copying input files"
  #cp *.m $1/
  cp $PAR_FILE $1/
  #cp -r ./wind $1/
  if [ $WIND_FILE ]; then
    cp -a $WIND_FILE $1/
  fi
else
  echo "log file not found: $LOG_FILE"
fi

echo "compressing data files"
gzip *.bin 2>/dev/null
gzip *.csp 2>/dev/null
gzip *.data 2>/dev/null
#gzip ALTI*.txt
#gzip AUTOCORREL*.txt

echo "moving output files into $1"
mv *.png $1/ 2>/dev/null
mv *.jpg $1/ 2>/dev/null
mv *.jpeg $1/ 2>/dev/null
mv *.eps $1/ 2>/dev/null
mv *.pdf $1/ 2>/dev/null
#mv *.txt $1/
mv $COM_FILE $1/ 2>/dev/null
mv *.log $1/ 2>/dev/null
mv *.out $1/ 2>/dev/null
mv *.bin.gz $1/ 2>/dev/null
mv *.csp.gz $1/ 2>/dev/null
mv *.data.gz $1/ 2>/dev/null

SRC_FILE="ReSCAL.tar"
if [ -f $SRC_FILE ]; then
  echo "compressing src archive"
  gzip $SRC_FILE
fi
SRC_FILE_GZ="${SRC_FILE}.gz"
if [ -f $SRC_FILE_GZ ]; then
  echo "copying sources into $1"
  mv $SRC_FILE_GZ $1/ 2>/dev/null
else
  echo "src archive not found: $SRC_FILE_GZ"
fi

echo "copying exec files into $1"
cp genesis $1/ 2>/dev/null
cp regenesis $1/ 2>/dev/null
#cp rescal $1/ 2>/dev/null
#cp rescal*.tar.gz $1/ 2>/dev/null
#cp genesis*.tar.gz $1/ 2>/dev/null
#rm -f *.bin 2>/dev/null

if [ -e images ]; then
  model=$(awk '/model/ {print $1; exit}' $1/${LOG_FILE})
  echo model = $model
  if [ -z $IMG ]; then
    IMG=$(ls -1 $1/${model}*.png 2>/dev/null | tail -1)
  fi
  #IMG=$(ls -1 $1/*.png 2>/dev/null | tail -1)
  if [ ! -e "$IMG" ]; then
    echo "no PNG images found"
  elif [ -f images/$1.png ]; then
    echo "file images/$1.png already exists"
  else
    echo "creating $1.png"
    cp $IMG images/$1.png 
  fi
else
  echo "Please create a directory \"images\" for collecting the last images of your simulations in one place"
fi

echo "done"

