#!/bin/bash
# Shows the emblem of security-command.org next to facts about this sandbox,
# in the style of fastfetch. A content file .local/bin/fastfetch replaces it.

# Foreground and background colors of the emblem's pixels.
declare -A fg=([r]=$'\e[38;2;119;31;47m' [g]=$'\e[38;2;92;85;85m')
declare -A bg=([r]=$'\e[48;2;119;31;47m' [g]=$'\e[48;2;92;85;85m')
accent=$'\e[1;31m'
reset=$'\e[0m'

# The emblem of the favicon: r is its red, g its grey, a space the background.
# Two pixel rows share one terminal row through half blocks.
logo=(
  '            rrrrrrrrrrrr           '
  '          rrrrrrr  rrrrrrr         '
  '        rrrr            rrrr       '
  '       rrr                rrr      '
  '      rrr       g  g       rrr     '
  '     rrr       g    g        rr    '
  '    rr     gg ggggggggggg     rr   '
  '   rrr    gg gggggggggg gg    rrr  '
  '   rr     gg  gggggggg  gg     rr  '
  '  rr    gggg r gggggg r gggg    rr '
  '  rr   gggg rr gggg g  r gggg   rr '
  ' rr    gg   r    gg    r   gg    rr'
  ' rr    g g  rr        rrr g g    rr'
  ' rr   rg g  rrrr rr rrrr  g gr   rr'
  ' rr r rr rrrrrrrrrrrrrrrrrr rr r rr'
  ' rrr  rrr g rrrrrrrrr rr g rrr  rrr'
  ' r rrrrrr grrrrrrrrrrrrrrg rrrrrr r'
  ' r  rr  rrrrrrrrrrrrrrrrrrrr  rr  r'
  ' rr  g gg rrrrr rrrr rrrrr gg g  rr'
  ' rr gg gg rrrrrr rr rrrrrr gg gg rr'
  ' rr gg  gg rrrrrr  rrrrrr gg  g  rr'
  ' rr  gg gg  rrrrrrrrrrrr  gg g   rr'
  ' rr  gggggg  rrrrrrrrrr  ggggg   rr'
  '  rr  gg  gg   r    r   gg  gg  rr '
  '  rr  gggg ggg  r  r  ggg ggg   rr '
  '   rr  ggg                ggg  rr  '
  '   rrr   g  gg        gg gg   rrr  '
  '    rr   gg  g       gg  g    rr   '
  '     rr   gggg       ggggg   rr    '
  '      rrr  gg          g   rrr     '
  '       rrr                rrr      '
  '        rrrr            rrrr       '
  '          rrrrrr   rrrrrrr         '
  '            rrrrrrrrrrrr           '
)

# Sizes in the binary units fastfetch prints.
size() {
  awk -v bytes="$1" 'BEGIN {
    split("B KiB MiB GiB TiB", units)
    for (unit = 1; bytes >= 1024 && unit < 5; unit++) bytes /= 1024
    printf "%.2f %s", bytes, units[unit]
  }'
}

usage() { printf '%s / %s (%d%%)' "$(size "$1")" "$(size "$2")" $(($2 > 0 ? $1 * 100 / $2 : 0)); }

plural() { (($1 == 1)) && echo "$1 $2" || echo "$1 ${2}s"; }

format_uptime() {
  local seconds=${1%.*} parts=()
  ((seconds < 60)) && { plural "$seconds" sec; return; }
  ((seconds >= 86400)) && parts+=("$(plural $((seconds / 86400)) day)")
  ((seconds / 3600 % 24)) && parts+=("$(plural $((seconds / 3600 % 24)) hour)")
  ((seconds / 60 % 60)) && parts+=("$(plural $((seconds / 60 % 60)) min)")
  local IFS=,
  local joined="${parts[*]}"
  echo "${joined//,/, }"
}

. /etc/os-release
read -r up _ < /proc/uptime
mem_total=$(awk '/^MemTotal:/ { print $2 * 1024 }' /proc/meminfo)
mem_free=$(awk '/^MemAvailable:/ { print $2 * 1024 }' /proc/meminfo)
if [[ -r /sys/fs/cgroup/memory.max && $(< /sys/fs/cgroup/memory.max) != max ]]; then
  mem_total=$(< /sys/fs/cgroup/memory.max)
  mem_used=$(< /sys/fs/cgroup/memory.current)
