#!/usr/bin/env bash

set -e -o pipefail -u

function spoonfeed() {
  init_delay=$1
  sleep "$init_delay"

  text=$2
  comp=
  buffer=
  for (( i=0; i<${#text}; i++ )); do
    char=${text:$i:1}
    if [[ $char == '^' ]]; then
      sleep 0.5
      continue
    elif [[ $char == '~' ]]; then
      comp=true
      char=
    elif [[ $char == ' ' || $char == '=' ]]; then
      comp=
    fi
    buffer="${buffer}${char}"
    if ! [[ $comp ]]; then
      echo -n "$buffer"
      buffer=
      sleep 0.15
    fi
  done
  echo "$buffer"
}

function script() {
  spoonfeed 2 'git ma~chete dis~cover --ch~ecked-out-since="2 weeks ago"'
  spoonfeed 5 'y^'
  spoonfeed 1 '~clear'

  spoonfeed 1 'git ma~chete st~atus --l~ist-commits'
  spoonfeed 5 '~clear'

  spoonfeed 1 'git chec~kout d~evelop'
  spoonfeed 1 'git ma~chete tr~averse'
  spoonfeed 4 'y^'
  spoonfeed 4 'yq^'
  spoonfeed 3 '~clear'

  spoonfeed 1 'git ma~chete st~atus --l~ist-commits'
  spoonfeed 5 '~clear'

  spoonfeed 1 'git ma~chete tr~averse'
  spoonfeed 4 'y^'
  spoonfeed 2 'yq^'
  spoonfeed 5 '~clear'
  spoonfeed 1 '~exit'
}

if [[ ${1-} ]]; then
  touch "$1"
  gif_path=$(realpath "$1")
else
  gif_path=/tmp/$(date +%s).gif
fi
cast_path=${gif_path/.gif/.cast}

self_dir=$(cd "$(dirname "$0")" &>/dev/null; pwd -P)
sandbox_dir=$(mktemp -d)
"$self_dir/setup-sandbox" "$sandbox_dir"
cd "$sandbox_dir"/machete-sandbox

script | asciinema rec --command="bash --init-file '$self_dir/bash-init-file'" --overwrite "$cast_path"
# Remove the final lines responsible for the terminating `exit`
cast_line_count=$(wc -l < "$cast_path")
head -n $(( cast_line_count - 5 )) "$cast_path" | sponge "$cast_path"

theme=000000,ffffff,000000,ff0000,00ff00,ffff00,00ffff,ff00ff,00ffff,d9d9d9,4d4d4d,ff0000,00ff00,ffff00,00ffff,ff00ff,00ffff,ffffff
# `--cols=... --rows=...` to fit the text on the screen without breaking the lines
# `--line-height=...` so that the ASCII vertical bars & junctions stick to each other without a visible gap
agg --speed=0.75 --theme="$theme" \
  --cols=122 --rows=35 \
  --font-size=14 --line-height=1.2 \
  "$cast_path" "$gif_path"

echo "Location of the generated GIF file:"
echo "$gif_path"
