#!/usr/bin/env python

import os
import subprocess
import sys
import traceback

if 'STY' not in os.environ:
    os.environ['START_WAIT_SHELL'] = '1'
    r = os.execlp('screen', 'screen', *sys.argv)
    sys.stderr.write('Unable to start screen, status %s.\n' % r)
    sys.exit(1)

# Run everything in an except clause to be able to spawn a waiting shell
# in any case.
try:
    # Qemu command. Parameters to this script will be added to the command.
    CMD= [sys.argv[1]] + ['-serial', 'pty', '-monitor', 'pty'] + sys.argv[2:]

    SCREENNAME = os.environ['STY']

    # Qemu is not really verbose, so we need to know in which order pty names 
    # will appear.
    TITLES=['Monitor', 'Serial']
    PREFIX = 'char device redirected to '

    # And then start qemu
    p = subprocess.Popen(CMD, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)

    devcount = 0
    # For obscure buffering reasons, iterating over stdout doesn't work.
    while p.poll() is None:
        line =  p.stdout.readline()
        sys.stdout.write(line)
        if line.startswith(PREFIX):
            devname = line[len(PREFIX):].strip()
            try:
                title = TITLES[devcount]
            except KeyError:
                title = devname
            # This command add a window to the current screen, using given pty.
            subprocess.call(['screen', '-x', SCREENNAME, '-X', 'screen', '-t', title, devname])
            devcount += 1

    for line in p.stdout:
        sys.stdout.write(line)

except:
    traceback.print_exc()

if 'START_WAIT_SHELL' in os.environ:
    os.execlp(os.environ['SHELL'], os.environ['SHELL'])
