#!/usr/bin/perl

# 1. Confirm local distro and release for compatibility
# 2. Confirm access to https://activate.freeswitch.org/activate/status
# 3. Call https://activate.freeswitch.org/activate/generate 
# 3a. In case of auth failure, let user know to check credentials
# 3b. In case of now 'crt' key, then let the user the cert has already been generated for those configs, and display cert info
# 3c. If key 'crt' is returned, then write the certs to correct locations, and add CA to proper location. 
#     Then add the debian source 'temp' file, and 'temp' config file, update, then install fss-commercial package.
#     Then remove temp config and source files, and call update again.
#

use Data::Dumper;
use LWP::UserAgent;
use IPC::Run    qw( run   );
use File::Slurp qw( slurp );
use Socket;
use JSON;

my $version = "0.3.1";

if ( confirm_local_distro_compatibility() ) {
    die "Not a compatible server";
}

if ( confirm_access_to_activate_freeswitch_com() ) {
    die "Not able to successfully connect to https://activate.freeswitch.com";
}

if ( fetch_fss_certificate() ) {
    die "Unable to download client SSL certificate";
}

if ( install_fss_debian_repo() ) {
    die "Unable to setup commercial repo settings";
}

print "\n\n\n\n";
print "Congratulations, this server is now configured properly for the Commercial FreeSWITCH Platform\n";
exit 0;


sub debug_log {
    my $line = shift;
    my $debug = 1;

    print $line if $debug;
}

sub confirm_local_distro_compatibility {
    # Needs to confirm running on linux, as root, on Debian Jessie
    my ($in, $err, $out);
    my $result = 1;

    $result = run(["lsb_release", "-a"], \$in, \$err, \$out);

    if ( ! $result || $err !~ m/jessie|stretch/g) {
	return 1;
    }

    if ( `whoami` !~ m/root/g ) {
	print "This script MUST be run as root\n";
	return 1;
    }

    return 0;
}

sub confirm_access_to_activate_freeswitch_com {
    # Check both DNS, and HTTPS connection to the server(confirm no webfilter in the way)
    my $address = inet_aton('activate.freeswitch.com');

    if ( ! defined $address ) {
	print "Unable to resolve activate.freeswitch.com\nPlease check your DNS settings.\n";
	return 1;
    }

    my $ua = LWP::UserAgent->new;
    $ua->agent("FSS Commercial Conversion Script ($version)");
    $ua->timeout(5);

    my $request = HTTP::Request->new(POST => 'https://activate.freeswitch.com/activate/status');
    $request->header( 'Accept' => 'application/json' );

    my $response = $ua->request($request);

    if ( ! $response->is_success ) {
	print "There was an error making a connection to https://activate.freeswitch.com from this server\n";
	print "Check your network routing, firewall settings, and confirm there is not a webfilter blocking the connection\n";
	print "Status line: " . $response->status_line . "\n";
	return 1;
    }

    return 0;
}

sub fetch_fss_certificate {
    my $password = "pass";

    print "Enter Password token:\n";
    chop($password=<STDIN>);

    my $ua = LWP::UserAgent->new;
    $ua->agent("FSS Commercial Conversion Script ($version)");
    $ua->timeout(5);

    my $request = HTTP::Request->new(POST => 'https://activate.freeswitch.com/activate/generate');
    $request->header( 'Accept' => 'application/json' );
    $request->header( 'FSS-Password' => $password );

    my $response = $ua->request($request);

    if ( ! $response->is_success ) {
	print "There was an error downloading the certificate from http://activate.freeswitch.com from this server\n";
	print "Check your network routing, firewall settings, and confirm there is not a webfilter blocking the connection\n";
	print "Status line: " . $response->status_line . "\n";
	return 1;
    }

    my $data = from_json($response->decoded_content);

    if ( ( not defined $data->{key} ) || ( not defined $data->{crt} ) ) {
	print "ERROR: The certificates could not be downloaded. Are you sure they have not already been downloaded to another machine?\n";
	print "ERROR: Certificates can only be downloaded once, so you will have to reset the certificates, which will invalidate the previous one\n";
	return 1;
    }

    open(FILE, '>/etc/ssl/private/fss.key');
    print FILE $data->{key};
    close(FILE);

    open(FILE, '>/etc/ssl/private/fss.crt');
    print FILE $data->{crt};
    close(FILE);

    open(FILE, '>/etc/ssl/private/ca.crt');
    print FILE $data->{ca};
    close(FILE);

    open(FILE, '>/etc/ssl/private/token.txt');
    print FILE $password;
    close(FILE);

    return 0;
}

sub install_fss_debian_repo {

    my $source_file = <<END;
deb https://repo.freeswitch.com/debian/ jessie main
deb-src https://repo.freeswitch.com/debian/ jessie main
END

    my $apt_conf    = <<END;
Acquire::https::repo.freeswitch.com {
    Verify-Peer "true";
    Verify-Host "true";

    CaInfo  "/etc/ssl/private/ca.crt";
    SslKey  "/etc/ssl/private/fss.key";
    SslCert "/etc/ssl/private/fss.crt";
};
END

    open(FILE, '>/etc/apt/sources.list.d/fss.temp.list');
    print FILE $source_file;
    close(FILE);

    open(FILE, '>/etc/apt/apt.conf.d/fss.temp.conf');
    print FILE $apt_conf;
    close(FILE);

    open(FILE, '>/tmp/fss.gpg');
    print FILE fss_repo_gpg_key();
    close(FILE);

    system("apt-key add /tmp/fss.gpg"); # Add the repo key
    print "Updating the apt package listing for the Commercial FSS repo\n";
    system("apt-get update");
    print "Installing the FSS Commercial Support package\n";
    system("apt-get install -y fss-commercial-support");

    # Delete temp apt files.
#    system("rm /etc/apt/sources.list.d/fss.temp.list");
#    system("rm /etc/apt/apt.conf.d/fss.temp.conf");

    return 0;
}

sub fss_repo_gpg_key {
    my $key = <<END;
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v1.4.12 (GNU/Linux)

mQINBFPNVhsBEADRGTrooJKGQIIS44eDFM7mV8mWNmwByZG9kKvwABKtJZHA+tWG
1yFE3co9oQgkA6HWPEjcUjTFYAbE3jNSVzQa647qBn9Lso+dQV169m0ePZQPescu
1ZIinTfrNfzRVwNOWUPr+Ke4N8e0FKEDP1H/M3E+zPWHig7+AOxZJ19Aj7hcShdA
KfF24odijmgG6rA0tU1HMVJ4pe5eO9G55vGYKJA3myQDbWHJefpPS6rNGCUTgaAc
97sJ7msT/hxX3GpxQxR30g1wQoKq0A8+TJCPke2pHiSbK/jOkz+wTCmyeXvImbx0
UYlqwcDVsI4/diEm9Vq7mHXzg/rOJyb2wBtcwoy89o4+yjZxbrBQLxOjFhY//shR
wg5npc9WT40JF4I+/t3H3ZO+Q+5sazjGafR5Xo2lRx4ai9WJcK7p8yOGpVAycu0N
xAg+xEo+QBDG+aPbYsQ4acQP2OmBLKk2/FklmSI5nqkg8y/CnDuYQTbbtbobbYFX
HttpTMAphq55LG8TVuB2F7CHf7DOJqRzdyKFV7LBdyQRIbIVN6V4/7n8g/O/DO83
RMxS2igDcjWYwmF/Csnh784OoS70atPnAENj9wyroJOciKEaQn0m2nlWOpE+UNW1
z+NaUUtEJjap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