package PMG::Service::pmgquarantineproxy;

use strict;
use warnings;

use HTTP::Headers;
use HTTP::Status qw(:constants);
use HTTP::Response;
use URI;
use URI::Escape;

use PVE::APIServer::AnyEvent;
use PVE::APIServer::Formatter;
# Formatter only holds the registry; the formatters themselves register
# themselves when their module is loaded. Without these two the daemon answers
# every successful API call with 501 "no formatter for uri ..., json", while
# still returning the right status for everything it refuses -- so a test that
# only checks status codes will not notice. 'htmlmail' needs no line here: it
# is registered by PMG::API2::Quarantine, which arrives through
# PMG::QuarantineHTTPServer.
use PVE::APIServer::Formatter::Standard;
use PVE::APIServer::Formatter::HTML;
use PVE::APIServer::Utils;
use PVE::Daemon;
use PVE::SafeSyslog;
use PVE::Tools;

use PMG::Config;
use PMG::QuarantineHTTPServer;
use PMG::Ticket;

use Template;

use base qw(PVE::Daemon);

my $cmdline = [$0, @ARGV];

my %daemon_options = (
    max_workers => 3,
    restart_on_error => 5,
    stop_wait_time => 15,
    leave_children_open_on_reload => 1,
    setuid => 'www-data',
    setgid => 'www-data',
    pidfile => '/run/pmgquarantineproxy/pmgquarantineproxy.pid',
);

my $daemon = __PACKAGE__->new('pmgquarantineproxy', $cmdline, %daemon_options);

sub add_dirs {
    my ($result_hash, $alias, $subdir) = @_;

    PVE::APIServer::AnyEvent::add_dirs($result_hash, $alias, $subdir);
}

my $gui_base_dir = "/usr/share/javascript/pmg-gui";
my $mobile_quarantine_ui_base_dir = "/usr/share/pmg-mobile-quarantine-ui/";
my $extjs_dir = "/usr/share/javascript/extjs/";
my $fontawesome_dir = "/usr/share/fonts-font-awesome";
my $widgettoolkit_dir = '/usr/share/javascript/proxmox-widget-toolkit';
my $i18n_dir = '/usr/share/pmg-i18n/';
my $mobile_i18n_dir = '/usr/share/pmg-yew-quarantine-i18n/';

