# -*- coding: utf-8 -*-
# vim:fenc=utf-8

# This file is part of the  X2Go Project - https://www.x2go.org
# Copyright (C) 2012-2020 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
#
# X2Go Session Broker is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# X2Go Session Broker is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

# modules
import os.path
import paramiko
import tornado.web

import x2gobroker._paramiko
x2gobroker._paramiko.monkey_patch_paramiko()

import x2gobroker.defaults

from x2gobroker.loggers import logger_error

class _RequestHandler(tornado.web.RequestHandler):
    def _handle_request_exception(self, e):
        logger_error.error('HTTP request error: {error_msg}'.format(error_msg=e))


class X2GoBrokerItWorks(_RequestHandler):
    """\
    HTTP request handler that simply replies with an "It works" page.

    """
    http_header_items = {
        'Content-Type': 'text/plain; charset=utf-8',
        'Expires': '+1h',
    }

    def _gen_http_header(self):

        for http_header_item in list(self.http_header_items.keys()):
            self.set_header(http_header_item, self.http_header_items[http_header_item])

    def get(self, *args, **kwargs):

        self.write('<body><html>')
        self.write('<h1>X2Go Session Broker</h1>')
        self.write('<p>It works...</p>')
        self.write('</body></html>')


class X2GoBrokerPubKeyService(_RequestHandler):
    """\
    HTTP request handler that provides X2Go Session Broker's SSH public
    keys, if any are configured.

    """
    http_header_items = {
        'Content-Type': 'text/plain; charset=utf-8',
        'Expires': '+1h',
    }

    def _gen_http_header(self):

        for http_header_item in list(self.http_header_items.keys()):
            self.set_header(http_header_item, self.http_header_items[http_header_item])

    def get(self, *args, **kwargs):

        output = ""

        broker_home = x2gobroker.defaults.X2GOBROKER_HOME

        if os.path.exists('{home}/.ssh/id_rsa.pub'.format(home=broker_home)):
            pubkey = paramiko.RSAKey(filename='{home}/.ssh/id_rsa'.format(home=broker_home))
            output += 'command="/usr/lib/x2go/x2gobroker-agent",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa {pubkey} {user}@{hostname}\n'.format(pubkey=str(pubkey.get_base64()), user=x2gobroker.defaults.X2GOBROKER_DAEMON_USER, hostname=x2gobroker.defaults.X2GOBROKER_HOSTNAME)

        if os.path.exists('{home}/.ssh/id_dsa.pub'.format(home=broker_home)):
            pubkey = paramiko.DSSKey(filename='{home}/.ssh/id_dsa'.format(home=broker_home))
            output += 'command="/usr/lib/x2go/x2gobroker-agent",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-dss {pubkey} {user}@{hostname}\n'.format(pubkey=str(pubkey.get_base64()), user=x2gobroker.defaults.X2GOBROKER_DAEMON_USER, hostname=x2gobroker.defaults.X2GOBROKER_HOSTNAME)

        self.write(output)
