#!/sbin/openrc-run
# Copyright 1999-2020 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

description="Virtual Machine Management daemon (libvirt)"

LIBVIRTD_OPTS=${LIBVIRTD_OPTS:-"${LIBVIRTD_OPTS}"}
LIBVIRTD_TIMEOUT=${LIBVIRTD_TERMTIMEOUT:-"TERM/25/KILL/5"}

command="/usr/sbin/libvirtd"
command_args="${LIBVIRTD_OPTS}"
start_stop_daemon_args="-b --env KRB5_KTNAME=/etc/libvirt/krb5.tab"
pidfile="/run/libvirtd.pid"
retry="${LIBVIRTD_TERMTIMEOUT}"

depend() {
	need virtlogd
	use ceph dbus iscsid virtlockd
	after cgconfig corosync ebtables iptables ip6tables nfs nfsmount ntp-client ntpdportmap rpc.statd sanlock xenconsoled
	
}

start_pre() {
	# Test configuration directories in /etc/libvirt/ to be either not
	# present or a directory, i.e. not a regular file, bug #532892

	checkpath --directory /etc/libvirt/lxc || return 1
	checkpath --directory /etc/libvirt/nwfilter || return 1
	[ -L /etc/libvirt/qemu ] ||
		checkpath --directory /etc/libvirt/qemu || return 1
	[ -L /etc/libvirt/storage ] ||
		checkpath --directory /etc/libvirt/storage || return 1
}

# adapted from SBo's rc.libvirt
# https://slackbuilds.org/repository/14.2/libraries/libvirt/
check_running_machines() {

  count=0

  for machine in $(/usr/sbin/virsh list --name --state-running | grep -v ^$) ; do
    /usr/sbin/virsh shutdown $machine
  done

  einfo "Waiting for machines"

  while [ $(/usr/sbin/virsh list --name --state-running | grep -v ^$ | wc -l) -gt "0" ]; do
    if [ "$count" -ge "$TIMEOUT" ];then
      break
    fi
    echo -n "."
    count=$(expr $count + 1)
    sleep 1
  done

  echo ""

  if [ $(/usr/sbin/virsh list --name --state-running | grep -v ^$ | wc -l) -gt "0" ];then

    einfo "The following machines are still running, forcing shutdown: "
    for machine in $(/usr/sbin/virsh list --name --state-running | grep -v ^$) ; do
      /usr/sbin/virsh destroy $machine
      echo -n "$machine "
    done

    echo ""
    sleep 2
  fi

}

stop_pre() {
	check_running_machines
	for network in $(/usr/sbin/virsh net-list | tail -n +3 | awk '{print $1}'); do
		/usr/sbin/virsh net-destroy "$network"
	done
}