sub init {
    my ($self) = @_;

    my $proxyconf = PVE::APIServer::Utils::read_proxy_config($self->{name});

    my $cfg = PMG::Config->new();
    my $port = $cfg->get('spamquar', 'listenport') // 8007;

    my $accept_lock_fn = "/var/lock/pmgquarantineproxy.lck";

    my $lockfh = IO::File->new(">>${accept_lock_fn}")
        || die "unable to open lock file '${accept_lock_fn}' - $!\n";

    my $listen_ip = $proxyconf->{LISTEN_IP};
    my $socket = $self->create_reusable_socket($port, $listen_ip);

    # Only what the quarantine UI needs. Deliberately without the xtermjs
    # console and the pmg-docs tree, which belong to the management interface.
    my $dirs = {};

    add_dirs($dirs, '/pve2/locale/', $i18n_dir);
    add_dirs($dirs, '/pve2/ext6/', $extjs_dir);
    add_dirs($dirs, '/pve2/images/' => "$gui_base_dir/images/");
    add_dirs($dirs, '/pve2/css/' => "$gui_base_dir/css/");
    add_dirs($dirs, '/pve2/js/' => "$gui_base_dir/js/");
    add_dirs($dirs, '/mobile/' => "$mobile_quarantine_ui_base_dir/");
    add_dirs($dirs, '/mobile/css/' => "$mobile_quarantine_ui_base_dir/css/");
    add_dirs($dirs, '/mobile/fonts/' => "$mobile_quarantine_ui_base_dir/fonts/");
    add_dirs($dirs, '/mobile/images/' => "$mobile_quarantine_ui_base_dir/images/");
    add_dirs($dirs, '/mobile/i18n/' => "$mobile_i18n_dir/");
    add_dirs($dirs, '/fontawesome/css/' => "$fontawesome_dir/css/");
    add_dirs($dirs, '/fontawesome/fonts/' => "$fontawesome_dir/fonts/");
    add_dirs($dirs, '/pwt/css/' => "$widgettoolkit_dir/css/");
    add_dirs($dirs, '/pwt/images/' => "$widgettoolkit_dir/images/");
    add_dirs($dirs, '/pwt/themes/' => "$widgettoolkit_dir/themes/");

    # Note: this cannot come from /etc/default/pmgquarantineproxy.
    # PVE::APIServer::Utils::read_proxy_config only returns a fixed set of
    # keys and silently drops everything else, so an extra CERT_FILE there
    # would never arrive. Like the port, it lives in pmg.conf instead.
    my $cert_file = $cfg->get('spamquar', 'listencert') // '/etc/pmg/pmg-api.pem';

    $self->{server_config} = {
        title => 'Proxmox Mail Gateway Quarantine',
        cookie_name => 'PMGAuthCookie',
        keep_alive => 100,
        max_conn => 500,
        max_requests => 1000,
        lockfile => $accept_lock_fn,
        socket => $socket,
        lockfh => $lockfh,
        debug => $self->{debug},
        trusted_env => 0, # not trusted, this listener is meant to be exposed
        logfile => '/var/log/pmgproxy/pmgquarantineproxy.log',
        allow_from => $proxyconf->{ALLOW_FROM},
        deny_from => $proxyconf->{DENY_FROM},
        policy => $proxyconf->{POLICY},
        ssl => {
            cert_file => $cert_file,
            dh => 'skip2048',
            cipher_list => $proxyconf->{CIPHERS},
            ciphersuites => $proxyconf->{CIPHERSUITES},
            honor_cipher_order => $proxyconf->{HONOR_CIPHER_ORDER},
        },
        compression => $proxyconf->{COMPRESSION},
        # Note: there is no authentication for those pages and dirs!
        # '/' deliberately does not serve the management interface here; it
        # only redirects to the quarantine, so a user who types the bare
        # hostname is not left staring at an error.
        pages => {
            '/' => \&redirect_to_quarantine,
            '/quarantine' => sub { get_index($self->{nodename}, @_) },
            '/favicon.ico' => {
                file => '/usr/share/doc/pmg-api/favicon.ico',
            },
            '/proxmoxlib.js' => {
                file => '/usr/share/javascript/proxmox-widget-toolkit/proxmoxlib.js',
            },
            '/qrcode.min.js' => {
                file => '/usr/share/javascript/qrcodejs/qrcode.min.js',
            },
        },
        dirs => $dirs,
    };

    if (defined($proxyconf->{DHPARAMS})) {
        $self->{server_config}->{ssl}->{dh_file} = $proxyconf->{DHPARAMS};
    }
    if (defined($proxyconf->{DISABLE_TLS_1_2})) {
        $self->{server_config}->{ssl}->{tlsv1_2} = !$proxyconf->{DISABLE_TLS_1_2};
    }
    if (defined($proxyconf->{DISABLE_TLS_1_3})) {
        $self->{server_config}->{ssl}->{tlsv1_3} = !$proxyconf->{DISABLE_TLS_1_3};
    }
}

sub run {
    my ($self) = @_;

    my $server = PMG::QuarantineHTTPServer->new(%{ $self->{server_config} });
    $server->run();
}

$daemon->register_start_command();
$daemon->register_restart_command(1);
$daemon->register_stop_command();
$daemon->register_status_command();

our $cmddef = {
    start => [__PACKAGE__, 'start', []],
    restart => [__PACKAGE__, 'restart', []],
    stop => [__PACKAGE__, 'stop', []],
    status => [__PACKAGE__, 'status', [], undef, sub { print shift . "\n"; }],
};

my $template_toolkit;

sub get_template_toolkit {

    return $template_toolkit if $template_toolkit;

    $template_toolkit =
        Template->new({ INCLUDE_PATH => [$gui_base_dir, $mobile_quarantine_ui_base_dir] });

    return $template_toolkit;
}

# The bare host is not an error on this listener, it is simply the quarantine.
# Keep the query string so a link that carries a ticket keeps working.
sub redirect_to_quarantine {
    my ($server, $r, $args) = @_;

    my $target = '/quarantine';
    if (defined(my $query = $r->uri->query())) {
        $target .= "?$query" if length($query);
    }

    my $headers = HTTP::Headers->new(Location => $target);

    return HTTP::Response->new(HTTP_FOUND, "Found", $headers);
}

