#!/usr/bin/env python2.3

# Copyright (C) 2003 Jonathan Middleton <jjm@ixtab.org.uk>

# 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.

# $Id: update-remote-setup.py 2127 2003-09-16 21:23:26Z jjm $

import os
import ConfigParser
import sys
import string

try:
    import optparse
except ImportError:
    import opt
    

def Options():
    """Read in the command line arguments and the
    ~/.update-remote-setup.pyrc file then return the options and
    number of args"""

    __version__ = "$LastChangedRevision: 2127 $"
    __version__ = __version__.replace("$LastChangedRevision: ", "")
    __version__ = __version__.replace(" $", "")

    version_string = "%prog: " + __version__

    ConfigFiles = [ '/etc/update-remote-setup.pyrc',
                    os.path.expanduser('~/.update-remote-setup.pyrc')]

    # Setup the command line options
    parser = optparse.OptionParser(version=version_string)

    parser.add_option("-f", "--file",
                      help="file to upload",
                      dest="files",
                      action="append",
                      )

    parser.add_option("-v", "--verbose",
                      action="store_true",             
                      help="increase verbosity",
                      dest="verbose",
                      default=True,
                      )

    parser.add_option("-q", "--quite",
                      action="store_false",
                      dest="verbose",
                      help="decrease verbosity",
                      )
    
    parser.add_option("-s", "--ssh-copy-id",
                      action="store_true",
                      dest="ssh",
                      help="Setup SSH keys",
                      )

    parser.add_option("-H", "--host",
                      action="append",
                      dest="hosts",
                      type="string",
                      help="Host to update",
                      )

    parser.add_option("-n", "--dry-run",
                      action="store_false",
                      help="show what would have been transferred",
                      dest="act",
                      default=True,
                      )

    # We now read in the rc file
    config = ConfigParser.ConfigParser()
    config.read(ConfigFiles)

    hosts = string.split(config.get('DEFAULT', 'hosts'))
    files = string.split(config.get('DEFAULT', 'files'))

    files = UserExpand(files)

    if sys.argv[1:].count("-H") == 0 and sys.argv[1:].count("--host") == 0:
        for host in hosts:
            sys.argv.append("--host")
            sys.argv.append(host)

    if sys.argv[1:].count("-f") == 0 and sys.argv[1:].count("--file") == 0:
        for file in files:
            sys.argv.append("--file")
            sys.argv.append(file)            

    (options, args) = parser.parse_args()

    return (options, args)

def UserExpand(list):

    """Take a list and run os.path.expanduser() on each item and
    return the expanded list """
    
    expanded = []

    for item in list:
        expanded.append(os.path.expanduser(item))

    return expanded

class Log:

    def __init__(self, level):
        self.level = level

    def message(self, message, newline):

        if self.level:
            if newline:
                print message
            else:
                print message, 

(options, args) = Options()

logger = Log(options.verbose)

if __name__ == '__main__':

    for host in options.hosts:
        if options.ssh:
            logger.message("Installing ssh-id: %s" % host, newline=True)
            if options.act:
                os.system("ssh-copy-id %s" % host)

        logger.message("Updating - %s\t" % host, newline=True)
        for file in options.files:
            logger.message("\t%s, " % file, newline=True)
            if options.act:            
                os.system("scp -q %s %s:%s" % (file, host, file))

        logger.message("", newline=True)
