#!/usr/bin/env python3

import sys
import subprocess
import time
import argparse

import yaml

XRANDR = 'xrandr'

def run(cmd):
    print('>>> ' + ' '.join(cmd))
    start = time.time()
    ret = subprocess.run(
        cmd,
        stdout=sys.stdout,
        stderr=sys.stderr)
    end = time.time()
    print("exit code: {}".format(ret.returncode))
    print("exec time: {}".format(end - start))

def fail(msg, code=1):
    print(msg)
    sys.exit(code)

parser = argparse.ArgumentParser()
parser.add_argument('config')

args = parser.parse_args()
config_path = args.config

try:
    config = yaml.safe_load(open(config_path))
except FileNotFoundError:
    fail("File {0} not found".format(config_path))

# reset
for output in config['outputs']:
    if config.get('reset') and output.get('reset'):
        run([XRANDR, '--output', output['name'], '--off'])
        run([XRANDR, '--delmode', output['name'], output['opts']['mode']])
        run([XRANDR, '--addmode', output['name'], output['opts']['mode']])
        run([XRANDR, '--output', output['name'], '--mode', output['opts']['mode']])

cmd = [XRANDR]
for output in config['outputs']:
    cmd.extend(['--output', output['name']])
    if output.get('disable'):
        cmd.append('--off')
    else:
        if output.get('primary', False):
            cmd.append("--primary")
        # cmd.append('--auto')
        for k, v in output['opts'].items():
            cmd.extend(['--{}'.format(k), str(v)])
        for k,v  in output.get('set', {}).items():
            cmd.extend(['--set', k, v])

run(cmd)
run(['i3-msg', 'restart'])
run(['systemctl', '--user', 'restart', 'keyboard'])
