#!/usr/bin/python

# This script generates new tests from existing ones. Generated tests will use NVME and SCSI interfaces
# instead of default virtio.

# The script is intended to be run as pre-commit git hook. However, that has to be set manually.

from os import listdir, path
import re

# directory with tests to be processed
TARGET_PATH = ".."

# filename suffix to be added to generated files (file extension is unaffected)
GENERATED_FILE_SUFFIX = "_generated"

# regex to determine files to be processed (also excluding those with GENERATED_FILE_SUFFIX)
REGEX_ORG_FILENAME_TEMPLATE = "tests_.*(?<!%s)[.]yml" % GENERATED_FILE_SUFFIX
# Note: "(?<!%s)\.yml" means "%s is not allowed to be right before '.yml'"
regex = re.compile(REGEX_ORG_FILENAME_TEMPLATE)

# generated file template
TEST_FILE_CONTENTS = """\
---
# This file was generated by generate_tests.py
- hosts: all
  tags:
    - tests::%s
  tasks:
    - name: set disk interface for test
      set_fact:
        storage_test_use_interface: "%s"

- import_playbook: %s
  tags:
    - tests::%s
"""

# list of interfaces which will have their files generated
INTERFACES = ["nvme", "scsi"]


# make a new filename
def generate_filename(orgname, interface):
    index = orgname.rfind(".yml")
    return orgname[:index] + "_" + interface + GENERATED_FILE_SUFFIX + orgname[index:]


# create new file and its contents
def generate_file(org_filename, iface):
    gen_path_file = path.join(TARGET_PATH, generate_filename(org_filename, iface))

    with open(gen_path_file, "w") as f:
        f.write(TEST_FILE_CONTENTS % (iface, iface, org_filename, iface))


# will new test be generated based on this item?
def is_test_file(filename):
    return regex.match(filename) is not None


if __name__ == "__main__":

    print("Generating tests... ")
    for f in listdir(TARGET_PATH):
        if path.isfile(path.join(TARGET_PATH, f)) and is_test_file(f):
            for iface in INTERFACES:
                generate_file(f, iface)
    print("done")
