#!/bin/bash


if [ $# -ne 2 ]; then
  echo "Usage: export-antlet <antlet-name> <destination-directory>"
  echo " "
  echo "This utility wil create a file in the destination-directory with"
  echo "the following naming convention:"
  echo "- antlet_name.date-time.type.ipX.export"
  exit 1
fi

debug=0

antlet_name=$1
dest_dir=$2


echo "Calling command: export-antlet $*" | logger -t export-antlet

# Does antlet exist and get antlet type: KVM or LXC
if [ `virsh -c qemu:///system list --name --all|grep "^${antlet_name}$"|wc -l` -eq "1" ]; then
  antlet_type=qemu
elif [ `virsh -c lxc:/// list --name --all|grep "^${antlet_name}$"|wc -l` -eq "1" ]; then
  antlet_type=lxc
else
  echo "antlet '${antlet_name}' does not exist!" | tee /dev/tty | logger -t export-antlet
  exit 1
fi

# Remove trailing / in destination path
last_char=${dest_dir: -1}
if [ "$last_char" = "/" ]; then
  dest_dir=${dest_dir%?}
fi

# Does the destination path exist
if [ ! -d "$dest_dir" ]; then
  echo "'${dest_dir}' is not a directory or does not exist" | tee /dev/tty | logger -t export-antlet
  exit 1
fi

# Get antlet zfs path
zfs_path=`zfs list -H -o name | grep "/${antlet_name}$"` 

## dumpxml to antlet directory
if [ $debug -eq 1 ]; then echo "+dumpxml $antlet_type"; fi
if [ "$antlet_type" = "qemu" ]; then
  virsh -c qemu:///system dumpxml $antlet_name > /${zfs_path}/antlet-libvirt.xml
else
  virsh -c lxc:/// dumpxml $antlet_name > /${zfs_path}/antlet-libvirt.xml
fi
echo "${antlet_name}: dumpxml to antlet directory" | logger -t export-antlet

# Get antlet details from xml.. only using mac addr in file name
#memory=`grep "<memory unit" /${zfs_path}/antlet-libvirt.xml | tr -d " " | tr "<>" "\t" | cut -f3`
#cpu=`grep "<vcpu placement" /${zfs_path}/antlet-libvirt.xml| tr -d " " | tr "<>" "\t" | cut -f3`
mac=`grep "<mac address='b2:61:6e" /${zfs_path}/antlet-libvirt.xml | cut -d ":" -f6 | tr -d "'/>" | tr "[a-f]" "[A-F]"`
# convert hex to decimal
ip=`echo "obase=10; ibase=16; $mac" | bc`


# create snapshot
if [ $debug -eq 1 ]; then echo "+snapshot"; fi
(zfs snapshot ${zfs_path}@exportsnap && echo "${antlet_name}: export snapshot created") | logger -t export-antlet

## zfs send to file
if [ $debug -eq 1 ]; then echo "+zfs send"; fi
bu_time=`date +"%Y%m%d-%H%M%S"`
(zfs send ${zfs_path}@exportsnap > ${dest_dir}/${antlet_name}.${bu_time}.${antlet_type}.ip${ip}.export && echo "${antlet_name}: zfs send to ${dest_dir}/${antlet_name}=${bu_time}.export") | logger -t export-antlet

## zfs destroy snapshot
if [ $debug -eq 1 ]; then echo "+zfs destroy"; fi
(zfs destroy ${zfs_path}@exportsnap && echo "${antlet_name}: zfs destroyed ${zfs_path}@exportsnap") | logger -t export-antlet

