#!/bin/bash

# config
MAX_TEMP=40
# set column width
COLUMNS=2
# colors
white="\e[39m"
green="\e[1;32m"
red="\e[1;31m"
dim="\e[2m"
undim="\e[0m"

# disks to check
disks=(sda sdb sdc sdd sde sdf sdg sdi)
logfiles='/var/log/syslog /var/log/syslog.1'

# get all lines with smartd entries from syslog
mapfile -t lines < <(grep -hiP 'smartd\[[[:digit:]]+\]:' $logfiles | grep -iP "(Temperature_Celsius|previous self-test)" | sort -r)

out=""
for i in "${!disks[@]}"; do
    disk=${disks[$i]}
    uuid=$(blkid -s UUID -o value "/dev/${disk}")
    #mapfile -t disklines < <(printf -- '%s\n' "${lines[@]}" | grep "${uuid}")
    temp=$(printf -- '%s\n' "${lines[@]}" | grep "${uuid}" | grep -m 1 "Temperature_Celsius" | awk '{ print $NF }')
    status=$(printf -- '%s\n' "${lines[@]}" | grep "${uuid}" | grep -m 1 "previous self-test" | awk '{ print $(NF-1),$NF }')
    # color green if temp <= MAX_TEMP, else red
    if [[ "${temp}" -gt "${MAX_TEMP}" ]]; then
        color=$red
    else
        color=$green
    fi
    # if temp > 80 assume reading is wrong and set temp to "--"
    if [[ "${temp}" -gt 80 ]]; then
        temp="--"
    fi
    # color green if status is "without error", else red
    if [[ "${status}" == "without error" ]]; then
        status_color=$green
    else
        status_color=$red
    fi
    # print temp & smartd error
    out+="${disk}:,${color}${temp}°C${undim} | ${status_color}${status}${undim},"
    # insert \n every $COLUMNS column
    if [ $((($i+1) % $COLUMNS)) -eq 0 ]; then
        out+="\n"
    fi
done
out+="\n"

printf "\nsmartd status:\n"
printf "$out" | column -ts $',' | sed -e 's/^/  /'
