#!/usr/bin/env bash
# Disable nounset etc. for simplicity in login shells
# set -euo pipefail

# ─── COLORS (use ANSI-C quotes so ESC is embedded) ───
RED=$'\e[31m'; GREEN=$'\e[92m'; WGREEN=$'\e[38;5;46m'
BLUE=$'\e[94m'; RESET=$'\e[0m'; STOP=$'\e[0m'
ESC=$'\e'

FIGLET="toilet"
HOSTNAME=$(hostname | tr '[:lower:]' '[:upper:]')

# Force at least this many columns between blocks (0=max squeeze)
MIN_GAP=0

# --- Load toilet output into array, strip trailing whitespace (keep interior spaces)
read_ascii() {
  local out_name="$1"; shift
  mapfile -t "$out_name" < <("$FIGLET" -f doom "$@" | sed -E 's/[[:space:]]+$//')
}

# --- Tight bounding box (remove common left/right blanks across lines)
tighten_block() {
  local name="$1"; declare -n A="$name"
  local lmin=999999 rmax=-1 s len l r i
  for s in "${A[@]}"; do
    len=${#s}; [[ -z "${s// /}" ]] && continue
    l=0; while (( l<len )) && [[ ${s:l:1} == ' ' ]]; do ((l++)); done
    r=$((len-1)); while (( r>=0 )) && [[ ${s:r:1} == ' ' ]]; do ((r--)); done
    (( l<lmin )) && lmin=$l; (( r>rmax )) && rmax=$r
  done
  (( rmax<lmin )) && { lmin=0; rmax=-1; }
  local width=$((rmax-lmin+1)); (( width<0 )) && width=0
  for i in "${!A[@]}"; do s="${A[i]}"; A[i]="${s:lmin:width}"; done
  printf '%d\n' "$width"
}

# --- Build 0/1 mask per line (1=ink, 0=space)
make_masks() {
  local name="$1"; declare -n A="$name"; local out="$2"; declare -n M="$out"
  M=()
  local s line i
  for s in "${A[@]}"; do
    line=""
    for ((i=0;i<${#s};i++)); do
      [[ ${s:i:1} == ' ' ]] && line+="0" || line+="1"
    done
    M+=("$line")
  done
}

# --- Ensure arrays have the same number of rows (pad with empties)
pad_rows() {
  local name="$1"; local rows="$2"; declare -n A="$name"
  while (( ${#A[@]} < rows )); do A+=(""); done
}

# --- Replace a single char in string by index (into variable by name)
set_char() {
  local var="$1" idx="$2" ch="$3"
  local s; s="${!var}"
  local left="${s:0:idx}"; local right=""
  (( idx+1 <= ${#s} )) && right="${s:idx+1}"
  printf -v "$var" '%s%s%s' "$left" "$ch" "$right"
}

# --- Compute maximum safe overlap of block B to composite mask C
max_overlap() {
  # args: compMaskName compWidth blockMaskName blockWidth min_gap
  local cName="$1" cW="$2" bName="$3" bW="$4" gap="$5"
  declare -n CM="$cName" BM="$bName"
  local s best=0
  for ((s=0; s<=cW; s++)); do
    local collided=0
    local start=$((cW - s + gap))
    for i in "${!BM[@]}"; do
      local rm="${BM[i]}"; [[ -z $rm ]] && continue
      local j pos
      for ((j=0; j<${#rm}; j++)); do
        [[ ${rm:j:1} == "0" ]] && continue
        pos=$((start + j))
        if (( pos>=0 && i<${#CM[@]} && pos<${#CM[i]} )); then
          [[ ${CM[i]:pos:1} == "1" ]] && { collided=1; break; }
        fi
      done
      (( collided )) && break
    done
    (( collided )) && break
    best=$s
  done
  printf '%d\n' "$best"
}

# --- Overlay block mask into composite at absolute start column
overlay_masks() {
  # args: compMaskName start blockMaskName
  local cName="$1" start="$2" bName="$3"
  declare -n CM="$cName" BM="$bName"
  local need_w=$start i
  for i in "${!BM[@]}"; do
    (( need_w < start + ${#BM[i]} )) && need_w=$(( start + ${#BM[i]} ))
  done
  for i in $(seq 0 $(( ${#BM[@]} - 1 )) ); do
    [[ -z ${CM[i]+x} ]] && CM[i]=""
    while (( ${#CM[i]} < need_w )); do CM[i]+="0"; done
    local rm="${BM[i]}" j pos
    for ((j=0; j<${#rm}; j++)); do
      [[ ${rm:j:1} == "0" ]] && continue
      pos=$((start + j))
      if (( pos >= ${#CM[i]} )); then
        while (( ${#CM[i]} <= pos )); do CM[i]+="0"; done
      fi
      set_char "CM[i]" "$pos" "1"
    done
  done
}

# --- Print a single line's non-space runs at absolute columns (1-based)
print_runs() {
  # args: color startCol0 lineString
  local color="$1" start0="$2" line="$3"
  local n=${#line} k=0
  while (( k<n )); do
    while (( k<n )) && [[ ${line:k:1} == ' ' ]]; do ((k++)); done
    (( k>=n )) && break
    local run_start=$k
    while (( k<n )) && [[ ${line:k:1} != ' ' ]]; do ((k++)); done
    local run_len=$((k - run_start))
    # Use %b so color/reset escape sequences are interpreted
    printf $'\e[%dG%b%.*s%b' $((start0 + run_start)) "$color" "$run_len" "${line:run_start}" "$RESET"
  done
}

# === Build blocks ===
read_ascii HOST  "$HOSTNAME"
read_ascii DOT   "."
read_ascii ARAD5 "ARAD5"
read_ascii COM   "com"

# Tighten
w_HOST=$(tighten_block HOST)
w_DOT=$(tighten_block DOT)
w_ARAD5=$(tighten_block ARAD5)
w_COM=$(tighten_block COM)

# Equalize height
rows=${#HOST[@]}
(( ${#DOT[@]}   > rows )) && rows=${#DOT[@]}
(( ${#ARAD5[@]} > rows )) && rows=${#ARAD5[@]}
(( ${#COM[@]}   > rows )) && rows=${#COM[@]}
pad_rows HOST "$rows"; pad_rows DOT "$rows"; pad_rows ARAD5 "$rows"; pad_rows COM "$rows"

# Masks
make_masks HOST  M_HOST
make_masks DOT   M_DOT
make_masks ARAD5 M_ARAD5
make_masks COM   M_COM

# Compose with kerning
COMP_MASK=()
for i in $(seq 0 $((rows-1))); do COMP_MASK[i]="${M_HOST[i]}"; done
COMP_W=${#COMP_MASK[0]}
declare -A START
START[HOST]=0

overlap=$(max_overlap COMP_MASK "$COMP_W" M_DOT "$w_DOT" "$MIN_GAP")
START[DOT1]=$((COMP_W - overlap + MIN_GAP))
overlay_masks COMP_MASK "${START[DOT1]}" M_DOT
(( COMP_W = (COMP_W > START[DOT1] + w_DOT) ? COMP_W : START[DOT1] + w_DOT ))

overlap=$(max_overlap COMP_MASK "$COMP_W" M_ARAD5 "$w_ARAD5" "$MIN_GAP")
START[ARAD5]=$((COMP_W - overlap + MIN_GAP))
overlay_masks COMP_MASK "${START[ARAD5]}" M_ARAD5
(( COMP_W = (COMP_W > START[ARAD5] + w_ARAD5) ? COMP_W : START[ARAD5] + w_ARAD5 ))

overlap=$(max_overlap COMP_MASK "$COMP_W" M_DOT "$w_DOT" "$MIN_GAP")
START[DOT2]=$((COMP_W - overlap + MIN_GAP))
overlay_masks COMP_MASK "${START[DOT2]}" M_DOT
(( COMP_W = (COMP_W > START[DOT2] + w_DOT) ? COMP_W : START[DOT2] + w_DOT ))

overlap=$(max_overlap COMP_MASK "$COMP_W" M_COM "$w_COM" "$MIN_GAP")
START[COM]=$((COMP_W - overlap + MIN_GAP))
overlay_masks COMP_MASK "${START[COM]}" M_COM
(( COMP_W = (COMP_W > START[COM] + w_COM) ? COMP_W : START[COM] + w_COM ))

# --- PRINT ---
echo -ne '\e[?7l' 
printf '%b' "${ESC}[?7l"   # disable wrap
for i in $(seq 0 $((rows-1))); do
  printf $'\e[1G'          # column 1
  print_runs "$RED"    $((START[HOST]+1))  "${HOST[i]}"
  print_runs "$GREEN"  $((START[DOT1]+1))  "${DOT[i]}"
  print_runs "$WGREEN" $((START[ARAD5]+1)) "${ARAD5[i]}"
  print_runs "$GREEN"  $((START[DOT2]+1))  "${DOT[i]}"
  print_runs "$BLUE"   $((START[COM]+1))   "${COM[i]}"
  printf '\n'
done
printf '%b' "${ESC}[?7h"   # re-enable wrap

# Footer
printf '%b\n' "${RED}Use of this system agrees to the folllowing conditions:${RESET}"
printf '%b\n' \
  "${RED} 1. ${RESET}Mayhem must ensue       ${RED}   3. ${RESET}Fuckery will be had${RESET}" \
  "${RED} 2. ${RESET}Shits shall not be given${RED}   4. ${RESET}Commits will be questionable${RESET}" \
  "${STOP}"
echo -ne '\e[?7h'
