#!/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 os
import sys

from one import driver_action, util
from one.extender import connect, get_device_path, make_resource


def main():
    util.log_info("Entering datastore/export")

    arg_driver_action, arg_app_id = util.get_datastore_args()
    driver = driver_action.DriverAction(arg_driver_action)
    res = make_resource(driver.image.source, driver.datastore.linstor_controllers,
                        driver.datastore.linstor_controller_auth_token)
    hosts = res.diskful_nodes()

    with connect(driver.datastore.linstor_controllers, driver.datastore.linstor_controller_auth_token) as lin:
        nodelist = lin.node_list_raise()
        dst_host = nodelist.node(hosts[0]).net_interfaces[0].address

    output_file = os.path.join(
        driver.datastore.staging_dirs, "{}-{}".format(res.name, arg_app_id)
    )

    rc, _, err = util.ssh_monitor_and_log(
        host=dst_host,
        cmd="dd if={} of={} bs=4M oflag=fsync".format(get_device_path(res), output_file),
        error_msg="could not dd image")

    if rc != 0:
        raise RuntimeError("Unable to dd export image file: " + err)

    img_format = util.detect_image_format(dst_host, output_file)

    if not driver.image.size:
        rc, img_size, _ = util.ssh_monitor_and_log(
            host=dst_host,
            cmd=" ".join(["du", "-LM", output_file, "|", "cut", "-f1"]),
            error_msg="could not determine the size of the exported file"
        )
    else:
        img_size = driver.image.size

    rc, img_checksum, _ = util.ssh_monitor_and_log(
        host=dst_host,
        cmd="md5sum {} | cut -d ' ' -f1".format(output_file),
        error_msg="could not determine checksum")

    if rc != 0 or not img_checksum:
        util.log_error("could not generate MD5SUM of the exported file")
        sys.exit(1)

    print(
        """<IMPORT_INFO>
    <IMPORT_SOURCE><![CDATA[{}]]></IMPORT_SOURCE>
    <MD5><![CDATA[{}]]></MD5>
    <SIZE><![CDATA[{}]]></SIZE>
    <FORMAT><![CDATA[{}]]></FORMAT>
    <DISPOSE><![CDATA[NO]]</DISPOSE>
    </IMPORT_INFO>""".format(
            "ssh://{}:{}".format(dst_host, output_file),
            img_checksum,
            img_size,
            img_format,
        )
    )

    util.log_info("Exiting datastore/export")


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