#!/usr/bin/env bash
#
# kvmx-supervise handles all registered kvmx instances in a system
#
# Copyright (C) 2017 Silvio Rhatto - rhatto at riseup.net
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 3 of the License,
# or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# Parameters
BASENAME="`basename $0`"
DIRNAME="`dirname $0`"
INSTANCES="`ls -1 /home/*/.config/kvmx/*`"
ACTION="$1"

# Load basic functions
export APP_BASE="`$DIRNAME/kvmx app_base`"
source $APP_BASE/lib/kvmx/functions || exit 1

# Calculate version
VERSION="`$APP_BASE/kvmx version`"

# Initialize
function __kvmx_supervise_initialize {
  #if [ "`whoami`" != "root" ]; then
  #  echo "$BASENAME: needs root privileges"
  #  exit 1
  #fi

  # Put startup code here
  true
}

# Display usage
function kvmx_supervise_usage {
  echo "$BASENAME $VERSION - virtual machine supervisor"
  echo ""
  echo "usage: $BASENAME <action> [options]"
  echo ""
  echo "available actions:"
  echo ""
  grep "^function kvmx_supervise_" $0 | cut -d ' ' -f 2 | \
    sed -e 's/kvmx_supervise_//' | sort | xargs -L 6 | column -t -c 6 | sed -e 's/^/\t/'
  echo ""

  #local list="`kvmx_supervise_list`"

  #if [ ! -z "$list" ]; then
  #  echo "available virtual machines:"
  #  echo ""
  #  echo "$list" | sed -e 's/^/\t/'
  #  echo ""
  #fi

  exit 1
}

# Call
function kvmx_supervise_call {
  local user="$1"
  local vm="$2"

  shift 2
  local params=($*)

  # Check parameters
  if [ -z "$vm" ]; then
    kvmx_supervise_usage
    exit 1
  fi

  # Check for existing VM
  if [ ! -e "/home/$user/.config/kvmx/$2" ]; then
    kvmx_supervise_usage
    exit 1
  fi

  # When running as root, operate only with VMs configured with supervise_manage=1
  # Specify /bin/bash to avoid restricted shells like kvmx-shell
  if [ "`whoami`" == "root" ]; then
    supervise_manage="`su $user -s /bin/bash -c "kvmx config $vm supervise_manage"`"
  else
    supervise_manage="1"
  fi

  # Dispatch
  if [ "$supervise_manage" == "1" ]; then
    if [ "`whoami`" == "root" ]; then
      su $user -s /bin/bash -c "kvmx ${params[0]} $vm ${params[@]:1}"
    else
      if [ "`whoami`" == "$user" ]; then
        kvmx ${params[0]} $vm ${params[@]:1}
      fi
    fi
  fi
}

# Foreach
function kvmx_supervise_foreach {
  local user
  local vm

  for instance in $INSTANCES; do
    user="`echo $instance | cut -d / -f 3`"
    vm="`basename $instance`"

    #echo "$BASENAME: $vm guest..."
    kvmx_supervise_call $user $vm $*
  done
}

# Status
function kvmx_supervise_status {
  kvmx_supervise_foreach status
}

# Start
function kvmx_supervise_start {
  kvmx_supervise_foreach start
}

# Stop
function kvmx_supervise_poweroff {
  kvmx_supervise_foreach poweroff
}

# Restart
function kvmx_supervise_restart {
  kvmx_supervise_foreach restart
}

# Dispatch
if type kvmx_supervise_$ACTION 2> /dev/null | grep -q "kvmx_supervise_$ACTION ()"; then
  __kvmx_supervise_initialize $*

  shift
  kvmx_supervise_$ACTION $*
else
  kvmx_supervise_usage
fi