#!/usr/bin/env perl

# bin/genssl - SSL CertFP generation script.
# Copyright (C) 2010-2011 Xelhua Development Group, et al.
# This program is free software; rights to this code are stated in doc/LICENSE.

# A simple script for generating an SSL certificate.
use 5.010_000;
use strict;
use warnings;
use FindBin qw($Bin);
use Cwd;
our $VERSION = 1.00;
my $Bin = $Bin;

my ($UPREFIX, %bin);
$bin{cwd} = getcwd;
if (!-e "$Bin/../build/syswide") {
    # Must be a custom PREFIX install.
    $bin{etc} = "$bin{cwd}/etc";
    $bin{var} = "$bin{cwd}/var";
    if (!-e "$Bin/lib/Lib/Auto.pm") {
        # Must be a system wide install.
        $bin{lib} = "$Bin/../lib/autobot/3.0.0";    
        $bin{bld} = "$bin{lib}/build";
        $bin{lng} = "$bin{lib}/lang";
        $bin{mod} = "$bin{lib}/modules";
    }
    else {
        # Or not.
        $bin{lib} = "$Bin/../lib";
        $bin{bld} = "$Bin/../build";
        $bin{lng} = "$Bin/../lang";
        $bin{mod} = "$Bin/../modules";
    }
    $UPREFIX = 1;
}
else {
    # Must be a standard install.
    $bin{etc} = "$Bin/../etc";
    $bin{var} = "$Bin/../var";
    $bin{lib} = "$Bin/../lib";
    $bin{bld} = "$Bin/../build";
    $bin{lng} = "$Bin/../lang";
    $bin{mod} = "$Bin/../modules";
    $UPREFIX = 0;
}

# Get the name of the network this cert is for.
print 'Network Name: ';
my $net = <STDIN>;
$net =~ s/(\r|\n)//gxsm;
say q{};

# Make sure etc/certs/ exists.
if (!-d "$bin{etc}") { mkdir "$bin{etc}", 0755 }
if (!-d "$bin{etc}/certs") { mkdir "$bin{etc}/certs", 0755 }

# Generate key and cert.
system "openssl req -nodes -newkey rsa:2048 -keyout $bin{etc}/certs/$net.key -x509 -days 3650 -out $bin{etc}/certs/$net.cert";
chmod 0400, "$bin{etc}/certs/$net.key";

# Get the fingerprint.
my $fpr = `openssl x509 -noout -fingerprint < $bin{etc}/certs/$net.cert`;
my $fp;
while ($fpr =~ s/(.*\n)//) {
    my $line = $1;
    $line =~ s/(\r|\n)//gsm;

    if ($line =~ m/^SHA1 Fingerprint/sm) {
        my $sfp = substr $line, 17;
        $sfp =~ s/://gxsm;

        $fp = $sfp;
    }
}

# Print the fingerprint.
say 'Done. Fingerprint: '.$fp;

# vim: set ai et sw=4 ts=4:
