#!/usr/bin/perl -w

#----------------------------------------------------------------------
# SME Server action script to ensure a valid CrowdSec bouncer API key
# exists for the smanager web panel.
#----------------------------------------------------------------------

use strict;
use warnings;
use esmith::ConfigDB;
use Mojo::UserAgent;
use Mojo::JSON qw(decode_json);

my $BOUNCER_NAME = 'smanager-panel';
my $DEFAULT_URL  = 'http://127.0.0.1:8787';

# 1. Open SME configuration DB (read/write)
my $db = esmith::ConfigDB->open
    or die "Failed to open esmith::ConfigDB\n";

# Ensure 'crowdsec' record exists in configuration DB
my $rec = $db->get('crowdsec');
if (!$rec) {
    $db->new_record('crowdsec', {
        type    => 'service',
        status  => 'enabled',
        LapiUrl => $DEFAULT_URL,
    });
    $rec = $db->get('crowdsec');
}

my $lapi_url = $rec->prop('LapiUrl')  || $DEFAULT_URL;
my $api_key  = $rec->prop('smanager') || '';

if (!$rec->prop('LapiUrl')) {
    $rec->set_prop('LapiUrl', $lapi_url);
}

# 2. Validate existing key against CrowdSec LAPI first (regardless of bouncer name)
sub is_key_valid {
    my ($url, $key) = @_;
    return 0 unless $key;

    my $ua = Mojo::UserAgent->new(connect_timeout => 3, request_timeout => 5);
    my $tx = $ua->get("$url/v1/decisions" => { 'X-Api-Key' => $key });

    if (my $res = $tx->result) {
        return 1 if $res->code == 200;
    }
    return 0;
}

if ($api_key && is_key_valid($lapi_url, $api_key)) {
    # Stored API key is already valid; nothing to do
    exit 0;
}

# 3. Check if the target bouncer already exists with an invalid/lost key
sub bouncer_exists {
    my ($name) = @_;
    my $raw = `/usr/bin/cscli bouncers list -o json 2>/dev/null`;
    return 0 unless $raw;

    my $list = eval { decode_json($raw) };
    return 0 unless ($list && ref $list eq 'ARRAY');

    for my $b (@$list) {
        return 1 if (($b->{name} // '') eq $name);
    }
    return 0;
}

if (bouncer_exists($BOUNCER_NAME)) {
    system('/usr/bin/cscli', 'bouncers', 'delete', $BOUNCER_NAME);
}

# 4. Generate a new bouncer API key (compatible with all cscli versions)
my $output = `/usr/bin/cscli bouncers add $BOUNCER_NAME 2>&1`;
my $new_key = '';

for my $line (split /\r?\n/, ($output // '')) {
    $line =~ s/^\s+|\s+$//g;
    next if $line eq '';
    next if $line =~ /^level=/;
    next if $line =~ /^API key for/i;
    next if $line =~ /^Please keep this key/i;

    # Match inline format: "Api key for '...': <KEY>"
    if ($line =~ /Api key for [^:]+:\s*(\S+)/i) {
        $new_key = $1;
        last;
    }
    # Match standalone key line (alphanumeric + base64 chars, no spaces/colons)
    if ($line =~ /^[A-Za-z0-9+\/_=-]{16,}$/) {
        $new_key = $line;
        last;
    }
}

if ($new_key) {
    $rec->set_prop('smanager', $new_key);
    warn "CrowdSec bouncer '$BOUNCER_NAME' configured and key saved to ConfigDB.\n";
    exit 0;
} else {
    warn "Failed to generate CrowdSec bouncer API key for '$BOUNCER_NAME'. Output was:\n$output\n";
    exit 1;
}
