#! /bin/bash
#
# zerofetch - a minimalist system information tool for GNU/Linux
# Copyright (C) 2025  Paulina Laura Emilia
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
shopt -s extglob

# Read kernel name and version
if [[ ! -f /proc/version ]] || IFS=' ' read -r kn _ kv _ < /proc/version && [[ $kn != Linux ]]; then
  printf '%s: this script supports only GNU/Linux systems\n' "${0##*/}"
  exit 1
fi

# Read os-release file
ANSI_COLOR=0 PRETTY_NAME=
for or in /usr/lib/os-release /etc/os-release; do
  if [[ -f $or ]]; then
    while IFS== read -r k v; do
      case $k in
      ANSI_COLOR|PRETTY_NAME)
        v=${v##[\"\']}
        declare "$k"="${v%%[\"\']}"
      esac
    done < "$or"
    break
  fi
done

# Calculate uptime
IFS=. read -r us _ < /proc/uptime
u=$((us % 60))s
(((um = us / 60)    > 0)) && u=$((um % 60))m\ $u
(((uh = us / 3600)  > 0)) && u=$((uh % 24))h\ $u
(((ud = us / 86400) > 0)) && u=${ud}d\ $u

# Calculate memory
mu=0
while IFS=': ' read -r k v _; do
  case $k in
  MemTotal)     ((mu += v, mt = v)) ;;
  Shmem)        ((mu += v)) ;;
  MemFree|Buffers|Cached|SReclaimable)
                ((mu -= v)) ;;
  MemAvailable) ((mu = mt - v)); break
  esac
done < /proc/meminfo

# Print all gathered information
printf '\e[%s;1m%s\e[0;1m@\e[22;%s;1m%s\e[m\n\n' "$ANSI_COLOR" "$USER" "$ANSI_COLOR" "$HOSTNAME"
p() { [[ -n $2 ]] && printf '\e[%s;1m%-8s\e[m%s\n' "$ANSI_COLOR" "$1" "$2"; }
p OS      "$PRETTY_NAME $HOSTTYPE"
p Kernel  "$kn $kv"
p Uptime  "$u"
p Shell   "${SHELL##*/}"
p Desktop "${XDG_CURRENT_DESKTOP:-$DESKTOP_SESSION}"
p Memory  "$((mu / 1024)) MiB / $((mt / 1024)) MiB"
