#!/usr/bin/env python
import httplib
import socket
from urllib import quote
import sys


class UHTTPConnection (httplib.HTTPConnection):
    def __init__(self, path):
        httplib.HTTPConnection.__init__(self, 'localhost')
        self.path = path

    def connect(self):
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        try:
            sock.connect(self.path)
        except socket.error as e:
            if e.errno == 13:
                sys.stderr.write('Permission denied\n')
                sys.exit(4)
            sys.stderr.write('Could not connect: %s\n' % e)
            sys.exit(3)
        self.sock = sock


if len(sys.argv) < 2:
    print('Usage: ajenti-ipc <endpoint> [arguments]')
    sys.exit(1)

url = sys.argv[1] + '/' + '\n'.join(sys.argv[2:]).encode('base64').strip()
conn = UHTTPConnection('/var/run/ajenti-ipc.sock')
conn.request(
    'GET',
    quote(url),
)

resp = conn.getresponse()
sys.stdout.write(resp.read())

sys.stderr.write('%s %s\n' % (resp.status, resp.reason))
sys.exit(0 if resp.status == 200 else 2)
