#!/usr/bin/python

import bottle
import getopt
import syslog
import ConfigParser
import sys

from bottle import get, abort, request, run
from bottle import PasteServer
from supay import Daemon


syslog.openlog('cphash', syslog.LOG_PID, syslog.LOG_SYSLOG)


@get('/auth/hash')
def getHash():
    """ Get CPanel's authentication hash
    """
    try:
        config = ConfigParser.ConfigParser()
        config.readfp(open('/etc/locaweb/cphash.conf'))
        authorizedHosts = config.get('auth', 'allowed_hosts')

    except IOError:
        syslog.syslog(syslog.LOG_ERR, '[Error] Configuration file not found.')

    remoteAddr = request.environ.get('REMOTE_ADDR')

    if remoteAddr not in authorizedHosts.split():
        abort(403, 'Unauthorized host.')

    hashfile = '/root/.accesshash'
    cphash = ''

    try:
        cphashf = open(hashfile)
        for line in cphashf.readlines():
            cphash = '%s%s' % (cphash, line)
        syslog.syslog(syslog.LOG_INFO,
                      '[Info] Sending authentication hash to %s.' % remoteAddr)

        hashdict = {}
        hashdict['accesshash'] = cphash.replace('\n', '')

        return hashdict

    except IOError:
        abort(404, 'CPanel hash file not found.')

    finally:
        cphashf.close()


def main():
    bottle.debug(True)
    sys.stdout = sys.stderr = open("/var/log/cphash.log", "a")
    run(host='0.0.0.0',
        port=6996,
        server=PasteServer,
        ssl_pem='/etc/locaweb/certificate.pem')


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], "a:", ["action="])
    except getopt.GetoptError, err:
        print str(err)

    action = 'start'
    for o, a in opts:
        if o in ('-a', '--action'):
            action = a

    daemon = Daemon(name='cphash', catch_all_log="/var/log/cphash.log")
    if action == 'start':
        daemon.start()
        main()
    elif action == 'status':
        daemon.status()
    elif action == 'stop':
        daemon.stop()
    elif action == 'debug':
        main()
