#!/usr/bin/env ruby
require 'pty'
require 'readline'
STDOUT.sync = true
bin = "#{Gem.bin_path('voltos', 'voltos')}-cli"
status = PTY.spawn(bin, *ARGV) do |stdout, stdin, pid|
  Thread.new do
    loop { STDOUT.print stdout.getc }
  end
  Thread.new do
    loop do
      input = Readline.readline("", true)
      if input.nil?
        stdout.close
        stdin.close
      end
      stdin.puts input.strip
    end
  end
  begin
    Process::waitpid(pid) rescue nil
  rescue SystemExit, Interrupt
    Process.kill('INT', pid)
    retry
  rescue EOFError
    puts "Ctrl-D"
  end
end
STDOUT.flush
exit(status.to_i)