#!/usr/local/cpanel/3rdparty/bin/perl
# The host's settings for the GhostParse cPanel plugin (run as root):
#   ghostparse-cpanel config --api-url https://ghostparse.com --api-key ek_live_... [--dashboard-url https://mail.yourhost.com/app]
#   ghostparse-cpanel status
use strict;
use warnings;
use lib '/opt/ghostparse-cpanel/lib';
use Getopt::Long ();
use GhostParse::Reseller ();

die "Run this as root.\n" if $> != 0 && !$ENV{GHOSTPARSE_TEST};
my $cmd = shift(@ARGV) // 'help';
my $core = GhostParse::Reseller->new( $ENV{GHOSTPARSE_CONFIG} ? ( config_file => $ENV{GHOSTPARSE_CONFIG} ) : () );

if ( $cmd eq 'config' ) {
    my %o;
    Getopt::Long::GetOptions( \%o, 'api-url=s', 'api-key=s', 'dashboard-url=s' ) or exit 2;
    my $c = eval { $core->save_config( api_url => $o{'api-url'}, api_key => $o{'api-key'}, dashboard_url => $o{'dashboard-url'}, allow_http => $ENV{GHOSTPARSE_TEST} ) };
    if ( !$c ) { print STDERR "Not saved: $@"; exit 1 }
    print "Saved. The key works and can make sub-accounts. Customers see GhostParse in cPanel (Email section) where the feature is on.\n";
}
elsif ( $cmd eq 'status' ) {
    my $c = $core->config;
    if ( !$c ) { print "Not set up. Run: ghostparse-cpanel config --api-url https://ghostparse.com --api-key ek_live_...\n"; exit 1 }
    ( my $shown = $c->{api_key} ) =~ s/^(ek_live_.{4}).*/$1…/;
    print "GhostParse: $c->{api_url}\nAPI key:    $shown\nDashboard:  $c->{dashboard_url}\n";
}
else {
    print "Usage:\n  ghostparse-cpanel config --api-url URL --api-key KEY [--dashboard-url URL]\n  ghostparse-cpanel status\n";
    exit( $cmd eq 'help' ? 0 : 2 );
}
