#!/bin/sh
# autopkgtest check: build and run pymol scripts from directory and subdirectories.
# ignores errors appearing inside PYMOL command line, checks if message
# "PyMOL: normal program termination." present in pymol's output.
# 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 [ "$ADTTMP" = "" ] ; then
  ADTTMP=$(mktemp -d /tmp/${pkg}-test.XXXXXX)
  trap "rm -rf $ADTTMP" 0 INT QUIT ABRT PIPE TERM
fi

cd $ADTTMP
error_lines="Traceback
raise
error"
normal_lines='PyMOL: normal program termination.'

for dir in $(find $testsdir -type d); 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'); 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
    command=$(pymol -c $file) 
    echo "Run 'pymol -c $file'..."
    error_lines_present=`echo "$command" | grep -F -i "$error_lines"` || true
    normal_lines_present=`echo "$command" | grep -F -i "$normal_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" ]
    else
      if [ -z "$normal_lines_present" ]; then
        echo "\t\033[31;1mnot ok - line '$normal_lines' was not found in pymol output\033[0m" 1>&2
        [ -z "$normal_lines_present" ]
      else
        # pymol -c $file
        echo "\t\033[32;1mok - line '$normal_lines' presents in pymol output\033[0m"
      fi
    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
