#!/usr/bin/python3
"""
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, make_resource
from one import consts, driver_action, util


def main():
    util.log_info("Entering datastore clone")

    arg_driver_action, arg_image_id = util.get_datastore_args()
    driver = driver_action.DriverAction(arg_driver_action)

    res = make_resource(
        "{}-{}".format(consts.IMAGE_PREFIX, driver.image.cloning_id),
        driver.datastore.linstor_controllers,
        driver.datastore.linstor_controller_auth_token
    )

    clone_name = "{}-{}".format(consts.IMAGE_PREFIX, arg_image_id)

    util.log_info("Cloning into new resource '{r}' into resource group '{p}'".format(
        r=clone_name, p=driver.datastore.linstor_resource_group)
    )
    success, _ = clone(
        res,
        clone_name,
        driver.datastore.linstor_resource_group,
        auth_token=driver.datastore.linstor_controller_auth_token
    )

    util.log_info("Exiting datastore clone with " + "success." if success else "error.")

    if success:
        print(clone_name)
    else:
        sys.exit(1)


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