#
# Resilient SDK v29 changed co3 to co3base
#
try:
	import co3base as resilient
except Exception as e:
	import co3 as resilient

import requests
import ssl
import sys, getopt
import json
import urllib
import subprocess

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
from requests_toolbelt.multipart.encoder import MultipartEncoder

HELP_STRING = \
            "Usage:\n" \
            "\tpython connect.py\n" \
            "\t-s <Resilient> \n" \
            "\t-u <Resilient user> \n" \
            "\t-p <Resilient password> \n" \
            "\t-i <incidnet_number> \n" \
            "\t-f <file_name> \n" \
            "\t-o <Organizatio> \n" \
            "\t-v <Optional: True or False for verifying certificate. Default to False if absent>"
#
# Login information
#
user=""
password = ""
url = ""
org=""
verify = True
baseurl = ""

class TLSHttpAdapter1(HTTPAdapter):
    """
    Adapter that ensures that we use the best available SSL/TLS version.
    Some environments default to SSLv3, so we need to specifically ask for
    the highest protocol version that both the client and server support.
    Despite the name, SSLv23 can select "TLS" protocols as well as "SSL".
    """
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       ssl_version=ssl.PROTOCOL_SSLv23)

#
# Read command line parameters
#
argv = sys.argv[1:]
try:
	opts, args = getopt.getopt(argv, "hs:u:p:i:f:o:v:",
                                   ["help", "server=", "user=", "password=", "incident=", "file=", "org=", "verify="])
except getopt.GetoptError:
	print(HELP_STRING)
	sys.exit(2)

for opt, arg in opts:
    if opt == "-h":
        print(HELP_STRING)
        sys.exit()
    elif opt in ("-s", "--server"):
        url = "https://" + arg +":443"
        baseurl = arg
    elif opt in ("-u", "--user"):
        user = arg
    elif opt in ("-p", "--password"):
        password = arg
    elif opt in ("-o", "--org"):
        org = arg
    elif opt in ("-f", "--file"):
        filename = arg
    elif opt in ("-i", "--incident"):
        inc_index = arg
    elif opt in ("-v", "--verify"):
        if arg == "False":
            verify = False

args = {"base_url": url, "verify": verify}
if org:
    args["org_name"] = org

try:
	# Try v29 and later
	resilient_client = resilient.BaseClient(**args)
except Exception as e:
	try:
		resilient_client = resilient.SimpleClient(**args)
	except Exception as e:
		print("Failed to instantiate resilient_client: " + str(e))
		sys.exit(2)
try:
    print("\n\n")
    print("Connecting to Resilient server: " + url + " using Resilient SDK: ")

    session = resilient_client.connect(user, password)

    if resilient_client:
    	print("\tConnected to resilient")
        print("Ready to post {} to incident {}".format(filename, inc_index))
        resilient_client.post_attachment("/incidents/{}/attachments".format(inc_index), filename)
    else:
    	print("\tConnection failed")
except Exception as e:
    print("\tConnection failed!!")
    print("\t" + str(e))