#!/usr/bin/env python3
import argparse
import os
import re
import sys
from subprocess import check_call

vendored_libbeat = os.path.normpath("vendor/github.com/elastic/beats")


goversion_var_libbeat = "defaultBeatVersion"		# version in libbeat
goversion_var = "appVersion"						# version for custom beats


def get_rootfolder():
    vendored_libbeat = os.path.normpath("vendor/github.com/elastic/beats")
    script_directory = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
    index = script_directory.find(vendored_libbeat)
    if index > 0:
        # Community beat detected, version files are stored at the root folder of the project
        return os.path.abspath(script_directory[:index])

    # Libbeat detected
    return os.path.dirname(script_directory)

def replace_in_file(filename, varname, version):
    new_lines = []
    with open(filename, 'r') as f:
        for line in f:
            if line.startswith("const " + varname):
                new_lines.append('const {} = "{}"\n'.format(varname, version))
            else:
                new_lines.append(line)

    with open(filename, 'w') as f:
        for line in new_lines:
            f.write(line)
    print ("Set version {} in file {}".format(version, filename))

def main():
    parser = argparse.ArgumentParser(
        description="Used to set the current version. Doesn't commit changes.")
    parser.add_argument("version",
                        help="The new version")
    args = parser.parse_args()
    version = args.version

    is_libbeat = vendored_libbeat not in os.path.realpath(__file__)
    if is_libbeat:
        goversion_filepath  = os.path.join(get_rootfolder(), "libbeat", "version", "version.go")
        go_var = goversion_var_libbeat
    else:
        goversion_filepath  = os.path.join(get_rootfolder(), "version.go")
        go_var = goversion_var

    # Create version.go and version.yml files
    replace_in_file(goversion_filepath, go_var, version)

if __name__ == "__main__":
    main()

