#!/bin/bash

# TODO: antlet name must match the name in the xml

if [ $# -ne 3 ]; then
  echo "Usage: import-antlet <export_file_name> <destination_zpool> <antlet_name>"
  exit 1
fi

export_file=$1
zpool=$2
antlet_name=$3
debug=0

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

# Does export file exist
if [ $debug -eq 0 ]; then echo "**export file check"; fi;
if [ ! -f "$export_file" ]; then
  echo "'$export_file' does not exist" | tee /dev/tty | logger -t import-antlet
  exit 1
fi

# Does antlet exist with same name
if [ `virsh -c qemu:///system list --name --all|grep "^${antlet_name}$"|wc -l` -eq "1" ] || [ `virsh -c lxc:/// list --name --all|grep "^${antlet_name}$"|wc -l` -eq "1" ]; then
  echo "antlet '${antlet_name}' already exists!" | tee /dev/tty | logger -t export-antlet
  exit 1
fi

# Does zpool exist
if [ $debug -eq 0 ]; then echo "**zpool check"; fi;
if [ `zpool list -H -o name | grep "^${zpool}$" | wc -l` -ne 1 ]; then
  echo "zpool '${zpool}' does not exist" | tee /dev/tty | logger -t import-antlet
  exit 1
fi

# zfs receive from export file
if [ $debug -eq 0 ]; then echo "**zfs receive"; fi;
(zfs receive ${zpool}/$antlet_name < $export_file && echo "zfs receive ${zpool}/$antlet_name < $export_file") | tee /dev/tty | logger -t import-antlet 

ret=${PIPESTATUS[0]}
if [ ${ret} -ne 0 ]; then
  echo "Could not zfs receive" >&2
  exit ${ret}
fi

# remove snapshot @exportsnap
if [ $debug -eq 0 ]; then echo "**zfs destroy"; fi;
(zfs destroy ${zpool}/${antlet_name}@exportsnap && echo "zfs destroy @exportsnap") | logger -t import-antlet

ret=${PIPESTATUS[0]}
if [ ${ret} -ne 0 ]; then
  echo "Could not remove @exportsnap" >&2
  exit ${ret}
fi

# Get domain type from xml
if [ $debug -eq 0 ]; then echo "**get domain_type from xml"; fi;
domain_type=`head -n 1 /${zpool}/${antlet_name}/antlet-libvirt.xml | cut -d "'" -f2`

ret=${PIPESTATUS[0]}
if [ ${ret} -ne 0 ]; then
  echo "Could not get domain type from xml" >&2
  exit ${ret}
fi

if [ $debug -eq 0 ]; then echo "**set 'vc' variable"; fi;
case "$domain_type" in

  lxc)
    vc="lxc:///"
    ;;
  kvm)
    vc="qemu:///system"
    ;;
  *)
    echo "Unknown domain type <${domain_type}> for antlet $antlet_name" >&2
    exit 150
    ;;
esac

# virsh define domain
if [ $debug -eq 0 ]; then echo "**virsh define"; fi;
(virsh -c "$vc" define /${zpool}/${antlet_name}/antlet-libvirt.xml 2>&1 && echo "Domain $antlet_name created") | logger -t import-antlet

ret=${PIPESTATUS[0]}
if [ ${ret} -ne 0 ]; then
  echo "Could not define domain" >&2
  exit ${ret}
fi
