#!/usr/bin/env python3

import subprocess


def host_script(opts, script, old_host=False):
    print('Running host script: ', script)
    if opts.hosts.gencfg:
        name = opts.hosts.old.cont_name if old_host else opts.hosts.new.cont_name
        sky_script = 'sky run ' + '\'' + script + '\' ' + name
    else:
        name = opts.hosts.old.name if old_host else opts.hosts.new.name
        sky_script = 'sky portorun ' + '\'' + script + '\' f@' + opts.hosts.family + ' . [h@' + name + ']'

    output = subprocess.run(sky_script, shell=True, check=True, universal_newlines=True, stdout=subprocess.PIPE, executable='/bin/bash')

    result = ''
    next_line_is_result = False
    for line in output.stdout.splitlines():
        if next_line_is_result:
            result = line.rstrip()
            break
        if str(line.rstrip()).find('----------') == 0:
            next_line_is_result = True

    print('Result:', result)
    return result


def script(opts, script):
    print('Running script: ', script)

    if opts.hosts.family == 'balancer_l7leveler_kubr_vla_experiment':  # run on all gencfg hosts simultaneously - only for vla exp
        sky_script = 'sky portorun --stream ' + '\'' + script + '\' f@' + opts.hosts.family
    elif opts.hosts.gencfg:
        assert not opts.hosts.has_old()  # not implemented
        sky_script = 'sky run --stream ' + '\'' + script + '\' ' + opts.hosts.new.cont_name
    else:
        assert not opts.hosts.has_old()  # not implemented
        sky_script = 'sky portorun --stream ' + '\'' + script + '\' f@' + opts.hosts.family + ' . [h@' + opts.hosts.new.name + ']'

    output = subprocess.run(sky_script, shell=True, check=True, universal_newlines=True, stdout=subprocess.PIPE, executable='/bin/bash')
    result = str(output.stdout.rstrip())
    print('Script result: ', result)
    return result


def local_script(script):
    print('Running local script: ', script)
    output = subprocess.run(script, shell=True, check=True, universal_newlines=True, stdout=subprocess.PIPE, executable='/bin/bash')

    result = []
    for line in output.stdout.splitlines():
        result.append(line.rstrip())

    print('Result:', result)
    return result
