#!/bin/bash

set -e

if [ $# -ne 0 ]; then
  tar -xzf "$1" --wildcards --to-command "$0" '*/*-check.log'
  exit
fi

if ! inhalt=$(grep -F 'skipped:'); then
  exit
fi

ignores=(
  '.* _USER and _PASS to'
  'Test irrelevant'
  'Test is only relevant'
  '\S\+ \(modules\? \)\?not \(compiled\.\|built\)'
  '.* only for perls\? '
  'Perl too new$'
  '.* not applicable for this perl '
  'your perl is new enough'
  'test currently not working'
  '\(Skipping\|not running\) dangerous \(.* \)\?test'
  '[nN]ot running on '
  'not MSWin32$'
  'No tests written yet\.$'
  'requires a git checkout and a unix for git and diff$'
  'no problem on this Perl$'
  'Not implemented yet$'
  'nothing to do when no custom ops$'
  'In progress\.\.\.$'
  'Failing test\. Not yet implemented$'
  'Hangs on none wxMSW platforms$'
  'disabling this test for now$'
  'Disable test entirely until '
  '404 Not Found$'
  'no MANIFEST$'
  'depends too much on specific installed perl$'
  'See \S\+$'
  '.* doesn'"'"'t actually do anything correct$'
)

inhalt=$(
  echo "${inhalt}" | \
    sed "$(printf '/skipped:\s*%s/d\n' "${ignores[@]}")"
)

if [ -z "${inhalt}" ]; then
  exit
fi

. "$(dirname "$(readlink -f "$0")")/perlFunktionen"

cd "${TAR_FILENAME%%/*}"
makepkg --verifysource -f >/dev/null 2>&1
source="${TAR_FILENAME%%/*}/$(
  ls -t | \
    grep -m1 '\.tar\.gz$'
)"
cd ..
main_name=$(
  tar -tzf "${source}" 2> /dev/null | \
    cut -d/ -f1 | \
    sort -u | \
    tail -n1
)

