#!/usr/bin/env python
# Startup from single-user installation
# Copyright (C) 2002 John Goerzen
# <jgoerzen@complete.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

import sys
sys.path.append('/usr/share/grunt')
import re, os, pwd, time, gruntlib
from sys import stdin, stdout, argv
import GnuPGInterface
from optparse import OptionParser

usage = """
    USAGE: gruntrun [options] delivery dest-command

    delivery is a UUCP path in the form of system!user OR
    an e-mail address in the form of user@system

    dest-command is the command to run on the remote."""

parser = OptionParser(usage = usage)
parser.add_option('-i', '--input', dest='input',
                  metavar='FILE',
                  help = 'Specify a file to be included as standard input for the program on the remote machine.  If FILE is a hyphen (-), then standard input will be read and passed along as standard input on the remote.')
gruntlib.addcommonoptions(parser)
(options, args) = parser.parse_args()

if len(args) != 2:
    parser.print_help()
    sys.exit(1)

(user, outfile) = gruntlib.transportopen(args[0])
outfile.write(gruntlib.getheaders(user))
outfile.flush()

gnupg = GnuPGInterface.GnuPG()
gnupg.options.meta_interactive = 1
gnupg.options.armor = 1
gpgargs = ['--sign']
gpgargs.extend(gruntlib.getencryptoptions(options, gruntlib.getconfig(),
                                          args[0]))
process = gnupg.run(['--sign'],
                    create_fhs=['stdin'],
                    attach_fhs={'stdout': outfile})
dataout = process.handles['stdin']
dataout.write(gruntlib.getheaders(user, 'EXEC', args[1], 1))
if options.input:
    if options.input == '-':
        gruntlib.copy(stdin, dataout)
    else:
        infile = open(options.input, 'rb')
        gruntlib.copy(infile, dataout)
        infile.close()
dataout.close()
process.wait()
assert outfile.close() == None, "Transport received error exit."
print "Request successfully sent."
