#!/usr/bin/env python2.2
# 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, re, os, pwd, time, gruntlib
from sys import stdin, stdout, argv
import GnuPGInterface
from optik import OptionParser

usage = """
    USAGE: %prog filename delivery dest-filename

    filename is the local file to send

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

    dest-filename is the location to place the data in on the remote."""

parser = OptionParser(usage = usage)
gruntlib.addcommonoptions(parser)
(options, args) = parser.parse_args()

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

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

if os.path.isdir(args[0]):
    os.chdir(args[0])
    infile = os.popen('tar -cSpf - .', 'r')
    mode = 'PUTDIR'
else:
    infile = open(args[0])
    mode = 'PUTFILE'

gnupg = GnuPGInterface.GnuPG()
gnupg.options.meta_interactive = 1
gnupg.options.armor = 1
gpgargs = ['--sign']
gpgargs.extend(gruntlib.getencryptoptions(options, gruntlib.getconfig(),
                                          args[1]))
process = gnupg.run(gpgargs,
                    create_fhs=['stdin'],
                    attach_fhs={'stdout': outfile})
dataout = process.handles['stdin']
dataout.write(gruntlib.getheaders(user, mode, args[2], 1))
gruntlib.copy(infile, dataout)
assert not infile.close(), "Error reading data"
dataout.close()
process.wait()
assert not outfile.close(), "Error writing data."
print "Request successfully sent."