else
  mem_used=$((mem_total - mem_free))
fi
# The cgroup limit wins over /proc/meminfo, which may describe the host.
swap=$(awk '/^SwapTotal:/ { print $2 * 1024 }' /proc/meminfo)
[[ -r /sys/fs/cgroup/memory.swap.max && $(< /sys/fs/cgroup/memory.swap.max) != max ]] && swap=$(< /sys/fs/cgroup/memory.swap.max)
read -r disk_size disk_used disk_type < <(df -B1 --output=size,used,fstype / | tail -n 1)
[[ $(awk '$2 == "/" { print $4 }' /proc/mounts | tail -n 1) == ro* ]] && disk_type+=' [Read-only]'
cpu=$(awk -F ': ' '/^model name/ { print $2; exit }' /proc/cpuinfo)
host=container
dmesg 2>/dev/null | grep -q gVisor && host=gVisor

facts=(
  "OS|$PRETTY_NAME $(uname -m)"
  "Host|$host"
  "Kernel|$(uname -sr)"
  "Uptime|$(format_uptime "$up")"
  "Packages|$(dpkg-query -f '.\n' -W | wc -l) (dpkg)"
  "Shell|bash ${BASH_VERSION%%[(-]*}"
  "Terminal|xterm.js"
  "CPU|${cpu:-unknown} ($(nproc))"
  "Memory|$(usage "$mem_used" "$mem_total")"
  "Swap|$( ((swap > 0)) && size "$swap" || echo Disabled)"
  "Disk (/)|$(usage "$disk_used" "$disk_size") - $disk_type"
  "Locale|${LANG:-C}"
)

emblem=()
for ((y = 0; y < ${#logo[@]}; y += 2)); do
  top=${logo[y]} bottom=${logo[y + 1]} line=''
  for ((x = 0; x < ${#top}; x++)); do
    t=${top:x:1} b=${bottom:x:1}
    if   [[ $t == ' ' && $b == ' ' ]]; then line+="$reset "
    elif [[ $t == "$b" ]];             then line+=$'\e[49m'"${fg[$t]}█"
    elif [[ $b == ' ' ]];              then line+=$'\e[49m'"${fg[$t]}▀"
    elif [[ $t == ' ' ]];              then line+=$'\e[49m'"${fg[$b]}▄"
    else                                    line+="${fg[$t]}${bg[$b]}▀"
    fi
  done
  emblem+=("$line$reset")
done

user=${USER:-$(id -un)}
title="$accent$user$reset@$accent$HOSTNAME$reset"
title_width=$((${#user} + 1 + ${#HOSTNAME}))
dashes=$(printf '%*s' "$title_width" '')
info=("$title" "${dashes// /-}")
info_width=$title_width
for fact in "${facts[@]}"; do
  key=${fact%%|*} value=${fact#*|}
  info+=("$accent$key$reset: $value")
  ((${#key} + 2 + ${#value} > info_width)) && info_width=$((${#key} + 2 + ${#value}))
done
blocks() { for color in "$@"; do printf '\e[%sm   ' "$color"; done; printf '%s' "$reset"; }
info+=('' "$(blocks 40 41 42 43 44 45 46 47)" "$(blocks 100 101 102 103 104 105 106 107)")

cols=$(tput cols 2>/dev/null || echo 80)
width=${#logo[0]}
gap=3

echo
if ((cols < width)); then
  printf '%s\n' "${info[@]}"
elif ((cols < width + gap + info_width)); then
  printf '%s\n' "${emblem[@]}" '' "${info[@]}"
else
  offset=$(((${#emblem[@]} - ${#info[@]}) / 2))
  ((offset < 0)) && offset=0
  rows=$((${#emblem[@]} > offset + ${#info[@]} ? ${#emblem[@]} : offset + ${#info[@]}))
  for ((row = 0; row < rows; row++)); do
    left=${emblem[row]:-$(printf '%*s' "$width" '')}
    right=''
    ((row >= offset)) && right=${info[row - offset]}
    printf '%s%*s%s\n' "$left" "$gap" '' "$right"
  done
fi
echo