sub is_phone {
    my ($ua) = @_;

    return 0 if !$ua;

    if ($ua =~ m/(iPhone|iPod|Windows Phone|Android|BlackBerry)/i) {
        return 1;
    }

    return 0;
}

my sub get_path_mtime {
    my ($path) = @_;

    my @stat_res = stat($path) or $!{ENOENT} or die "failed to stat '$path' - $!\n";
    my $mtime = $stat_res[9];

    return $mtime // 0;
}

# Restricted variant of the index in PMG::Service::pmgproxy: quarantine only,
# no console and no management interface.
sub get_index {
    my ($nodename, $server, $r, $args) = @_;

    my $lang = 'en';
    my $username;
    my $token = 'null';
    my $mobile = is_phone($r->header('User-Agent'));
    if (defined($args->{mobile})) {
        $mobile = $args->{mobile} ? 1 : 0;
    }

    my $theme = "";

    if (my $cookie = $r->header('Cookie')) {
        if (my $newlang = ($cookie =~ /(?:^|\s)PMGLangCookie=([^;]*)/)[0]) {
            if ($newlang =~ m/^[a-z]{2,3}(_[A-Z]{2,3})?$/) {
                $lang = $newlang;
            }
        }

        if (my $newtheme = ($cookie =~ /(?:^|\s)PMGThemeCookie=([^;]*)/)[0]) {
            if ($newtheme =~ m/^[a-z]{1,10}(-[a-z]{1,10}){0,5}$/) {
                $theme = $newtheme;
            }
        }

        my $ticket = PVE::APIServer::Formatter::extract_auth_value($cookie, $server->{cookie_name});

        if (defined($ticket) && $ticket =~ m/^PMGQUAR:/) {
            $username = PMG::Ticket::verify_quarantine_ticket($ticket, 1);
        }
    } else {
        if (defined($args->{ticket})) {
            my $ticket = uri_unescape($args->{ticket});
            $username = PMG::Ticket::verify_quarantine_ticket($ticket, 1);
        }
    }

    if ($theme eq "") {
        $theme = "auto";
    }

    $token = PMG::Ticket::assemble_csrf_prevention_token($username)
        if defined($username);

    my $langfile = 0;

    if (-f "/usr/share/pmg-i18n/pmg-lang-$lang.js") {
        $langfile = 1;
    }

    my $wtversionraw = PVE::Tools::file_read_firstline("$widgettoolkit_dir/proxmoxlib.js");
    my $wtversion = '';
    if ($wtversionraw =~ m|^// (.*)$|) {
        $wtversion = $1;
    }

    my $versionraw = PVE::Tools::file_read_firstline("$gui_base_dir/js/pmgmanagerlib.js");
    my $version = '';
    if ($versionraw =~ m|^// (.*)$|) {
        $version = $1;
    }

    my $cfg = PMG::Config->new();
    my $quarantinelink = $cfg->get('spamquar', 'quarantinelink');
    my $consent_text = $cfg->get('admin', 'consent-text');

    $username = '' if !$username;

    my $page = '';

    my $i18n_js_mtime = get_path_mtime($i18n_dir);
    my $i18n_yew_mtime = get_path_mtime($mobile_i18n_dir);
    my $ui_yew_mtime = get_path_mtime($mobile_quarantine_ui_base_dir);

    my $vars = {
        lang => $lang,
        langfile => $langfile,
        username => $username,
        token => $token,
        nodename => $nodename,
        debug => $args->{debug} || $server->{debug},
        version => $version,
        wtversion => $wtversion,
        quarantinelink => $quarantinelink,
        theme => $theme,
        i18n_js_mtime => $i18n_js_mtime,
        i18n_yew_mobile_mtime => $i18n_yew_mtime,
        yew_mobile_mtime => $ui_yew_mtime,
        yew_mobile_base_path => '/mobile',
        consenttext => $consent_text,
    };

    my $template_name = $mobile ? "pmg-mobile-index.html.tt" : "pmg-index.html.tt";

    my $tt = get_template_toolkit();

    $tt->process($template_name, $vars, \$page)
        || die $tt->error() . "\n";

    my $headers = HTTP::Headers->new(Content_Type => "text/html; charset=utf-8");
    my $resp = HTTP::Response->new(200, "OK", $headers, $page);

    return $resp;
}

1;
