import subprocess
import json

from copy import deepcopy

def update_owners(group, generilka_path="/home/i024/GENERILKA", update_owners_log=None, update_gencfg=False, commit_to_svn=False):

    """
    Expect topology in format "stable-100-r1"
    """

    if update_gencfg:
        update_gencfg_script = "./update.sh"
        print update_gencfg_script
        update_gencfg = subprocess.Popen(
            update_gencfg_script,
            shell=True,
            cwd=generilka_path,
            stdout=subprocess.PIPE
        )
        update_gencfg.wait()

    get_owners_script = "./utils/common/show_groups.py -g {} -i owners".format(group)
    print get_owners_script
    get_owners = subprocess.Popen(
        get_owners_script,
        shell=True,
        cwd=generilka_path,
        stdout=subprocess.PIPE
    )
    owners = map(lambda x: x.strip(), get_owners.stdout.readlines()[0].split(","))
    old_owners = deepcopy(owners)

    if "yandex_search_tech_quality_robot_saas" not in owners:
        owners.append("yandex_search_tech_quality_robot_saas")

    if "osidorkin" in owners:
        del(owners[owners.index("osidorkin")])

    if owners != old_owners:

        set_owners_script = "./utils/common/update_card.py -g {} -k owners -v '[{}]' -y".format(group, ",".join(owners))
        print set_owners_script
        set_owners = subprocess.Popen(
            set_owners_script,
            shell=True,
            cwd=generilka_path,
            stdout=subprocess.PIPE
        )

        if commit_to_svn:
            gencfg_commit_script = './gen.sh run_checks && svn commit db -m "Update owners in {}"'.format(group)
            print gencfg_commit_script
            set_owners.wait()
            gencfg_commit = subprocess.Popen(
                gencfg_commit_script,
                shell=True,
                cwd=generilka_path,
                stdout=subprocess.PIPE
            )

    return owners
