#!/usr/libexec/platform-python
"""
OpenNebula Driver for Linstor
Copyright 2018 LINBIT USA LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import sys

from one.extender import clone, get_rsc_name, make_resource
from one import util, vm
from one.datastore import Datastore

SRC = sys.argv[1]
DST = sys.argv[2]  # clone name
VM_ID = int(sys.argv[4])
DS_ID = sys.argv[5]


def main():
    util.log_info("Entering tm cpds with " + str(sys.argv[1:]))

    src_host = util.arg_host(SRC)
    disk_id = SRC.split(".")[-1].strip()
    datastore = Datastore(util.show_ds(DS_ID))

    target_vm = vm.Vm(util.show_vm(VM_ID))

    res_name = get_rsc_name(target_vm, disk_id)
    util.log_info("SOURCE IMAGE: " + res_name)

    res = make_resource(res_name, datastore.linstor_controllers, datastore.linstor_controller_auth_token)
    success, _ = clone(
        res,
        DST,
        datastore.linstor_resource_group,
        prefer_node=src_host,
        auth_token=datastore.linstor_controller_auth_token
    )

    util.log_info("Exiting tm cpds with " + "success." if success else "error.")

    if not success:
        sys.exit(1)


if __name__ == "__main__":
    util.run_main(main)
