#!/bin/bash
config=~/scripts/config/tux.txt
invert=1

clean () {
   echo -e "\e[$(($(tput lines) +1));0H\e[m"
}

trap clean EXIT

setColor () {
  l_h=$(($h*$maxh/$winh))
  l_w=$(($w*$maxw/$winw))
  l_line=${lines[$l_h]}
  
  if (($l_w < ${#l_line})) && [ "${l_line:$l_w:1}" != " " ]
  then
    if (( ! $inverted ))
    then
      c=$(((c+3)%7 +1))
      inverted=1
    fi
    echo -ne "\e[30;${du}${c}m"
  else
    if (( $inverted ))
    then
      c=$(((c+4)%7 +1))
      inverted=0
    fi
    echo -ne "\e[30;${he}${c}m"
  fi
}

writeleer () {
   for (( j=$w; $((w-j)) < $1; w++ )) do
      setColor
      echo -n " "
   done
}

setPos () {
   h=$1
   w=$2
   echo -ne "\e[${h};${w}H"
}

# INIT #
IFS=''
lines=()

maxw=0
maxh=0
eval config=$config
if [ -f "$config" ]
then
  while read -r line
  do
    lines[$maxh]="$line"
    maxh=$(($maxh+1))
    lw=${#line}
    if (($lw > $maxw))
    then
      maxw=$lw
    fi
  done < <(cat $config)
else
  lines[0]=""
  invert=0
fi

if (( $invert ))
then
  he=4
  du=10
else
  he=10
  du=4
fi
inverted=0


# LOOP #
while [ 1 ]
do
   u=0
   
   winw=$(tput cols)
   winh=$(tput lines)
   ml=$(((RANDOM%winw +2)/2))
   
   w=$((RANDOM%winw +1))
   h=$((RANDOM%winh +1))
   l=$((RANDOM%ml +1))
   c=$((RANDOM%7 +1))
   
   setPos $h $w
   
   if [ $h -eq $winh -a $((l + w)) -ge $winw ]
   then
      let newl=w+l-winw
      let l=winw-w+1
      u=1
   fi
   
   v=$((i%7 +1))
   echo -ne "\e[30;"4$c"m"
   
   writeleer $l
   if [ $u -eq 1 ]
   then
      setPos 0 0
      writeleer $newl
   fi
   
   let i++
done
