#!/usr/bin/env python
#
# Copyright (c) 2013-2017 - Adjacent Link LLC, Bridgewater, New Jersey
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in
#   the documentation and/or other materials provided with the
#   distribution.
# * Neither the name of Adjacent Link LLC nor the names of its
#   contributors may be used to endorse or promote products derived
#   from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

import sys
import argparse

from etce.field import Field
from etce.clientbuilder import ClientBuilder


usagestr = '''
description: Many to one copy function. Copies remotesrc from hosts specified 
             in the hostfile to the localdst directory on the local machine. 
             remotesrc names a file or subdirectory that exists under the 
             directory named by the etce.conf WORK_DIRECTORY value on
             the remote nodes. localsrc specifies an absolute or relative path
             to a directory on the local host. remotesrc is only copied from the 
             root nodes of the two-level hostfile tree structure.

             Note, etcecollect does not attempt to resolve file collisions - 
             the case where remotesrc names a file that exists on multiple
             hosts, or names a directory that contains an identically named
             file anywhere in its subdirectories on multiple hosts. The usual
             case for etcecollect is to collect remote directories where
             care has been taken to name all contained files with a unique 
             prefix to avoid collision.
 
Examples:    For hostfile:
             -----------------
             server1 {
               node-1
               node-2
             }

             server2
             -----------------

             And WORK_DIRECTORY=/tmp/etce on both server1 and server2:

             1. etcecollect foo/bar . hostfile
                Recursively copies the directory rooted at 
                /tmp/etce/foo/bar on the remote hosts to current working 
                directory.
'''

def main():
    parser = argparse.ArgumentParser(description=usagestr,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('--envfile',
                        action='store',
                        default=None,
                        help='''Environment file to invoke on remove nodes
                        before running the specified command.
                        default: None.''')
    parser.add_argument('remotesrc',
                        metavar='REMOTESRC',
                        action='store',
                        default=None,
                        help='''The remote source directory to move
                        to the local destination.''')
    parser.add_argument('localdst',
                        metavar='LOCALDST',
                        action='store',
                        default=None,
                        help='''The local destination directory
                        to collect the remote source files to.''')
    parser.add_argument('hostfile',
                        metavar='HOSTFILE',
                        action='store',
                        default=None,
                        help='''The ETCE Host file containing the 
                        node names from which the remote source 
                        directories are collected.''')

    args = parser.parse_args()

    field = Field(args.hostfile)

    client = ClientBuilder().build(field.roots(),
                                   envfile=args.envfile)

    try:
        ret = client.collect(args.remotesrc, args.localdst, field.roots())
    except ValueError as e:
        print e.message
    finally:
        client.close()


if __name__=='__main__':
    main()
