#!/usr/bin/env bash

detect_os_1 () {

   if $(which lsb_release > /dev/null 2>&1) ; then

      os_dist="$(lsb_release -i | awk '{print tolower($3)}')"
      os_version="$(lsb_release -r | awk '{print tolower($2)}')"
      os_codename="$(lsb_release -c | awk '{print tolower($2)}')"

      if [[ "$os_dist" = "debian" ]]; then
         if $(echo "$os_version" | grep -q '\.') ; then
            os_version=$(echo "$os_version" | cut --delimiter='.' -f1)
         fi
      fi

   elif [[ -e "/etc/os-release" ]]; then

      . /etc/os-release

      os_dist=$ID
      os_version=${VERSION_ID}

   fi

   # remove whitespace from os_dist and os_version
   os_dist="${os_dist// /}"
   os_version="${os_version// /}"

}

detect_os_2 ()
{
  if [[ ( -z "${os}" ) && ( -z "${os_dist}" ) ]]; then
    # some systems dont have lsb-release yet have the lsb_release binary and
    # vice-versa
    if [ -e /etc/lsb-release ]; then
      . /etc/lsb-release

      if [ "${ID}" = "raspbian" ]; then
        os=${ID}
        os_dist=`cut --delimiter='.' -f1 /etc/debian_version`
      else
        os=${DISTRIB_ID}
        os_dist=${DISTRIB_CODENAME}

        if [ -z "$os_dist" ]; then
          os_dist=${DISTRIB_RELEASE}
        fi
      fi

    elif [ `which lsb_release 2>/dev/null` ]; then
      os_dist=`lsb_release -c | cut -f2`
      os=`lsb_release -i | cut -f2 | awk '{ print tolower($1) }'`

    elif [ -e /etc/debian_version ]; then
      # some Debians have jessie/sid in their /etc/debian_version
      # while others have '6.0.7'
      os=`cat /etc/issue | head -1 | awk '{ print tolower($1) }'`
      if grep -q '/' /etc/debian_version; then
        os_dist=`cut --delimiter='/' -f1 /etc/debian_version`
      else
        os_dist=`cut --delimiter='.' -f1 /etc/debian_version`
      fi

    else
      os_dist="unknown"
      os="unknown"
    fi
  fi

  if [ -z "$os_dist" ]; then
    os_dist="unknown"
  fi

  # remove whitespace from OS and os_dist name
  os="${os// /}"
  os_dist="${os_dist// /}"

  echo "Detected operating system as $os/$os_dist."
}

detect_os_1

echo -e "\nOutput from function 'detect_os_1'"
echo "=================================="

echo "Distribution: ${os_dist}"
echo "Version:      ${os_version}"
if [[ -n "$os_codename" ]]; then
   echo "Codename:     ${os_codename}"
fi

os=""
os_dist=""
os_version=""
os_codename=""

echo -e "\nOutput from function 'detect_os_2'"
echo "=================================="
detect_os_2

echo "OS:   $os"
echo "Dist: $os_dist"


echo
exit
