# Fancy waifu motd

MOTDPATH="/usr/share/motd"            # path to motd folder
CACHEFILE="$HOME/.cache/waifu"        # to cache waifu state
RESOLUTION=256                        # resolution of waifu
CENTER=true                           # center motd?
LOLCAT=true                           # use lolcat?
UNAMEARG="-sr"                        # uname arguments
UPTIMEARG="--pretty"                  # uptime arguments
tput_cols=$(/usr/bin/tput cols)       # terminal columns
MINTERMWIDTH=200                      # minimal width of term, to display motd

WAIFUS=$(($(ls $MOTDPATH/waifus/*.256.png | wc -w) - 1))   # count of waifus

output() {
  val=0
  if [ $1 == "true" ]; then val=$(($val + 1)); fi
  if [ $2 == "true" ]; then val=$(($val + 2)); fi
  if [ -f "/usr/games/lolcat" ]; then lx="/usr/games/lolcat"; else lx="/usr/bin/lolcat"; fi
  case "$val" in
    0)
      /usr/bin/cat $MOTDPATH/motd 
      uname $UNAMEARG 
      uptime $UPTIMEARG
      ;;

    1)
      /usr/bin/cat $MOTDPATH/motd | $lx
      uname $UNAMEARG | $lx
      uptime $UPTIMEARG | $lx
      ;;

    2)
      /usr/bin/cat $MOTDPATH/motd | awk '{ z = '$tput_cols' - length; y = int(z / 2); x = z - y; printf "%*s%s%*s\n", x, "", $0, y, ""; }'
      uname $UNAMEARG | awk '{ z = '$tput_cols' - length; y = int(z / 2); x = z - y; printf "%*s%s%*s\n", x, "", $0, y, ""; }'
      uptime $UPTIMEARG | awk '{ z = '$tput_cols' - length; y = int(z / 2); x = z - y; printf "%*s%s%*s\n", x, "", $0, y, ""; }'
      ;;

    3)
      /usr/bin/cat $MOTDPATH/motd | awk '{ z = '$tput_cols' - length; y = int(z / 2); x = z - y; printf "%*s%s%*s\n", x, "", $0, y, ""; }' | $lx
      uname $UNAMEARG | awk '{ z = '$tput_cols' - length; y = int(z / 2); x = z - y; printf "%*s%s%*s\n", x, "", $0, y, ""; }' | $lx
      uptime $UPTIMEARG | awk '{ z = '$tput_cols' - length; y = int(z / 2); x = z - y; printf "%*s%s%*s\n", x, "", $0, y, ""; }' | $lx
      ;;
  esac
}


if [ $tput_cols -gt $MINTERMWIDTH ]
then
  if [ $TERM == "xterm-kitty" ]
  then
    if [ $((0 + RANDOM % 2)) -eq 0 ]
    then
      if [ -f "$CACHEFILE" ]
      then
        WAIFU=$(/bin/cat $CACHEFILE)
      else
        touch $CACHEFILE
        echo 0 > $CACHEFILE
        WAIFU=$((0 + RANDOM % $WAIFUS))
      fi
      if [ $WAIFU -gt $WAIFUS ]
      then
        echo 0 > $CACHEFILE
        WAIFU=$((0 + RANDOM % $WAIFUS))
      else
        echo $(($WAIFU + 1)) > $CACHEFILE
      fi
      if $CENTER; then kitty +kitten icat "$MOTDPATH/waifus/waifu-$WAIFU.$RESOLUTION.png"; else kitty +kitten icat --align left "$MOTDPATH/waifus/waifu-$WAIFU.$RESOLUTION.png"; fi
    else
      if $CENTER; then kitty +kitten icat "$MOTDPATH/waifus/waifu-$((0 + RANDOM % $WAIFUS)).$RESOLUTION.png"; else kitty +kitten icat --align left "$MOTDPATH/waifus/waifu-$((0 + RANDOM % $WAIFUS)).$RESOLUTION.png"; fi
    fi
  fi
  output $LOLCAT $CENTER
fi


