#!/usr/bin/env python

from pathlib import Path
from subprocess import run
import sys


def parse_args():
    options = []
    cmds = []
    server = None
    for arg in sys.argv[1:]:
        if arg.startswith('-') and not server:
            options.append(f"{arg}=<placeholder>")
        elif options and "<placeholder>" in options[-1] and not server:
            options[-1] = options[-1].replace("<placeholder>", arg)
        elif not server:
            server = arg
        else:
            cmds.append(arg)

    return options, cmds, server


if __name__ == '__main__':
    options, cmds, server = parse_args()

    # print("OPTIONS:")
    for opt in options:
        if (
            opt.startswith("-o=ControlPath")
            and '-o=ControlMaster=auto' in options
        ):
            cpath = opt.split('=')[-1]
            Path(cpath).touch()
        # print(opt)
        elif opt.startswith("-p="):
            # fake connection error
            sys.exit(1)
    # print(f"SERVER: {server}")
    # print(f"CMD: {' '.join(cmds)}")
    # sys.exit(0)
    # run the command:
    p = run(cmds, stdout=sys.stdout, stderr=sys.stderr)
    sys.exit(p.returncode)
