#!/usr/bin/env ruby

require "fcntl"
require "open3"

PIPE_NAME = '/tmp/testpipe'

at_exit { File.delete(PIPE_NAME) }
%x{ rm -f #{PIPE_NAME} && mkfifo #{PIPE_NAME} }

stdin, stdout, stderr = Open3.popen3("sh") # interactive command we control
stdout.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)
stderr.fcntl(Fcntl::F_SETFL, Fcntl::O_NONBLOCK)

while true
  reads, writes = select([ stdout, stderr ], [ stdin ])
  reads.each { |io| print io.read }

  unless writes.empty?
    input = File.read(PIPE_NAME)
    stdin << input
    exit if input =~ /^exit$/

    %x{ rm -f #{PIPE_NAME} && mkfifo #{PIPE_NAME} }
  end
end
