#!/bin/bash -ue

# 0 = disable workaround
# 1 = enable workaround
WORKAROUND=$1

trap 'rm -f fifo[01] exe exe.o ; kill 0' EXIT
mkfifo fifo0
mkfifo fifo1

g++ -x c++ -c -o exe.o -I/usr/include/python2.7 - << EOF
#include <Python.h>
#include <stdio.h>
#include <fcntl.h>
#include <assert.h>

void workaround(const char *ptsname)
{
	int ptsfd = open(ptsname, O_RDWR);
	dup2(ptsfd, 0);
	dup2(ptsfd, 1);
	dup2(ptsfd, 2);
}

int main(int argc, char **argv)
{
	assert(argc == 3);
	const char *ptsname = argv[1];
	int enable_workaround = atoi(argv[2]);
	if(enable_workaround) {
		workaround(ptsname);
	}
	Py_Initialize();
	FILE *ptsfile = fopen(ptsname, "rw");
	PyRun_InteractiveLoop(ptsfile, ptsname);
	Py_Finalize();
}
EOF
g++ -o exe exe.o -lutil -lpython2.7

xterm -e bash -c 'tty > fifo0 ; cat < fifo1' &
PTS=$( cat fifo0 )
./exe $PTS $WORKAROUND ; exec {a}>fifo1 ; exec {a}>&-
wait
