#!/bin/bash

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 or later of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see
# https://www.gnu.org/licenses/licenses/gpl-3.0.en.html.

if [ "$1" = "-l" ] ; then
   ARG="$1"
   shift
elif [ "$1" = "-r" ] ; then
   ARG="$1"
   shift
   if [[ "$1" =~ ^[0-9]+$ ]] ; then
      n="$1"
      shift
   else
      echo 'number expected after -r.' >&2
      exit 1
   fi
fi

if [ "$1" = "-h" ] || [ "$1" = "--help" ] || [ -z "$*" ] ; then cat << EOF
usage  $(basename "$0") [ -l | -r <n>] <file>..
   Checks whether its arguments contain tabs.
   Binary files are silently ignored.
   If so, the tab positions are shown and a non-zero value is returned.
   Else, returns 0.
   If -l is set, outputs the list of files containing tabs and returns 0.
   If -r is set, silently expands all tabs with size <n> and returns 0.
EOF
exit 0
fi

if [ -n "$ARG" ] ; then
   readarray -t FILES <<< "$(grep -I -l $'\t' "$@")"
   if [ "$ARG" = "-r" ] ; then
      sed -i -f <(
         T=$'\t'
         echo ":label"
         for i in $(seq 0 "$(( n - 1 ))"); do
            SP="$(yes '' | head -n "$(( n - i ))" | tr $'\n' ' ')"
            echo -e "s/^\(\([^$T]\{$n\}\)*\)\([^$T]\{$i\}\)$T/\1\3$SP/; t label"
         done
      ) "${FILES[@]}"
   else
      echo "${FILES[@]}"
   fi
else
   export GREP_COLORS=$GREP_COLORS":ms=41"
   if grep -I --color=always -n -m5 $'\t' "$@" ; then
      echo "Some files contain tabs. Use $(basename "$0") -r <n> [FILES] to expand them with size <n>." >&2
      exit 1
   fi
fi
