#! /usr/bin/perl

use 5.010001;
use strict;
use warnings;
use feature ":5.10";
use autodie;
use Digest::SHA1 qw(sha1_hex);
use File::Basename;
use File::Path qw(make_path);

use Pod::Usage;
use File::Copy;
use Getopt::Long;

sub slurp($);

my $ca_dir = "CA";
my $umask = 077;

MAIN: {

    umask $umask;

    GetOptions() or pod2usage;

    given (shift) {
	when ("init") {
	    exit init(@ARGV);
	}
    }
}

sub init {

    my $cnf = "conf/openssl.cnf";
    local $_;

    make_path dirname $cnf;
    make_path "$ca_dir/newcerts";
    make_path "var/bundles";

    die "$cnf already exists" if -f $cnf
	or -f "$ca_dir/serial"
	or -f "$ca_dir/index.txt";

    # copy the config and remember the hash of 
    # the orig config
    copy "/usr/lib/ssl/openssl.cnf" => $cnf;
    my $fh;
    $_ = slurp $cnf;
    open($fh, ">", "$cnf-orig.sha1");
    say {$fh} sha1_hex($_);
    say "now you should edit $cnf…";

    # edit the config
    open($fh, "+<", $cnf);
    $_ = join "", <$fh>;
    s/\.\/demoCA/.\/$ca_dir/;
    seek($fh, 0, 0);
    truncate($fh, 0);
    print $fh $_;


    open($fh, ">", "$ca_dir/serial");
    print {$fh} "00\n";

    open($fh, ">", "$ca_dir/index.txt");
    close($fh);

    return 0;
}

sub slurp($) {
    my $fn = shift;
    open(my $fh => $fn) or die "$fn: $!";
    return <$fh> if wantarray;
    return join "", <$fh>;
}


__END__

=head1 NAME

 micro-ca -- you name it

=head1 SYNOPSIS

 micro-ca init

=head1 DESCRIPTION

...

=head1 SUBCOMMANDS

=over

=item B<--init>

Initialize the data structure.

=back

=cut