for fix_type in 'dependencies' 'variables' 'author_release' 'spellchecker' 'xvfb'; do

  case "${fix_type}" in
    'dependencies')
      tokens=(
        'Missing dependenc\(y\|ies\):'
        'Test requires module .* but it'"'"'s not found$'
        '\S\+ \([0-9.+]\+ \)\?\(required\|needed\) \(for\|to test\) '
        '\S\+ \([0-9.+]\+ \)\?\(\(is \)\?not \(available\|found\|installed\)\|missed\|required\|unavailable\)'
        'requires \S\+ to test this$'
        'T\(his t\)\?est \(temporarily \)\?requires \S\+$'
        '[Nn]eeds\? \S\+\(, \S\+\)*\( for \(this test\|testing\)\)\?$'
        '\S\+: Can'"'"'t locate \S\+ in @INC'
        'please install \S\+ to run these tests$'
        '\S\+ module not available$'
        'needs \S\+ and \S\+ for testing$'
        'good \S\+ unavailable$'
        'cpanm \S\+$'
      )
    ;;
    'variables')
      tokens=(
        '[Ss]et [A-Z_0-9]\+ \(to enable\|if you want to run\) this test'
        '[A-Z_0-9]\+=1$'
        '.* if the [A-Z_0-9]\+ environment variable '
        'Make \$ENV{[A-Z_0-9]\+} true to run this test$'
        '.* unless you set [A-Z_0-9]\+ to a true value'
        'set [A-Z_0-9]\+ to true if you want to run this test$'
      )
    ;;
    'author_release')
      tokens=(
        'Author tests'
        '.*only for developers\.$'
        '.*for testing by the author$'
        '.*for release candidate testing$'
        '.*runs for the maintainer$'
        'skipping for regular installs'
        '.*Skipping test on plain module install'
      )
    ;;
    'spellchecker')
      tokens=(
        'no working spellchecker found$'
      )
    ;;
    'xvfb')
      tokens=(
        '\$DISPLAY is not set\.$'
      )
    ;;
    *)
      >&2 printf 'Whoops, fix type "%s" unknown.\n' "${fix_type}"
      exit 42
    ;;
  esac

  fixable_tests=$(
    echo "${inhalt}" | \
      sed -n "$(printf '/skipped:\s*%s/{s/skipped:.*$//;s/\s\+\.\+\s*$//;p}\n' "${tokens[@]}")"
  )

  if [ -n "${fixable_tests}" ]; then
    (
      set -e
      content=$(
        tar -Oxzf "${source}" $(
          echo "${fixable_tests}" | \
            sed 's|^|'"${main_name}"'/|'
        ) 2> /dev/null
      )
      case "${fix_type}" in
        'dependencies')
          needed=$(
            echo "${content}" | \
              tr ';' '\n' | \
              sed -n '
                s/^eval "\(.*\)"$/\1/
                /^use /{
                  s/^use //
                  s/^base //
                  s/ .*$//
                  s/^'"'"'\(.*\)'"'"'$/\1/
                  /^[0-9.]\+$/d
                  /^t/d
                  p
                }
              ' | \
              sed '
                s/::/-/g
              ' | \
              tr '[:upper:]' '[:lower:]' | \
              sort -u
          )
          checkdepends=$(
            . "${TAR_FILENAME%%/*}/PKGBUILD"
            printf '%s\n' "${checkdepends[@]}"
          )
          needed=$(
            (
              for need in ${needed}; do
                substituiere "${need}"
                if [ -n "${erg}" ] && [ "${erg}" != 'perl-%skip' ]; then
                  echo "${erg}"
                fi
              done | \
                sort -u
              echo "${checkdepends}" | \
                sed 'p'
            ) | \
              sort | \
              uniq -u
          )
          if [ -n "${needed}" ]; then
            (
              set -e
              cd "${TAR_FILENAME%%/*}"
              if ! grep -q '^checkdepends=(' 'PKGBUILD'; then
                for nach in 'makedepends' 'depends'; do
                  if grep -q "^${nach}"'=(' 'PKGBUILD'; then
                    break
                  fi
                done
                sed -i '
                  /^'"${nach}"'=(/{
                    :a
                      N
                      /)/! ba
                    a checkdepends=()
                  }
                ' 'PKGBUILD'
              fi
              pkgrel=$(
                sed -n '
                  s/^pkgrel=//
                  T
                  s/'"'"'//g
                  p
                ' 'PKGBUILD'
              )
              sed -i '
                s/^pkgrel=.*/pkgrel='"'"$((pkgrel+1))"'"'/
                /checkdepends=(/{
                  i '"$(
                    printf 'checkdepends=(\\\n'
                    printf '%s\n' "${checkdepends}" "${needed}" | \
                      versionsUniq | \
                      sed '
                        s|^|  '"'"'|
                        s|$|'"'"'\\|
                      '
                    printf ')\n'
                  )"'
                  :a
                    /)/!{
                      N
                      ba
                    }
                  d
                }
              ' 'PKGBUILD'
              rm -rf --one-file-system 'src' 'pkg'
              makepkg -Lfrs --asdeps --noconfirm || exit $?
              diff=$(
                {
                  echo "${fixable_tests}"
                  sed -n "
                    /skipped:/!d
                    $(printf '/skipped:\s*%s/d\n' "${ignores[@]}")
                    $(printf '/skipped:\s*%s/{s/skipped:.*$//;s/\s\+\.\+\s*$//;p}\n' "${tokens[@]}")
                  " ${TAR_FILENAME%%/*}-*-check.log
                } | \
                  sort | \
                  uniq -u
              )
              [ -n "${diff}" ] || exit 1
              echo "'${diff}'" >&2
              git add 'PKGBUILD'
            ) || \
              git checkout -- "${TAR_FILENAME%%/*}/PKGBUILD"
            rm -f "${TAR_FILENAME%%/*}/${TAR_FILENAME%%/*}-"*'.log'
          fi
        ;;
        'variables')
        ;;
        'author_release')
        ;;
        'spellchecker')
        ;;
        'xvfb')
        ;;
        *)
          >&2 printf 'Whoops, fix of fix type "%s" not (yet) implemented.\n' "${fix_type}"
          exit
        ;;
      esac
    )
  fi

  inhalt=$(
    echo "${inhalt}" | \
      sed "$(printf '/skipped:\s*%s/d\n' "${tokens[@]}")"
  )

  if [ -z "${inhalt}" ]; then
    exit
  fi

done

#echo "$inhalt" #| \
#  sed "s|^|${TAR_FILENAME%%/*} |"