#!/bin/bash
# batch-extract-igt output_dir [input_dir...]

usage() {
  echo "usage: batch-extract-igt DATADIR OUTDIR METHOD"
  echo "  DATADIR:"
  echo "    the directory with subdirectories containing testsuites"
  echo "  OUTDIR:"
  echo "    the directory for output subdirectories"
  echo "  METHOD:"
  echo "    ts      : extract from testsuites in DATADIR"
  echo "    odin    : extract from ODIN files in DATADIR/../odin/X/"
  echo "              where X is the basename of DATADIR (e.g. dev1)"
  echo "    ts+odin : extract using both ts and odin; results will be"
  echo "              concatenated together"
  echo "    tb-ctn  : extract from chintang toolbox files in DATADIR"
  exit 1
}

test $# -eq 3 || usage
test -d "$1" || usage
echo "$3" | grep -E '^(ts|odin|ts\+odin|tb-ctn)$' -q || usage

datadir="$1"
outdir="$2"
method="$3"
mkdir -p "$outdir"

export PATH=scripts/:$PATH

ts-to-igt() {
  if [ -z "$1/testsuite" ]; then
    echo "No suitable testsuite found in $lgdir"
    exit
  fi
  testsuite2igt "$lgdir/testsuite" $outdir
}

odin-to-igt() {
  lg=`basename "$1"`
  setname=`basename $(dirname "$1")`
  odinpath="$1/../../odin/$setname/$lg.txt"
  if [ -z "$odinpath" ]; then
    echo "No suitable testsuite found in $odinpath"
    exit
  fi
  odin2igt "$odinpath" $outdir
}


if [ "$method" == "tb-ctn" ]; then
  PS3="Select the Chintang toolbox file you want to extract from: "
  select TBFILE in `ls -l $datadir | grep -v ^d | awk '{print $9}'`;
  do
    cat "$datadir/$TBFILE" | igt_from_toolbox  > "$outdir/igt"
    cat "$datadir/$TBFILE" | igt_from_toolbox -t | sed -f scripts/tokenizer.sed >  "$outdir/t"
    break
  done
else
  for lgdir in "$datadir"/*; do
    if [ -d "$lgdir" ]; then
      lg=`basename "$lgdir"`
      echo "Converting $lg with $method" >&2
      mkdir -p "$outdir/$lg"
      case "$method" in
        ts)
          ts-to-igt "$lgdir" > "$outdir/$lg/igt"
          ts-to-igt "$lgdir" "-t" | sed -f scripts/tokenizer.sed > "$outdir/$lg/t"
          ;;
        odin)
          odin-to-igt "$lgdir" > "$outdir/$lg/igt"
          odin-to-igt "$lgdir" "-t" | sed -f scripts/tokenizer.sed > "$outdir/$lg/t"
          ;;
        ts+odin)
          ts-to-igt "$lgdir" > "$outdir/$lg/igt"
          ts-to-igt "$lgdir" "-t" | sed -f scripts/tokenizer.sed > "$outdir/$lg/t"
          lastid=$((`grep -o "Igt_id=[0-9]\+" "$outdir/$lg/igt"\
                    | tail -n1 | sed 's/Igt_id=//'` + 1))
          odin-to-igt "$lgdir" "-n $lastid" >> "$outdir/$lg/igt"
          odin-to-igt "$lgdir" "-t" | sed -f scripts/tokenizer.sed >> "$outdir/$lg/t"
        ;;
      esac
    fi
  done
fi
