#!/bin/bash

yaml() {
    python3 -c "import yaml;print(yaml.safe_load(open('$1'))$2)"
}

tmplname=$1
if [ -z $tmplname ]; then
    echo Must specify template or VM. Run 'kvmctl' to list all applicable templates and VMs.
    exit 1
fi

if [ -z $CB_JOBID ] || [ -z "$CB_ALLOCATION" ]; then
    echo Please submit the script as an AIP job.
    exit 1
fi

existing_vm=0
if [[ $tmplname == vm-* ]]; then
    existing_vm=1
    vmname=$tmplname
else
    vmname="vm-$tmplname-"$(date +%s)
fi

function sighd() {
    virsh destroy $vmname
    sleep 5
    virsh undefine $vmname
    exit 1
}

umask 0022
SSHDIR=$HOME/.ssh

kvm_yaml_file="/opt/skyformai/etc/kvm.yaml"
tmpl_root_dir=$(yaml $kvm_yaml_file "['template_path']")
vm_root_dir=$(yaml $kvm_yaml_file "['vm_image_path']")
host_gpu_devices=$(yaml $kvm_yaml_file "['gpu_pci_device']['$HOSTNAME']")

vm_ips=""
grep "vm_ips:" $kvm_yaml_file > /dev/null 2>&1
if [ $? == 0 ]; then
    vm_ips=$(yaml $kvm_yaml_file "['vm_ips']")
fi    

