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

from linstor import SizeCalc
from one.extender import deploy
from one import consts, driver_action, util
from one.extender import get_device_path


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

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

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

    is_version6 = util.one_version_larger(5, 12)

    format_ = driver.image.format if is_version6 else driver.image.fs_type

    if format_ == "save_as":
        util.log_info("No need to create new image, exiting.")
        print(resource_name)
        sys.exit(0)

    util.set_up_datastore(
        " ".join(
            [
                driver.datastore.base_path,
                driver.datastore.restricted_dirs,
                driver.datastore.safe_dirs,
            ]
        )
    )

    util.log_info("Creation of a new resource: {}".format(resource_name))
    res = deploy(
        linstor_controllers=driver.datastore.linstor_controllers,
        resource_name=resource_name,
        vlm_size_str=driver.image.size + "MiB",
        resource_group=driver.datastore.linstor_resource_group,
        auth_token=driver.datastore.linstor_controller_auth_token
    )

    device_path = get_device_path(res)

    res_host = random.choice(list(res.diskful_nodes()))

    mkfs_cmd = 'mkfs_command "{0}" "{1}" "{2}"'.format(
        device_path,
        format_,
        SizeCalc.convert(res.volumes[0].size, SizeCalc.UNIT_B, SizeCalc.UNIT_MiB))

    if is_version6:
        mkfs_cmd = 'source {remotes}etc/datastore/datastore.conf ; \
FS_OPTS=$(eval $(echo "echo \\$FS_OPTS_{fs}")) ; \
mkfs_command "{devp}" "{format}" "{size}" "$SUPPORTED_FS" "{fs}" "$FS_OPTS"'.format(
            devp=device_path,
            format=format_,
            size=SizeCalc.convert(res.volumes[0].size, SizeCalc.UNIT_B, SizeCalc.UNIT_MiB),
            fs=driver.image.fs,
            remotes=util.REMOTES_DIR)

    output = util.exec_local_with_out(mkfs_cmd)
    output = 'set -e\nexport PATH=/usr/sbin:/sbin:$PATH\n' + output

    rc = util.ssh_exec_and_log(
        host=res_host,
        cmd=output,
        error_msg="Error mkfs_command for resource {}, on {}".format(res, res_host))

    if int(rc) != 0:
        res.delete()
        sys.exit(1)

    util.log_info("Finished mkfs_command {} on {} at {}".format(format_, res, res_host))
    util.log_info("Exiting datastore mkfs.")

    print(res.name)


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