#!/usr/bin/env python3
#
# (c) 2017 Fetal-Neonatal Neuroimaging & Developmental Science Center
#                   Boston Children's Hospital
#
#              http://childrenshospital.org/FNNDSC/
#                        dev@babyMRI.org
#

import sys, os
sys.path.insert(1, os.path.join(os.path.dirname(__file__), '..'))

import  socket
import  json
import  sys
import  pfurl
from    argparse            import RawTextHelpFormatter
from    argparse            import ArgumentParser
from    pfurl._colors       import Colors

str_defIP   = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
str_defPort = '5055'

str_name    = 'pfurl'
str_version = "1.3.18.0"
str_desc    = Colors.CYAN + """

        __            _ 
       / _|          | |
 _ __ | |_ _   _ _ __| |
| '_ \|  _| | | | '__| |
| |_) | | | |_| | |  | |
| .__/|_|  \__,_|_|  |_|
| |                     
|_|                     


                            Process-File-over-URL

           A simple URL-based communication and control script.

                              -- version """ + \
           Colors.YELLOW + str_version + Colors.CYAN + """ --
           
    'pfurl' sends REST conforming commands and data to remote services, similar
    in some ways to the well-known CLI tool, 'curl' or the Python tool, 'httpie'
    
    'pfurl' not only sends curl type payloads, but can also zip and unzip entire
    directories of files for transmission and reception.
    
    'pfurl' is designed to be part of the ChRIS/CHIPS framework.
    
""" + \
           Colors.BLINK_RED +  """
        
              +---------------------------------------------------------+
              | NOTE THAT 'pfurl' COMMS ARE NOT NATIVELY ENCRYPTED!     |
              | USE AN SSH TUNNEL IF YOU NEED SECURE DATA TRANSMISSION. |
              +---------------------------------------------------------+
              
""" + Colors.NO_COLOUR

parser  = ArgumentParser(description = str_desc, formatter_class = RawTextHelpFormatter)

parser.add_argument(
    '--msg',
    action  = 'store',
    dest    = 'msg',
    default = '',
    help    = 'Message to send to pman or similar listener.'
)
parser.add_argument(
    '--verb',
    action  = 'store',
    dest    = 'verb',
    default = 'POST',
    help    = 'REST verb.'
)
parser.add_argument(
    '--http',
    action  = 'store',
    dest    = 'http',
    default = '%s:%s' % (str_defIP, str_defPort),
    help    = 'HTTP string: http://<IP>[:<port>]</some/path/>'
)
parser.add_argument(
    '--auth',
    action  = 'store',
    dest    = 'auth',
    default = '',
    help    = 'user:passwd authorization'
)
parser.add_argument(
    '--jsonwrapper',
    action  = 'store',
    dest    = 'jsonwrapper',
    default = '',
    help    = 'wrap msg in optional field'
)
parser.add_argument(
    '--quiet',
    help    = 'if specified, only echo final JSON output returned from server',
    dest    = 'b_quiet',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--raw',
    help    = 'if specified, do not wrap return data from remote call in json field',
    dest    = 'b_raw',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--oneShot',
    help    = 'if specified, transmit a shutdown ctl to the remote service after event',
    dest    = 'b_oneShot',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--man',
    help    = 'request help: --man commands',
    dest    = 'man',
    action  = 'store',
    default = ''
)
parser.add_argument(
    '--content-type',
    help    = 'content type',
    dest    = 'contentType',
    action  = 'store',
    default = ''
)
parser.add_argument(
    '--jsonpprintindent',
    help    = 'pretty print json-formatted payloads',
    dest    = 'jsonpprintindent',
    action  = 'store',
    default = 0
)
parser.add_argument(
    '--httpResponseBodyParse',
    help    = 'if specified, assume full HTTP responses and parse only the body',
    dest    = 'b_httpResponseBodyParse',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--version',
    help    = 'if specified, print version number',
    dest    = 'b_version',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--unverifiedCerts',
    help    = "Allows you to send https requests with self signed ssl certificates",
    dest    = 'unverifiedCerts',
    action  = 'store_true',
    default = False
)
parser.add_argument(
    '--authToken',
    help    = 'Send a token for authentication with your http request',
    dest    = 'authToken',
    action  = 'store',
    default = 'password'
)
args    = parser.parse_args()

if args.b_version:
    print("Version: %s" % str_version)
    sys.exit(1)

pfurl  = pfurl.Pfurl(
    msg                         = args.msg,
    http                        = args.http,
    verb                        = args.verb,
    contentType                 = args.contentType,
    auth                        = args.auth,
    b_raw                       = args.b_raw,
    b_quiet                     = args.b_quiet,
    b_oneShot                   = args.b_oneShot,
    b_httpResponseBodyParse     = args.b_httpResponseBodyParse,
    jsonwrapper                 = args.jsonwrapper,
    man                         = args.man,
    desc                        = str_desc,
    name                        = str_name,
    version                     = str_version,
    startFromCLI                = True,
    unverifiedCerts             = args.unverifiedCerts,
    authToken                   = args.authToken
    )

if not args.jsonpprintindent:
    print(pfurl())
else:
    print(json.dumps(json.loads(pfurl()), indent=int(args.jsonpprintindent)))

sys.exit(0)
