#!/bin/sh -e

cpid=$(pidof caddy)
# shellcheck disable=SC2009
caddymemusage=$(
  ps axo rss,comm,pid | grep "${cpid}" \
    | awk '{ $1/=1024; printf "%.0fMB\t",$1 }{ print $2 }' | awk '{ print $1 }'
)

secs=$(
  ps -p "${cpid}" -oetime= | tr '-' ':' \
    | awk -F: '{ total=0; m=1; } {
    for (i=0; i < NF; i++) { total += $(NF-i)*m; m *= i >= 2 ? 24 : 60 }
    } { print total }'
)

if [ "${secs}" -lt 120 ]; then
  caddyuptime="${secs} seconds"

elif [ "${secs}" -lt 3600 ]; then
  caddyuptime=$(printf '%d minutes %d seconds\n' \
    $((secs % 3600 / 60)) $((secs % 60)))

elif [ "${secs}" -lt 86400 ]; then
  caddyuptime=$(printf '%d hrs %d min %d sec\n' \
    $((secs / 3600)) $((secs % 3600 / 60)) $((secs % 60)))

else
  ups=$(date -d "1970-01-01 + ${secs} seconds" "+%H hrs %M min %S sec")
  caddyuptime=$($((secs / 86400)) days, "${ups}")
fi

freeram=$(free -h | grep Mem: | awk '{ print $7 }')

info() { printf '%s\n' "$*" >&2; }
header() { printf "\033[0;34m%s\e[0m\n" "$*" >&2; }

header " Caddy is running"
info " Caddy (PID: ${cpid}) is using ${caddymemusage} RAM"
info " System available RAM ${freeram}B"
info " Uptime - ${caddyuptime}"
printf "\n"
