#
# autodetect enviremont: openvz dom0 system, openvz CT, classic system (no virtualization)
#

if [ -n "$debug" ]; then
    echo "debugging active (debug=$debug)"
fi

export is_dom0_host=0
export is_virtual_host=0
export is_classic_host=1
export is_openvz_host=0
export is_lxc_host=0
export is_kvm_host=0

if [ -e /proc/user_beancounters ] && [ -e /proc/vz/version ] ; then
        export is_dom0_host=1
        export is_classic_host=0
	export is_openvz_host=1
fi

if [ -e /proc/user_beancounters ] && [ ! -e /proc/vz/version ] ; then
        export is_virtual_host=1
        export is_classic_host=0
	export is_openvz_host=1
fi

if [ $is_dom0_host -eq 0 ] && [ -e /proc/user_beancounters ] ; then

    SIMFS=$(df -h / | head -n 2 | tail -n 1 | awk '{print $1}' | grep "simfs" |wc -l)
    if [ $SIMFS -eq 0 ] ; then
        #/etc/init.d/vz not running, but it is dom0 system

        export is_virtual_host=0
        export is_classic_host=0
        export is_dom0_host=1
	export is_openvz_host=1
   fi
fi

#
# lxc-detection block
#
if [ $is_openvz_host -eq 0 ] && [ -e /proc/1/cgroup ] ; then
    PATH_OLD=$PATH
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
    if  which lxctl &>/dev/null || which lxc-version &>/dev/null || which lxc-list &>/dev/null || which lxc-create &>/dev/null && grep '^/$' /proc/1/cpuset >/dev/null ; then
	export is_lxc_host=1
	export is_classic_host=0
	export is_dom0_host=1
    else
        if sudo strings /proc/1/environ | egrep -q '=lxc$'; then
	    export is_lxc_host=1
	    export is_classic_host=0
	    export is_virtual_host=1
	fi 
    fi
    PATH=$PATH_OLD
fi

if grep -qi QEMU /proc/cpuinfo ; then
        export is_classic_host=0
        export is_virtual_host=1
	export is_kvm_host=1
fi

#check OpenStack
if dmidecode -q -t 1 2>/dev/null | grep -qi openstack ; then
	export is_virtual_host=1
	export is_kvm_host=1
    export is_classic_host=0
fi

if [ -n "$debug" ]; then
    echo -e "is_dom0_host: $is_dom0_host\nis_virtual_host: $is_virtual_host\nis_classic_host: $is_classic_host"
    echo -e "is_openvz_host: $is_openvz_host\nis_lxc_host: $is_lxc_host\nis_kvm_host: $is_kvm_host\n"
fi
