#!/bin/bash

os_system=$(lsb_release -d 2> /dev/null | tr -s " " | cut -d ":" -f 2)
if [ -z "${os_system}" ] ; then
  os_system=$(uname -o)
else
  os_system=$(echo ${os_system})
fi
kernel=$(uname -r)
if [ -f /proc/uptime ] ; then
  uptime_sec=$(cat /proc/uptime)
  uptime_sec_cut=$(echo ${uptime_sec} | tr -s " " | cut -d " " -f 1 | cut -d "." -f 1)
  uptime_min=$(expr ${uptime_sec_cut} / 60)
  if [ ${uptime_min} -le 59 ] ; then
    uptime="${uptime_min}min"
  else
    uptime_hour=$(expr ${uptime_min} / 60)
    if [ ${uptime_hour} -le 23 ] ; then
      uptime="${uptime_hour}h"
    else
      uptime_day=$(expr ${uptime_hour} / 24)
      uptime="${uptime_day}d"
    fi
  fi
else
  uptime=$(uptime 2> /dev/null | tr -s " " | cut -d "," -f 1)
  if [ -z "${uptime}" ] ; then
    uptime="Unknown"
  else
    uptime=$(echo ${uptime})
  fi
fi
shell=$(bash --version | head -1 | tr -s " " | cut -d " " -f 4 | cut -d "(" -f 1 | cut -d "-" -f 1)
if [ -f /proc/cpuinfo ] ; then
  cpu_model=$(cat /proc/cpuinfo | grep -i "model name" | head -1 | tr -s " " | cut -d ":" -f 2)
  cpu_model=$(echo ${cpu_model})
elif [ -f /usr/bin/lscpu ] ; then
  cpu_model=$(lscpu 2>/dev/null | grep -i "Model name:" | tr -s " " | cut -d ":" -f 2)
  cpu_model=$(echo ${cpu_model})
else
  cpu_model="Unknown"
fi
if [ -f /proc/meminfo ] ; then
  mem_total_kb=$(cat /proc/meminfo | grep -i "memtotal" | tr -s " " | cut -d ":" -f 2)
  mem_total_kb_num=$(echo ${mem_total_kb} | tr -s " " | cut -d " " -f 1)
  mem_total_gb=$(expr ${mem_total_kb_num} / 1000 / 1000)
  mem_total=$(echo ${mem_total_gb}G)
elif [ -f /usr/bin/lsmem ] ; then
  mem_total=$(lsmem | grep -i "total online memory:" | tr -s " " | cut -d ":" -f 2)
  mem_total=$(echo ${mem_total})
else
  mem_total="Unknown"
fi
arch_system="${HOSTTYPE}"
avaibleUpdates=$(checkUpdates.sh)

if [ -z "${1}" ] ; then
  echo "Syntax: ${0} <hostname>"
else
  figlet " ${1}" > /etc/motd
  echo "" >> /etc/motd
  echo " * OS: ${os_system}" >> /etc/motd
  echo " * Kernel: ${kernel}" >> /etc/motd
  echo " * Uptime: ${uptime}" >> /etc/motd
  echo " * Shell: ${shell}" >> /etc/motd
  echo " * Arch: ${arch_system}" >> /etc/motd
  echo " * CPU: ${cpu_model}" >> /etc/motd
  echo " * Mem: ${mem_total}" >> /etc/motd
  echo " * Updates: ${avaibleUpdates}" >> /etc/motd
  echo "" >> /etc/motd
fi
