#!/bin/bash

__command_ARG=""
__ssh_option_ARG="StrictHostKeyChecking=no"
_help_show_args="user@kvm-name"
. `dirname $0`/_option_processor 2> /dev/null

# Find the hostnames and ip
# The first occurance is the newest ip
KvmIps=$(
cat /var/lib/libvirt/dnsmasq/*.status | \
egrep '{|ip-address|hostname|expiry-time' | \
sed -e 's/^[[:space:]]*//' \
    -e 's/^{$/#/' -e 's/[^:]*://' \
    -e 's/[",[:space:]]//g' | \
tr '#\n' '\n ' | \
awk '{print $2 " " $3 " " $1}' | \
egrep '^[^ ]{1,} [^ ]{1,} [^ ]{1,}$' | \
sort -r | \
tr ' ' '#' | \
sed 's/#[^#]*#/#/'
)

# Create SedArgs array
unset SedArgs

if [ "$__ip" = "" ]
then
   for Opt in `echo $__ssh_option_ARG`
   do
      Sp='[:space:]'
      SedArgs[${#SedArgs[@]}]='-e'
      SedArgs[${#SedArgs[@]}]="s#^[^$Sp]*[$Sp][$Sp]*#\\\0-o\\ $Opt\\ #"
   done
fi

for KvmIp in $KvmIps
do
   Host=`echo $KvmIp | sed 's/#.*//'`
   Ip=`echo $KvmIp | sed 's/.*#//'`
   if ! echo "${SedArgs[@]}" | grep -q "s#$Host#"
   then
      SedArgs[${#SedArgs[@]}]='-e'
      SedArgs[${#SedArgs[@]}]="s#$Host#$Ip#g"
   fi
done

# If we have no SedArgs, cat the result
if [ ${#SedArgs[@]} -gt 0 ]
then
   Sed=sed
else
   Sed=cat
fi

# If the first arg is not a command and the
# command option is not provided, use ssh
if ! which "$(echo $1 | eval $(echo $Sed ${SedArgs[@]}))" &> /dev/null &&
   [ "$__command" != "yes" ]
then
   __command_ARG="ssh"
fi

if [ "$__ip" = "yes" ]
then
   echo $* | eval $(echo $Sed ${SedArgs[@]})
else
   echo "# $(echo $__command_ARG $* | eval $(echo $Sed ${SedArgs[@]}))"
   exec $(echo $__command_ARG $* | eval $(echo $Sed ${SedArgs[@]}))
fi
