#!/usr/bin/ruby
# termios.rb is required. see http://arika.org/ruby/termios.xhtml
# usage: script
# $Id: script,v 1.2 2002/11/03 23:51:31 tommy Exp $

require 'tpty'
require 'termios'

logfile = File::open('typescript', 'a')
t = Termios::tcgetattr($stdin)
t.iflag = t.oflag = t.lflag = 0
t.cc[Termios::VMIN] = 1
t.cc[Termios::VTIME] = 0
oldt = Termios::tcsetattr($stdin, Termios::TCSANOW, t)
begin
  pty = TPty::new do |s,m|
    fork do
      Termios::tcsetattr(s, Termios::TCSANOW, oldt)
      $stdin = $stdout = $stderr = s
      m.close
      s.close
      logfile.close
      Process::setsid
      exec "/bin/sh"
    end
  end
  loop do
    rfds, = select([pty.master, $stdin])
    rfds.each do |r|
      data = r.sysread(1024) rescue exit
      if r == $stdin then
	pty.master.syswrite data
      else
	logfile.syswrite data
	$stdout.syswrite data
      end
    end
  end
ensure
  Termios::tcsetattr($stdin, Termios::TCSANOW, oldt)
end