if [ $existing_vm == 1 ]; then
    vm_xml_file="$vm_root_dir/$CB_JOB_EXECUSER/$vmname/$vmname.xml"
    vm_img=$(find $vm_root_dir/$CB_JOB_EXECUSER/$vmname/* -name "$vmname*" ! -name "$tmplname.xml")
    os=$(grep libosinfo:os $vm_xml_file | awk -F= '{print $2}'| awk -F/ '{print $4 $5}'|tr -d '\"')
else
    tmpl_xml_file="$tmpl_root_dir/$tmplname/$tmplname.xml"
    if [ ! -f $tmpl_xml_file ]; then
        echo Template xml file $tmpl_xml_file not exist!
        exit 1
    fi

    tmpl_img=$(find $tmpl_root_dir/$tmplname/* -name "$tmplname*" ! -name "$tmplname.xml")
    if [ ! -f $tmpl_img ]; then
        echo Template $tmpl_img not exist!
        exit 1
    fi

    if [ ! -d $vm_root_dir ]; then
        echo VM root directory $vm_root_dir not exist!
        exit 1
    fi
    os=$(grep libosinfo:os $tmpl_xml_file | awk -F= '{print $2}'| awk -F/ '{print $4 $5}'|tr -d '\"')
fi

# Comput VM resource
gpu_res=$(echo $CB_ALLOCATION | awk -F '"Assigned Resource Units":' '{print $2}' | cut -d'{' -f2| cut -d'}' -f1| cut -d':' -f1|tr -d '\"')
gpu_assigned=($(echo $CB_ALLOCATION | awk -F '"Assigned Resource Units":' '{print $2}' | cut -d'{' -f2| cut -d'}' -f1| cut -d':' -f2|cut -d'[' -f2|cut -d']' -f1|sed 's/,/ /g'))
gpu_num=${#gpu_assigned[*]}

cpu_per_gpu=$(yaml $kvm_yaml_file "['resource_per_gpu']['$gpu_res']['cpu']")
vcpu=$(($cpu_per_gpu*$gpu_num))

mem_per_gpu=$(yaml $kvm_yaml_file "['resource_per_gpu']['$gpu_res']['memGB']")
mem_per_gpu=$(($mem_per_gpu*1024))
memMB=$(($mem_per_gpu*$gpu_num))

gpu_devices=""
gpu_device_array=($(echo $host_gpu_devices| cut -d'[' -f2| cut -d']' -f1|sed 's/,/ /g'))
for (( i=0; i<${#gpu_assigned[*]}; i++ ));
do
    index=${gpu_assigned[$i]}
    gpu_devices="$gpu_devices --host-device ${gpu_device_array[$index]}"
done

if [ $existing_vm == 0 ]; then
    # Create VM dir
    vmdir="$vm_root_dir/$CB_JOB_EXECUSER/$vmname"
    mkdir -p $vmdir
    chown -R $CB_JOB_EXECUSER:$CB_JOB_EXECUSER $vm_root_dir/$CB_JOB_EXECUSER

    # Copy VM XML file
    vm_xml_file="$vmdir/$vmname.xml"
    cp $tmpl_xml_file $vm_xml_file
    chown $CB_JOB_EXECUSER:$CB_JOB_EXECUSER $vm_xml_file

    # Create VM image
    img_ext=$(echo $tmpl_img|cut -d'.' -f2)
    vm_img="$vmdir/$vmname.$img_ext"
    cp $tmpl_img $vm_img
    chown $CB_JOB_EXECUSER:$CB_JOB_EXECUSER $vm_img

    # Generate SSH key
    ssh-keygen -f /root/.ssh/key.$vmname -N "" -q
    virt-customize -a $vm_img --ssh-inject $USER:file:/root/.ssh/key.$vmname.pub > /dev/null 2>&1
    mv /root/.ssh/key.$vmname /root/.ssh/key.$vmname.pub $SSHDIR
    chown $CB_JOB_EXECUSER:$CB_JOB_EXECUSER  $SSHDIR/key.$vmname $SSHDIR/key.$vmname.pub
    
    # Set static ip
    if [[ $CB_ALLOCATION == *vmip* && $vm_ips != "" ]]; then
        ip_assigned_index=$(echo $CB_ALLOCATION | awk -F '"Assigned Resource Units":' '{print $2}' | awk -F '"vmip":' '{print $2}'|cut -d'[' -f2|cut -d']' -f1)
        vm_ip_array=($(echo $vm_ips))
        ip=$(echo ${vm_ip_array[$ip_assigned_index]}|sed 's/,//g'|sed "s/'//g")
        
        # Only tested on ubuntu2204
        cat <<EOF >$vmdir/00-installer-config.yaml
network:
  ethernets:
    enp1s0:
        addresses: [$ip/24]
        gateway4: 10.206.1.1
        nameservers:
            addresses: [180.184.1.1]
        dhcp4: false
        dhcp6: false
  version: 2
EOF
        chown $CB_JOB_EXECUSER:$CB_JOB_EXECUSER $vmdir/00-installer-config.yaml
        virt-copy-in -a $vm_img $vmdir/00-installer-config.yaml /etc/netplan > /dev/null 2>&1
    fi
fi

virt-install \
        --name $vmname \
        --vcpus $vcpu \
        --ram $memMB \
        $gpu_devices \
        --network bridge=br0 \
        --virt-type kvm \
        --os-variant $os \
        --disk path=$vm_img \
        --noautoconsole \
        --import > /dev/null 2>&1

trap sighd SIGINT SIGTERM

# get vm ip and cpost ssh key
n=1
ip=""
while true;do
    sleep 5
    virsh qemu-agent-command $vmname '{"execute":"guest-network-get-interfaces"}' > /dev/null 2>&1
    if  [ $? == 0 ]; then
        vm_inters=$(virsh qemu-agent-command $vmname '{"execute":"guest-network-get-interfaces"}')
        ip_array=($(echo $vm_inters | grep -oP '(?<="ip-address":).*?(?=,)'|tr -d '\"'))
        for (( i=0; i<${#ip_array[*]}; i++ ));
        do
            if [[ ${ip_array[$i]} =~ [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3} ]]; then
                if [ "${ip_array[$i]}" != "127.0.0.1" ]; then
                    ip=${ip_array[$i]}
                    break
                fi
            fi
            i=$((i+1))
        done
        break
    fi
    if [ $n == 60 ]; then
      break
    fi
    n=$((n+1))
done

cpost -d "ssh -i key root@$ip" $CB_JOBID > /dev/null 2>&1
cat $SSHDIR/key.$vmname

while true; do sleep 3600; done

