#!/bin/bash

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

usage() {
    echo "Usage: $0 list-templates"
    echo "       $0 list-vms"
    echo "       $0 list-specs"
    echo "       $0 delete-image --vm=vm_name"
    exit 1
}

while [ $# != '0' ]; do
  case $1 in
  *=*) optarg=`expr "X$1" : '[^=]*=\(.*\)'` ;;
  *)  optarg=no ;;
  esac

  case $1 in
  list-templates)
        subcmd="list-templates"
        ;;
  list-vms)
        subcmd="list-vms"
        ;;  
  list-specs)
        subcmd="list-specs"
        ;;          
  delete-image)
        subcmd="delete-image"
        ;;      
  --vm=*)
        vm_name=$optarg
        ;;          
  --help | -h)
        usage ;;
  *)
        echo "ERROR: Invalid option"
        usage ;;
  esac
  shift
done

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']")
res_specs=$(yaml $kvm_yaml_file "['resource_per_gpu']")

# list-templates
if [[ $subcmd == "list-templates" ]]; then
    if [ -d $tmpl_root_dir ]; then
        cd $tmpl_root_dir
        ls -ad */ | cut -f1 -d'/'
        exit $?
    fi
fi

# list-vms
if [[ $subcmd == "list-vms" ]]; then
    vmdir=$vm_root_dir/$USER
    if [ -d $vmdir ]; then
        cd $vmdir
        ls -ad */ >/dev/null 2>&1
        if [ $? == 0 ]; then 
            ls -ad */ | cut -f1 -d'/'
            exit $?
        fi
    fi
fi

# list-specs
if [[ $subcmd == "list-specs" ]]; then
    echo $res_specs
    exit $?
fi

# delete-image
if [[ $subcmd == "delete-image" ]]; then
    vmdir=$vm_root_dir/$USER/$vm_name
    if [ -d $vmdir ]; then
        rm -r $vmdir
        exit $?
    fi
fi

