#!/bin/sh
# autopkgtest check: build and run pymol scripts from directory and subdirectories.
# ignores errors appearing inside PYMOL command line but looks for tracebacks or
# exceptions being raised. pymol provides no indication of successful exit when
# run in batch mode.
# Author: Tatiana Malygina <merlettaia@gmail.com>

set -e

testsdir="$(cd "$1" && pwd)"
skipped_pattern="$2" # this is optional
echo "Search pymol scripts in $testsdir..."

pkg=pymol

if [ "$AUTOPKGTEST_TMP" = "" ] ; then
  AUTOPKGTEST_TMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  trap "rm -rf $AUTOPKGTEST_TMP" 0 INT QUIT ABRT PIPE TERM
fi

cd $AUTOPKGTEST_TMP
error_lines="Traceback
raise
error"

for dir in $(find $testsdir -type d | sort); do
  echo "Processing new directory $dir"
  # 1. select .py and .pml and run with pymol in temporary dir
  for file in $(find $dir/* -name '*.py' -or -name '*.pml' | sort); do
    if [ -n "$skipped_pattern" ]; then
      if [ -n "$(echo $file | egrep $skipped_pattern)" ]; then
        echo "Skip $file"
        # skip file if it matches provided pattern
        continue
      fi
    fi
    echo "Run 'pymol -c $file'..."
    command=$(pymol -c $file)
    error_lines_present=`echo "$command" | grep -F -i "$error_lines"` || true
    if [ -n "$error_lines_present" ]; then
      echo -n "\033[35m"
      pymol -c $file
      echo -n "\033[0m"
      echo '\t\033[31;1mnot ok - error-related patterns were found in pymol output\033[0m'
      [ -n "$error_lines_present" ]
    fi
  done
  # 2. delete all files and symlinks in current directory after folder processing, processing next
  for file in $(find -P . -type f); do
    rm $file
  done
done
