#!/usr/bin/perl
#  (changes to "./amnesia/config/chroot_local-includes/usr/local/bin/tails-start-i2p"

use feature "state";



### helper subs

sub get_router_port {
    # gets router port (default 7657) from /etc/i2p/clients.config
    state $routerPort = 0;
    my $I2pDefaultPort = 7657;


    if($routerPort) {
    # If we found the Port before there should be no need to recheck it.
        return $routerPort;
    }


    my $conffile;
    if(! open($conffile, "<", "/etc/i2p/clients.config")) {
        warn "Can not open i2p config file '/etc/i2p/client.config'.".
        " Using default port ". $I2pDefaultPort." for I2P webinterface instead.";
        return $I2pDefaultPort;
    }
    my @client_config = <$conffile>;
    close($conffile);
    chomp(@client_config);


    my $ClientAppNo = -1;
    my $line;
    foreach $line (@client_config) {
        if($line =~ m/^clientApp\.([0-9]+)\.main=net\.i2p\.router\.web\.RouterConsoleRunner$/) {
            #we are trying to get $NUMBER$ from >>clientApp.$NUMBER$.main=net.i2p.router.web.RouterConsoleRunner<<
            $ClientAppNo = $1;
            last;
        }
    }
    if($ClientAppNo == -1) {
        warn "Check wheather '/etc/i2p/client.config' includes"
        ." 'clientApp.[0-9].main=net.i2p.router.web.RouterConsoleRunner' .".
        " Using default port ". $I2pDefaultPort." for I2P webinterface instead.";
        return $I2pDefaultPort;
    }


    my $regex = '^clientApp\.' . $ClientAppNo . '\.args=([0-9]{1,5})\ [0-9s:,. \-]+ \.\/webapps\/[\s]*$';
    #      'clientApp.$NUMBER$.args=$PORT$ ::1,127.0.0.1 ./webapps/'
    #                   $PORT$ ::1 ./webapps/
    #                   $PORT$ ::1,127.0.0.1 -s 7667 ::1,127.0.0.1 ./webapps/
    #here $NUMBER$ is the one we obtained above and $PORT$ is what we want to get
    #doesn't match if only https port is given.
    foreach $line (@client_config) {
        if (($routerPort) = ($line =~ m/$regex/)) {
            return $routerPort;
        }
    }
    warn "RegEx checking 'clientApp.".$ClientAppNo.".args=[...]' didn't match.".
    "Can not find port in '/etc/i2p/client.config'." .
    " Using default port ". $I2pDefaultPort." for I2P webinterface instead.";
    return $I2pDefaultPort;

}

print "result is: " . get_router_port() . "\n";
print "result (without calculation) is: " . get_router_port() . "\n";