#!/bin/sh
# Linux login welcome message.
# Install as /etc/profile.d/welcome.sh.

is_direct_run() {
    case "$0" in
        */login_welcome.sh|login_welcome.sh|*/welcome.sh|welcome.sh) return 0 ;;
        *) return 1 ;;
    esac
}

case "$-" in
    *i*) ;;
    *) is_direct_run || return 0 2>/dev/null || exit 0 ;;
esac

get_hostname() {
    command hostname 2>/dev/null || command uname -n 2>/dev/null || echo "unknown"
}

get_current_time() {
    command date '+%F %T' 2>/dev/null \
        || command date '+%Y-%m-%d %H:%M:%S' 2>/dev/null \
        || command date 2>/dev/null \
        || echo "未获取"
}

get_uptime() {
    if command uptime -p >/dev/null 2>&1; then
        command uptime -p
        return
    fi

    if [ -r /proc/uptime ]; then
        awk '{
            s = int($1)
            d = int(s / 86400)
            h = int((s % 86400) / 3600)
            m = int((s % 3600) / 60)
            out = "up "
            if (d > 0) out = out d " days, "
            if (h > 0) out = out h " hours, "
            print out m " minutes"
        }' /proc/uptime
        return
    fi

    command uptime 2>/dev/null | sed 's/^.* up *//;s/, *[0-9][0-9]* users.*//;s/, *load average.*//' || echo "未获取"
}

get_load() {
    if [ -r /proc/loadavg ]; then
        awk '{print " "$1", "$2", "$3}' /proc/loadavg
        return
    fi

    command uptime 2>/dev/null | awk -F'load average:' '{print $2}'
}

get_memory() {
    if command -v free >/dev/null 2>&1; then
        command free -h | awk 'NR==2{print "已用 "$3" / 总计 "$2}'
        return
    fi

    if [ -r /proc/meminfo ]; then
        awk '
            /^MemTotal:/ {total=$2}
            /^MemAvailable:/ {avail=$2}
            END {
                if (total > 0 && avail > 0) {
                    used = total - avail
                    if (total >= 1048576) {
                        printf "已用 %.1fG / 总计 %.1fG\n", used / 1048576, total / 1048576
                    } else {
                        printf "已用 %dM / 总计 %dM\n", used / 1024, total / 1024
                    }
                } else {
                    print "未获取"
                }
            }
        ' /proc/meminfo
        return
    fi

    echo "未获取"
}

get_root_disk() {
    command df -h / 2>/dev/null | awk 'NR==2{print "根分区已用 "$5}'
}

echo "欢迎登录：$(get_hostname)"
echo "当前时间：$(get_current_time)"
echo "运行时间：$(get_uptime)"
echo "负载：$(get_load)"
echo "内存：$(get_memory)"
echo "磁盘：$(get_root_disk)"
