#!/bin/bash
#########################################################
#                                                       #
# This is BashStyle-NG                                  #
#                                                       #
# Licensed under GNU GENERAL PUBLIC LICENSE v3          #
#                                                       #
# Copyright Christopher Roy Bratušek                    #
#                                                       #
#########################################################

. gettext.sh
export TEXTDOMAIN="bashstyle-rc"

prettyprint () {
    LC_NUMERIC=C printf "%0${2}.0f\n" "${1}"
}

case ${1} in
    battery)
        check P "acpi" "'systemkit battery'" || exit 1

        state=$(echo "${acpi_output}" | awk '{print $3}')
        load=$(echo "${acpi_output}" | sed -E 's/.*, ([0-9]+)%,.*/\1/')

        case ${state%,} in
            Charging)      statesign="^" ;;
            Discharging)   statesign="v" ;;
            Full)          statesign="°" ;;
            * )             statesign="|"
                            load="0" ;;
        esac

        [[ ! "$load" =~ ^[0-9]+$ ]] && load=0

        formatted_load=$(prettyprint "${load}" 3)
        echo "${statesign}${formatted_load}"
    ;;

    cpuload)
        NICE_IGNORE=20
        t="0"

        while read -r cpu ni; do
            [[ $ni == *-* || $ni -le ${NICE_IGNORE} ]] && t="$t + ${cpu}"
            [[ ${cpu%%.*} -eq 0 ]] && break
        done < <(ps -Ao "%cpu= ni="| sort -r)

        cpu=$(echo "$t" | bc)
        [[ ! "${cpu#.}x" = "${cpu}x" ]] && cpu="0${cpu}"
        cpu=${cpu%%.*}

        prettyprint "${cpu}" 3
    ;;

    externalip)
        check P "curl" "'systemkit externalip'" || exit 1
        curl_opts="-s -m 5"

        case "${2}" in
            6 | ipv6 )      curl ${curl_opts} icanhazip.com ;;
            4 | ipv4 | * )  curl ${curl_opts} ipv4.icanhazip.com ;;
        esac
    ;;

    internalip)
        interface="${3}"
        if [[ -z "${3}" ]]; then
            interface=$(ip route | awk '/default/ {print $5; exit}')
        fi

        case "${2}" in
            6 | ipv6 )
                ip -6 addr show dev "${interface}" scope link | \
                    awk '/inet6 / {print $2}' | cut -d/ -f1 | head -n 1
            ;;
            4 | ipv4 | * )
                ip -4 addr show dev "${interface}" scope global | \
                    awk '/inet / {print $2}' | cut -d/ -f1 | head -n 1
            ;;
        esac
    ;;

    usedram) prettyprint "$(awk '/MemAvailable/ {avail=$2} END {print int(avail/1024)}' /proc/meminfo)" 5 ;;
    freeram) prettyprint "$(awk '/MemTotal/ {total=$2} /MemAvailable/ {avail=$2} END {print int((total-avail)/1024)}' /proc/meminfo)" 5 ;;
    totalram) prettyprint "$(awk '/MemTotal/ {total=$2} END {print int(total/1024)}' /proc/meminfo)" 5 ;;

    usedram%) prettyprint "$(awk '/MemTotal/ {total=$2} /MemAvailable/ {avail=$2} END {print int(((total-avail)/total)*100)}' /proc/meminfo)" 3 ;;
    freeram%) prettyprint "$(awk '/MemTotal/ {total=$2} /MemAvailable/ {avail=$2} END {print int((avail/total)*100)}' /proc/meminfo)" 3 ;;

    dirsize)
        if check P "diskus" "systemkit dirsize" &>/dev/null; then
            TotalBytes=$(diskus | awk '{print $1}')
        else
            TotalBytes=$(du -s "${2:-.}" | awk '{print $1}')
        fi

        if [[ ${TotalBytes} -lt 1024 ]]; then
                echo "${TotalBytes} KB"
        elif [[ ${TotalBytes} -lt 1048576 ]]; then
                echo "$((TotalBytes/1024)) MB"
        elif [[ ${TotalBytes} -lt 1073741824 ]]; then
                echo "$((TotalBytes/1048576)) GB"
        else    echo "$((TotalBytes/1073741824)) TB"
        fi
    ;;

    usedspace)  df -h --output=used "${2}" | tail -n 1 | tr -d ' ' ;;
    freespace)  df -h --output=avail "${2}" | tail -n 1 | tr -d ' ' ;;
    totalspace) df -h --output=size "${2}" | tail -n 1 | tr -d ' ' ;;
    usedspace%) df --output=pcent "${2}" | tail -n 1 | tr -d ' ' ;;
    freespace%)
        used_pcent
        used_pcent=$(df --output=pcent "${2}" | tail -n 1 | tr -d ' %')

        if [[ "$used_pcent" =~ ^[0-9]+$ ]]; then
            echo "$((100 - used_pcent))%"
        else
            echo "0%"
        fi
    ;;

    cpu)
        echo -e "CPU:
    Model:$(gawk -F : '/model name/{print $2;exit;}' /proc/cpuinfo)
    MHz  :$(gawk -F : '/cpu MHz/{print $2;exit;}' /proc/cpuinfo)\n"
    ;;

    kernel)
        echo -e "Kernel:
    Release: $(uname -r)
    Version: $(uname -v)
    Machine: $(uname -m)\n"
    ;;

    partitions)
        label_device_node=$(eval_gettext "device-node")
        label_type=$(eval_gettext "type")
        label_mount=$(eval_gettext "mount")
        label_used=$(eval_gettext "used")
        label_free=$(eval_gettext "free")
        label_total=$(eval_gettext "total")

        eval_gettext "Partitions:"
        echo -e "\n"

        {
            echo "${label_device_node} ${label_type} ${label_mount} ${label_used} ${label_free} ${label_total}"
            df -h --output=source,fstype,target,used,avail,size -x loop -x tmpfs -x devtmpfs -x squashfs -x efivarfs | tail -n +2 | sort -k3,3
        } | column -t
    ;;

    pci)
        check P "lspci" "'systemkit pci'" || exit 1
        echo -e "$(eval_gettext "PCI Devices:\n\n")" "$(lspci -vkmm)\n"
    ;;

    usb)
        check P "lsusb" "'systemkit usb'" || exit 1
        echo -e "$(eval_gettext "USB Devices:\n\n")" "$(lsusb -v)\n"
    ;;

    bios)
        bios_not_root=$(eval_gettext "You're not root.")
        bios_ask_sudo=$(eval_gettext "Do you want to use sudo? [j/N]: ")
        bios_title=$(eval_gettext "SMBIOS/DMI Info:\n\n")

        if (( EUID == 0 )); then
            check P "dmidecode" "'systemkit bios'" || exit 1
            echo -e "${bios_title}$(dmidecode -q)\n"
        else
            echo "${bios_not_root}" >&2
            read -r -p "${bios_ask_sudo}" answer

            if [[ "${answer}" =~ ^[JjYy]([Aa][Ee][Ss])?$ ]]; then
                check P "sudo" "'systemkit bios'" || exit 1
                echo -e "${bios_title}$(sudo dmidecode -q)\n"
            else
                exit 1
            fi
        fi
    ;;

    load1)  awk '{print $1}' /proc/loadavg ;;
    load5)  awk '{print $2}' /proc/loadavg ;;
    load15) awk '{print $3}' /proc/loadavg ;;

    tty)
        TTY=$(tty)
        echo "${TTY:5}"
    ;;

    uptime)
        uptime_raw=$(</proc/uptime)
        timeused=${uptime_raw%%.*}

        daysused=$(( timeused / 86400 ))
        hoursused=$(( (timeused % 86400) / 3600 ))
        minutesused=$(( (timeused % 3600) / 60 ))
        secondsused=$(( timeused % 60 ))

        h_fmt=$(prettyprint "${hoursused}" 2)
        m_fmt=$(prettyprint "${minutesused}" 2)
        s_fmt=$(prettyprint "${secondsused}" 2)

        echo "${daysused}d ${h_fmt}h:${m_fmt}m:${s_fmt}s"
    ;;

    processes)
        procs=$(ps ax | tail -n +2 | wc -l | tr -d ' ')
        prettyprint "${procs}" 4
    ;;

    cof | countoverallfiles)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -type f -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    cod | countoveralldirs)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -type d -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    coi | countoverallitems)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    cvf | countvisiblefiles)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -type f ! -name ".*" -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    cvd | countvisibledirs)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -type d ! -name ".*" -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    cvi | countvisibleitems)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 ! -name ".*" -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    chf | counthiddenfiles)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -type f -name ".*" -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    chd | counthiddendirs)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -type d -name ".*" -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;
    chi | counthiddenitems)
        find -L "${2:-$PWD}" -maxdepth 1 -mindepth 1 -name ".*" -print0 | tr -cd '\0' | wc -c | tr -d ' '
        ;;

    *)
        bashstyle-help -a "Christopher Roy Bratusek" -e "nano@jpberlin.de" -h "https://www.nanolx.org/"\
            -l "GNU GPL v3" -n "systemkit" -s "$(eval_gettext "show various system information")"\
            -v "${BSNG_VERSION}" -y "${BSNG_YEAR}"\
            -o "$(eval_gettext "battery:|show battery load state using acpi")"\
            -o "$(eval_gettext "cpuload:|show cpu load")"\
            -o "$(eval_gettext "externalip:ipv4/ipv6|show your PCs external ip (default is ipv4)")"\
            -o "$(eval_gettext "internalip:ipv4/ipv6:interface|show interface's internal ip (auto-determined if none given)")"\
            -o "$(eval_gettext "usedram:|used RAM")"\
            -o "$(eval_gettext "usedram%:|used RAM in %")"\
            -o "$(eval_gettext "freeram:|free RAM")"\
            -o "$(eval_gettext "freeram%:|free RAM in %")"\
            -o "$(eval_gettext "totalram:|total RAM")"\
            -o "$(eval_gettext "dirsize:|size of all items in current dir")"\
            -o "$(eval_gettext "usedspace:mount|used space on mountpoint")"\
            -o "$(eval_gettext "freespace:mount|free space on mountpoint")"\
            -o "$(eval_gettext "totalspace:mount|total space on mountpoint")"\
            -o "$(eval_gettext "usedspace%:mount|used space on mountpoint in %")"\
            -o "$(eval_gettext "freespace%:mount|free space on mountpoint in %")"\
            -o "$(eval_gettext "cpu:|show cpu information")"\
            -o "$(eval_gettext "kernel:|show kernel information")"\
            -o "$(eval_gettext "partitons:|show mounted partitions information")"\
            -o "$(eval_gettext "pci:|show pci device information")"\
            -o "$(eval_gettext "usb:|show usb device information")"\
            -o "$(eval_gettext "bios:|show bios information [only root]")"\
            -o "$(eval_gettext "load1:|show load average for 1 minute")"\
            -o "$(eval_gettext "load5:|show load average for 5 minutes")"\
            -o "$(eval_gettext "load15:|show load average for 15 minutes")"\
            -o "$(eval_gettext "tty:|show current TTY device node")"\
            -o "$(eval_gettext "uptime:|show uptime in pretty printed format")"\
            -o "$(eval_gettext "cof:directory|count all files in directory (or pwd)")"\
            -o "$(eval_gettext "cod:directory|count all directories in directory (or pwd)")"\
            -o "$(eval_gettext "coi:directory|count all items in directory (or pwd)")"\
            -o "$(eval_gettext "cvf:directory|count visible files in directory (or pwd)")"\
            -o "$(eval_gettext "cvd:directory|count visible directories in directory (or pwd)")"\
            -o "$(eval_gettext "cvi:directory|count visible items in directory (or pwd)")"\
            -o "$(eval_gettext "chf:directory|count hidden files in directory (or pwd)")"\
            -o "$(eval_gettext "chd:directory|count hidden directories in directory (or pwd)")"\
            -o "$(eval_gettext "chi:directory|count hidden items in directory (or pwd)")"
    ;;
esac
