#!/usr/bin/bash
# vmid
# identify virtualization host type
#
# note: this method uses dmidecode.
# a more accurate method maybe to use systemd-detect-virt 
# which uses this method: https://lwn.net/Articles/301888/

#----------------------------------------------------------------------
# Force ourselves to be root
ChkRoot() {
   if [ $(id -u) != 0 ] ; then
      #echo "You are not root. Attempting to sudo."
      exec sudo $0 $*
      echo "You are not root, and failed to exec sudo"
      exit 1
   fi
} # ChkRoot

#----------------------------------------------------------------------
# Check cmd line params, print usage if needed
Usage() {
   if [ $# -ne 0 ] ; then
      echo '
Usage: vmid

Identify what type of virtualization is running, if any.
Print a string to the stdout and return code for VM type.

Return codes:
0 - no virtualization (bare metal OS)
1 - VMware
2 - Xen
3 - KVM (libvirt)
4 - Qemu
5 - Virtual Box
6 - HyperV

Example:
$ vmid
Detected VMware host.
$ echo $?
1
'
   exit 1
   fi
} # Usage

#----------------------------------------------------------------------
# Input: none
# Output: VIRT=Abbreviation String, VIRC=Integer Code
# Reference: http://unix.stackexchange.com/questions/89714/easy-way-to-determine-virtualization-technology
DetectVM() {

   # Get some DMI info
   Name=$(dmidecode -s system-product-name)
   DMID=/tmp/vmid.$RANDOM.tmp
   dmidecode >$DMID
   VIRT="none"; VIRC=0

   # parse most virtualization types
   case $Name in
      VMware*)      VIRT="VMW"  ; VIRC=1; echo "Detected VMware host"          ;;
      *domU*)       VIRT="Xen"  ; VIRC=2; echo "Detected Xen HVM host"         ;;
      KVM)          VIRT="KVM"  ; VIRC=3; echo "Detected KVM VirtIO host"      ;; # qemu KVM
      Bochs)        VIRT="Qemu" ; VIRC=4; echo "Detected Qemu (emulated) host" ;; # qemu emulated
      VirtualBox*)  VIRT="VB"   ; VIRC=5; echo "Detected VirtualBox host"      ;;
   esac

   # backup case for Xen
   if [ $VIRC -eq 0 ] ; then
      if grep "domU" $DMID ; then
         VIRT="Xen"; VIRC=2;
         echo "Detected Xen host"
      fi
   fi

   # backup case for Xen PV (paravirtualizaton mode)
   if [ $VIRC -eq 0 ] ; then
      if dmesg | grep -qi "Xen version:" ; then
         VIRT="Xen"; VIRC=2;
         echo "Detected Xen PV host"
  fi
      fi

   # microsoft is always a special case
   if [ $VIRC -eq 0 ] ; then
      if grep -qi "Manufacturer: Microsoft" $DMID ; then
         VIRT="HPV"; VIRC=6; # MS VirtualPC or Hyper-V
         echo "Detected Hyper-V host"
      fi
   fi

   # display results
   if [ $VIRC -eq 0 ] ; then
      echo "Detected no virtualization host"
   fi

} # DetectVM

#----------------------------------------------------------------------
# Main
Usage $*
ChkRoot
DetectVM
exit $VIRC

