#!/usr/bin/python

import requests
from ansible.callbacks import vvv

class Connection(object):

    def __init__(self, runner, host, port, user, *args, **kwargs):
        self.runner = runner
        self.host = host
        self.port = port or 8700
        self.user = user
        self.has_pipelining = False

    def _build_url(self, url):
        return 'http://{host}:{port}{url}'.format(host=self.host, port=self.port, url=url)

    def connect(self):
        vvv("ESTABLISH CONNECTION FOR USER: %s" % self.user, host=self.host)
        self.session = requests.Session()
        return self

    def exec_command(self, cmd, tmp_path, *args, **kwargs):
        vvv("EXEC %s" % cmd, host=self.host)

        r = self.session.post(self._build_url('/exec'), data={'command': cmd})
        if r.status_code == 200:
            data = r.json()
            return (data['status'], data['stdin'], data['stdout'], data['stderr'])

        return (255, '', '', r.text)

    def put_file(self, in_path, out_path):
        vvv("PUT %s TO %s" % (in_path, out_path), host=self.host)
        with open(in_path, 'rb') as fp:
            r = self.session.put(self._build_url('/upload'), data={'dest': out_path}, files={'src': fp})

        if r.status_code != 200:
            raise errors.AnsibleError("failed to transfer file from %s" % in_path)

    def fetch_file(self, in_path, out_path):
        vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
        raise errors.AnsibleError("not unimplemented")

    def close(self):
        self.session.close()

@@ -61,16 +61,140 @@
 port vvv
+%0Afrom ansible.constants import p, get_config%0A%0ADEFAULT_USE_SSL = get_config(p, 'agent', 'use_ssl', None, False, boolean=True)
 %0A%0Aclass 
@@ -393,16 +393,105 @@
  = user%0A
+        self.proto = 'http'%0A        if DEFAULT_USE_SSL:%0A            self.proto = 'https'%0A
         
@@ -566,20 +566,23 @@
 return '
-http
+%7Bproto%7D
 ://%7Bhost
@@ -603,16 +603,34 @@
 .format(
+proto=self.proto, 
 host=sel
@@ -801,24 +801,60 @@
 s.Session()%0A
+        self.session.verify = False%0A
         retu

Support configuring the connection plugin to use SSL