#!/usr/bin/env perl
use strict;
use warnings;
use File::Path qw(make_path);
use LWP::Simple qw(getstore);

my $PREFIX   = "/usr/local/sectools";
my $BIN      = "/usr/local/bin/sectools";
my $SRC_URL  = "https://lic.east4serv.com/sectools/v6/sectools.pl";
my $TARGET   = "$PREFIX/sectools.pl";
my $DIALOGRC = "$PREFIX/dialogrc";

sub fake_progress {
    my ($msg) = @_;
    for my $i (0..20) {
        printf("\r[*] %s %d%%", $msg, $i*5);
        select(undef, undef, undef, 0.1);
    }
    print "\n";
}

sub main {
    print "[*] Starting installer...\n";
    fake_progress("Checking system");
    make_path($PREFIX) unless -d $PREFIX;

    fake_progress("Downloading sources");
    my $rc = getstore($SRC_URL, $TARGET);
    if ($rc != 200) {
        die "[-] Failed to download sectools.pl from $SRC_URL (HTTP $rc)\n";
    }
    chmod 0700, $TARGET;

    fake_progress("Creating launcher");
    open my $fh, ">", $BIN or die "Cannot write $BIN: $!";
    print $fh <<"EOF";
#!/bin/bash
export TERM=\${TERM:-xterm}
exec /usr/bin/env perl $TARGET "\$@"
EOF
    close $fh;
    chmod 0755, $BIN;

    fake_progress("Applying theme");
    open my $dfh, ">", $DIALOGRC or die "Cannot write $DIALOGRC: $!";
    print $dfh <<"RC";
# East4Serv dialog theme (black background, yellow highlights)
use_shadow = OFF
use_colors = ON
screen_color = (BLACK,BLACK,OFF)
title_color  = (YELLOW,BLACK,ON)
border_color = (YELLOW,BLACK,ON)
button_active_color   = (BLACK,YELLOW,ON)
button_inactive_color = (YELLOW,BLACK,OFF)
item_color          = (WHITE,BLACK,OFF)
item_selected_color = (BLACK,YELLOW,ON)
RC
    close $dfh;

    print "\n[+] Sectools installed successfully!\n";
    print "[*] Run it using: sectools\n";
}

main();

