#!/bin/sh
#
# USAGE: ostype [OPTIONS]
#
# OPTIONS:
#    -h|--help          Show this help text
#    -d|--distribution  Print the (Linux) distribution instead of OS name
#    -f|--family        Print the OS/distribution family instead of OS name
#    -v|--version       Print the major OS version number
#
# This utility script prints the name of the current operating system in 
# lower case. This is not necessarily the same as the output from uname.
#


OPMODE="o"

if [ "$1" != "" ]; then
case "$1" in

   -h|--help)
      head -12 $0 | tail -11 | cut -c3- 
      exit 0
      ;;

   -d|--distribution)
      OPMODE="d"
      ;;

   -f|--family)
      OPMODE="f"
      ;;

   -v|--version)
      OPMODE="v"
      ;;

   *)
      echo "ERROR: Invalid argument $1"
      echo ""
      head -12 $0 | tail -11 | cut -c3-
      exit 1;
      ;;

esac
fi

OSNAME=`uname | tr [:upper:] [:lower:]`
if [ "$OSNAME" = "sunos" ]; then
   OSNAME="solaris"
fi

if [ "$OPMODE" = "o" ]; then
   echo $OSNAME
   exit 0
fi


if [ "$OSNAME" = "linux" ]; then
   OSDIST=`awk -F'=' '/^ID=/ {print tolower($2)}' /etc/*-release | tr -d \" 2> /dev/null`
else
   OSDIST=$OSNAME
fi

if [ "$OPMODE" = "d" ]; then
   echo $OSDIST
   exit 0
fi


if [ "$OSNAME" = "linux" ]; then
   case "$OSDIST" in
      "rhel"|"centos"|"almalinux"|"rocky"|"ol")
         OSFAM="rhel"
         OSVER_MAJOR=`rpm -E "%{rhel}"`
         ;;
      "ubuntu"|"debian")
         OSFAM="debian"
         OSVER_MAJOR=`lsb_release -r 2>/dev/null|awk '{print $2}'|cut -d. -f1`
         ;;
      *)
         OSFAM=$OSDIST
         ;;
   esac
else
   OSFAM=$OSDIST
   OSVER_MAJOR=11
fi

if [ "$OPMODE" = "f" ]; then
   echo $OSFAM
   exit 0
fi

if [ "$OPMODE" = "v" ]; then
   echo $OSVER_MAJOR
   exit 0
fi

echo "ERROR: Unexpected OPMODE"
exit 99


