# system libraries
import sys
import hmac
import json
import hashlib
import subprocess

import bottle
app = application = bottle.Bottle()

@bottle.route('/management/database/dump', method='POST')
def database_dump():
    return subprocess.check_output(
        ["pg_dump", "-Fc", "mpsdb"]
    )


@bottle.route('/management/reload', method='POST')
def reload_mps():
    try:
        data = json.loads(bottle.request.body)
        # use our hidden credential file to import username and
        # password info
        import mps_credentials

        remote_signature = bottle.request.META.get(
            'HTTP_X_HUB_SIGNATURE'
        ).split('=')[1]
        real_signature = hmac.new(
            mps_credentials.webhook_secret,
            bottle.request.body,
            hashlib.sha1
        ).hexdigest()

        if remote_signature not in real_signature:
            raise Exception

        # we only want to update if we push to master
        if "refs/heads/master" in data['ref']:

            # adam is responsible for deploying to master
            if "nszceta" in data['pusher']['name'] \
                    or "ahgough" in data['pusher']['name']:
                subprocess.call(
                    ['/home/mps/mps-database-server/scripts/reload-all.sh']
                )
                return bottle.response.status(200)

    # return HTTP error if _anything_ goes wrong whatsoever.
    except Exception:
        pass

    return bottle.response.status(304)

# END STATIC ROUTES #

# BEGIN APPLICATION BOOTSTRAP # NO URL ROUTES BELOW THIS LINE #


def run_as_developer():
    bottle.run(host='localhost', port=8098, debug=True)


def run_as_gunicorn():
    bottle.run(host='localhost',
               port=8098,
               server='gunicorn',
               workers=2,
               debug=False)


if __name__ == "__main__":
    try:
        if 'dev' in sys.argv[1]:
            run_as_developer()
        else:
            run_as_gunicorn()
    except IndexError:
        print "You must specify whether this is a 'dev' or 'prod' environment"

# END APPLICATION BOOSTRAP # NO URL ROUTES BELOW THIS LINE #
