#!/usr/bin/perl

package keyparty_common;

#### Only real configuration option

# root directory of all key parties
$target_root = "/srv/www/stefan.samaflost.de/htdocs/keysigning";

# root URL for all key parties
$root_url = "http://stefan.samaflost.de/keysigning/";

####

use vars qw! $target_root $root_url $event_name $event_date $event_year $event_month $event_day $event_time $event_dir $event_url $event_keyring $event_keyring_asc $event_rel_keyring $event_rel_keyring_asc!;
use strict;

# Drop ending any / from dir settings
$target_root =~ s!/$!!;
$root_url =~ s!/$!!;

$event_name = shift;
$event_date = shift;
($event_year, $event_month, $event_day, $event_time) =
    $event_date =~ /^(\d{4})(\d{2})(\d{2})(\d*)$/;


## load all plugins from plugin_dir
sub load_plugins {
    my $plugin_dir = shift;
    $plugin_dir =~ s!/$!!;
    my @plugins = ();
    # Plugins: Start
    if ($plugin_dir and opendir PLUGINS, $plugin_dir) {
        foreach my $plugin (grep { /^\w+$/ && -f "$plugin_dir/$_"  }
                            sort readdir(PLUGINS)) {
            my($plugin_name, $off) = $plugin =~ /^\d*(\w+?)(_?)$/;
            if ($off ne '_') {
                require "$plugin_dir/$plugin";
                push @plugins, $plugin_name;
            }
        }
        closedir PLUGINS;
    }
    return @plugins
}

## run the configure function in all plugins that declare one
sub run_plugins_configure {
    run_plugins("configure", shift);
}

# run a function in all plugins that declare it
sub run_plugins {
    my ($function, @plugins) = @_;
    foreach my $plugin ( @plugins ) {
        if ($plugin->can($function)) {
            $plugin->$function();
        }
    }
}

## calculate paths based on configuration
sub calc_paths {
    my $combined = $event_name . "_" . $event_date;
    $event_dir = $target_root . "/" . $combined;
    $event_url = $root_url . "/" . $combined . "/";
    $event_rel_keyring = $combined . ".gpg";
    $event_keyring = $event_dir . "/" . $event_rel_keyring;
    $event_rel_keyring_asc = $combined . ".asc";
    $event_keyring_asc = $event_dir . "/" . $event_rel_keyring_asc;
}

## replace all Perl variables in a text - stolen from blosxom
sub interpolate {
    my $template = shift;
    $template =~ 
        s/(\$\w+(?:::)?\w*)/"defined $1 ? $1 : ''"/gee;
    return $template;
}  

sub export_keys {
    system ("gpg",
            "--keyring",  $event_keyring,
            "--no-default-keyring",
            "--export", "--armor",
            "--batch", "--yes",
            "--no-options",
            "--output", $event_keyring_asc);
}

