#!/bin/bash
######################################################################
#Copyright (C) 2025 Kris Occhipinti
#https://filmsbykris.com
#
#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 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 <http://www.gnu.org/licenses/>.
######################################################################

#prints give file one character at a time
#like a typewriter

# fatal uses SIGUSR1 to allow clean fatal errors
trap "exit 1" 10
PROC=$$

function error() {
  red=$(echo -en "\e[31m")
  normal=$(echo -en "\e[0m")

  echo -e "${red}$@${normal}" >&2
  #  exit 1
  kill -10 $PROC
}

#check if there is an file givin or standard input passed
[[ -z "$1" ]] && [[ -t 0 ]] && error "Input Needed."

#if no file then read standard input
[[ $1 ]] || read -r -d '' text

# if file is given and exists set it's contact as text
[[ $1 ]] && [[ -f $1 ]] && text="$(<$1)"
[[ $text ]] || error "No Text Given"

function typetext() {
  #Read each file one line at a time
  while read l; do
    #read each line one Character at a time
    for ((i = 0; i < ${#l}; i++)); do
      echo -n "${l:$i:1}"
      sleep .01
    done

    #add new line char
    echo ""
  done
  exit
}

#pass text to type function
echo "$text" | typetext
