#!/bin/sh -ef

po_domain="alterator-mkve"

alterator_api_version=1
. alterator-sh-functions
. mkve-sh-functions

# action list {{{
undefined_openvz_machine()
{
    local m

    for m in $(mkve list); do
        local id=$($mkve_config get "/var/lib/mkve/machines/$m/info" main id)
        [ "$id" != "$ctid" ] || return 1
    done
    return 0
}

list_openvz_ctids()
{
    local ctid

    for ctid in $(vzlist --all -H -o ctid); do
        undefined_openvz_machine "$ctid" && echo "$ctid"
    done
}

action_list()
{
    case "$in__objects" in
        list_hypervisors)
            write_enum_item 'openvz'
            ;;
        list_openvz_ctids)
            for ctid in $(list_openvz_ctids); do write_enum_item $ctid; done
            ;;
    esac
}
# }}}
# action type {{{
action_type()
{
    write_type_item machine_name mkve-machine-name
}
# }}}
# action write {{{
adopt_openvz()
{
    local err

    err=$(mkve adopt "$in_machine_name" --hy openvz --args "$in_args" 2>&1) ||
        write_error "mkve failed: $err"
}

action_write()
{
    if [ "$in_adopt" = "yes" ]; then
        case "$in_hypervisor" in
            openvz)
                adopt_openvz
                ;;
            *)
                write_error "`_ "unknown hypervisor"`"
                ;;
        esac
    fi
}
# }}}

on_message()
{
    set | egrep '^in_'
    echo
    case "$in_action" in
        list)        action_list        ;;
        write)       action_write       ;;
        read)        write_nop          ;;
        type)        action_type        ;;
        *)           write_bool 'false' ;;
    esac
}

message_loop

# vim:fdm=marker et sw=4 ts=4
