#!/bin/sh
PATH=$PATH:/opt/lsb/bin

perl_version() {
  perl_ver=`/usr/bin/perl -V:version | sed "s|version=||g;s|;||g;s|'||g"`
  echo "System perl version is: $perl_ver"
}

save_journal() {
  last_dir=`find results -name '00*e' | sort -n | tail -1 | cut  -c11- | cut -c-2`
  next_dir=`expr $last_dir + 1`
  next_dir=`printf "%02d" $next_dir`
  next_dir="results/00$next_dir"e
  mkdir $next_dir
  mv t/tet_xres $next_dir/journal
  echo "Journal file is $next_dir/journal"
}

unicode_symlink() {
  if [ ! -h lib/unicore/lib ];then
    echo "Creating Unicode Character Database symlink..."
    cd lib/unicore
    if [ -d "$installprivlib/unicore/lib" ];then
      ln -s "$installprivlib/unicore/lib" .
    else
      echo "Cannot find the Unicode Character Database"
      echo "Test uni/class.t will most likely fail"
      sleep 10
    fi
    cd ../..
  fi
}

memoize_symlink() {
  cd lib
  for pfile in blib.pm constant.pm strict.pm;do
    if [ ! -h "$pfile" ]; then
      echo "Creating symlink to system $pfile"
      if [ -f "$installprivlib/$pfile" ];then
        ln -s "$installprivlib/$pfile" .
      else
        echo "Cannot find $pfile in the installed perl"
        echo "Test lib/Tie/Memoize.t will most likely fail"
        sleep 10
      fi
    fi
  done
  cd ..
}

pod_symlink() {
  cd lib/Pod
  if [ ! -h "Functions.pm" ]; then
      echo "Creating symlink to system Functions.pm"
      if [ -f "$installprivlib/Pod/Functions.pm" ];then
        ln -s "$installprivlib/Pod/Functions.pm" .
      else
        echo "Cannot find Pod/Functions.pm in the installed perl"
        echo "Pod tests may fail"
        sleep 10
      fi
    fi
  cd ../..
}

# cleanup in case one switches back and forth from system perl to lsb-perl
clean_symlinks() {
  if [ -h "lib/unicore/lib" ];then
    rm -f lib/unicore/lib
  fi
  cd lib
  for pfile in blib.pm constant.pm strict.pm;do
    if [ -h "$pfile" ];then
      rm -f "$pfile"
    fi
  done
  if [ -h "Pod/Functions.pm" ];then
    rm -f Pod/Functions.pm
  fi
  cd ..
}

# for information only
perl_version
# get $installprivlib
eval `perl '-V:installprivlib'`
unicode_symlink
memoize_symlink
pod_symlink
cd t
TET_ROOT=/opt/lsb-tet3-lite PERL_TEST_Net_Ping=1 PERL_SRC=../.. PERL=/usr/bin/perl /usr/bin/perl harness
cd ..
save_journal
clean_symlinks
