#!/usr/bin/perl
#
# crtprt - print using vt100 print-escape codes
#
# Takes stdin and outputs it to either the controlling tty, or the tty
# specified in the ~/.tty file, wrapping vt100 print-escape codes around it.
#
# This and other hacks can be found at: http://oddgeek.info/
#
# Copyright (c) 2005 Jason A. Dour
#
# This software is provided 'as-is', without any express or implied warranty.
# In no event will the authors be held liable for any damages arising from the
# use of this software.
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
#
#     1. The origin of this software must not be misrepresented; you must not
#     claim that you wrote the original software. If you use this software in a
#     product, an acknowledgment in the product documentation would be
#     appreciated but is not required.
#
#     2. Altered source versions must be plainly marked as such, and must not
#     be misrepresented as being the original software.
#
#     3. This notice may not be removed or altered from any source
#     distribution.
#

#
# Version Information
#
# 1.0   2005.06.01
#
#       Put in a few additional comments.  Cleaned up formatting.  Added
#       support for .tty file, as a work-around for issues with GNU Screen.  In
#       your .profile, do something along the lines of: echo $SSH_TTY > ~/.tty
#
# ooze	2000.01.25
#
#       Used for years to print from my co-lo or other remote servers to a
#       PC-attached printer without needing to establish print ueues on the
#       servers, firewall rules, et cetera.  Uses standard vt100 print-escape
#       codes that redirect output to an "attached" printer.  Most terminal
#       emulation software packages honor these codes and will send the output
#       to the designated local (or default) printer.
#

# vt100 Print-Escape Start
$header = "\033[5i";

# vt100 Print-Escape Stop
$footer = "\f\033[4i";

# Grab contents of ~/.tty
open(TTY,"$ENV{'HOME'}/.tty");
$tty = <TTY>;
chomp($tty);
close(TTY);

# If ~/.tty had contents, assume they're OK (not cool)...
if ( length($tty) ) {
    # Close stdout...
    close(STDOUT);
    # Reopen it as going to the specified tty.
    open(STDOUT,">>$tty");
} elsif ( $ENV{'SSH_TTY'} && -c $ENV{'SSH_TTY'} && -w $ENV{'SSH_TTY'}) {
    # Close stdout...
    close(STDOUT);
    # Reopen it as going to the SSH-specified tty.
    open(STDOUT,">>$ENV{'SSH_TTY'}");
}

# Output the start header.
print $header;

# Output all the input.
while (<>) { print; }

# Output the stop footer.
print $footer;

# We're done.
exit(0);
