#!/usr/bin/env bash
# This file strips all unit tests from ShellCheck, removing
# the dependency on QuickCheck and Template Haskell and
# reduces the binary size considerably.
set -o pipefail

sponge() {
  local data
  data="$(cat)"
  printf '%s\n' "$data" > "$1"
}

modify() {
  if ! "${@:2}" < "$1" | sponge "$1"
  then
    {
      printf 'Failed to modify %s: ' "$1"
      printf '%q ' "${@:2}"
      printf '\n'
    } >&2
    exit 1
  fi
}

detestify() {
  printf '%s\n' '-- AUTOGENERATED from ShellCheck by striptests. Do not modify.'
  awk '
    BEGIN {
      state = 0;
    }

    /LANGUAGE TemplateHaskell/ { next; }
    /^import.*Test\./ { next; }

    /^module/ {
      sub(/,[^,)]*runTests/, "");
    }

    # Delete tests
    /^prop_/ { state = 1; next; }

    # ..and any blank lines following them.
    state == 1 && /^ / { next; }

    # Template Haskell marker
    /^return / {
      exit;
    }

    { state = 0; print; }
    '
}



if [[ ! -e 'ShellCheck.cabal' ]]
then
  echo "Run me from the ShellCheck directory." >&2
  exit 1
fi

if [[ -d '.git' ]] && ! git diff --exit-code > /dev/null 2>&1
then
  echo "You have local changes! These may be overwritten." >&2
  exit 2
fi

modify 'ShellCheck.cabal' sed -e '
  /QuickCheck/d
  /^test-suite/{ s/.*//; q; }
  '

find . -name '.git' -prune -o -type f -name '*.hs' -print |
  while IFS= read -r file
  do
    modify "$file" detestify
  done