#!/usr/bin/env bash

reset() {
  tput reset
  tput cnorm
  exit
}

trap reset EXIT
read -ra date < <(date "+%Y %m %d")

if (( date[1] == 12 && date[2] > 25 )); then
  new_year=$(( date[0] + 1 ))
else
  new_year=${date[0]}
fi

clear
tput civis
tput setaf 2
tput bold

lines=2
cols=$(( $(tput cols) / 2 ))
cur_col=$(( cols - 1 ))

for (( needles = 1; needles < 20; needles += 2 )); do
  tput cup "$lines" "$cols"

  for (( needle = 0; needle < needles; ++needle )); do
    printf '*'
  done

  (( lines++ ))
  (( cols-- ))
done

tput sgr0
tput setaf 3

for _ in {1..2}; do
  tput cup "$(( lines++ ))" "$cur_col"
  printf 'MWM\n'
done

tput setaf 1
tput bold
tput cup "$lines" "$(( cur_col - 6 ))"
printf 'HAPPY HOLIDAYS\n'
tput cup "$(( lines + 1 ))" "$(( cur_col - 10 ))"
printf 'And lots of CODE in %d\n' "$new_year"

(( ++cur_col ))
pos=1
color=0
line=( )
column=( )

while true; do
  for needle in {1..35}; do
    if (( pos > 1 )); then
      needle_pos=$(( pos - 1 ))$needle

      tput setaf 2
      tput bold
      tput cup "${line[$needle_pos]}" "${column[$needle_pos]}"
      printf '*'
      unset "line[$needle_pos]"
      unset "column[$needle_pos]"
    fi

    new_line=$(( RANDOM % 9 + 3 ))
    start=$(( cur_col - new_line + 2 ))
    new_col=$(( RANDOM % (new_line - 2) * 2 + 1 + start ))

    tput setaf "$color"
    tput bold
    tput cup "$new_line" "$new_col"
    printf 'o'

    line[$pos$needle]=$new_line
    column[$pos$needle]=$new_col
    color=$(( (color + 1) % 8 ))
    sh=1

    for l in C O D E; do
      tput cup "$(( lines + 1 ))" "$(( cur_col + sh ))"
      printf '%s' "$l"
      (( sh++ ))
      sleep 0.01
    done
  done

  pos=$(( pos % 2 + 1 ))
done