#!/usr/bin/perl

package keyparty_setup;

### Configuration

# only real configuration option, everything else can be overridden by plugins
# where are the plugins?
$plugin_dir = "/home/stefan/dev/keyparty/setup_plugins";

# where are the templates that should be copied to the event directory
$skel_dir = "/home/stefan/dev/keyparty/setup_skel";

use vars qw! $plugin_dir $skel_dir @plugins %files !;

require "common.pl";

use strict;
use utf8;
use File::Basename;
use File::Find;
use File::Path;
use FileHandle;

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

@plugins = keyparty_common::load_plugins($plugin_dir);

#allow plugins to override or create configuration settings
keyparty_common::run_plugins_configure(@plugins);

# calculate path and file names from configuration
keyparty_common::calc_paths();

# create target directory and populate it from skeleton dir
mkpath($keyparty_common::event_dir);

my $fh = new FileHandle;

if ($skel_dir) {
    find (
        sub {
            my ($rel_path) = $File::Find::name =~ m#$skel_dir/(.*)$#;
            -f $File::Find::name and -r $File::Find::name
                and $files{$rel_path} = $File::Find::name;
        }, $skel_dir);
    
    foreach my $rel_path (sort keys %files) {
        if ($fh->open("< $files{$rel_path}")) {
            my $content = keyparty_common::interpolate(join '', <$fh>);
            $fh ->close();
            my $outfile = $keyparty_common::event_dir . "/" . $rel_path;
            my $outdir = dirname($outfile);
            -d $outdir or mkpath($outdir);
            $fh->open("> $outfile");
            $fh->print($content);
            $fh ->close();
        }
    }
}

$fh->open("> $keyparty_common::event_keyring") and $fh->close()
    and chmod(0600, $keyparty_common::event_keyring);

# allow plugins to do something after the keyring has been created but
# not exported, yet
keyparty_common::run_plugins("pre_export", @plugins);

keyparty_common::export_keys();

# allow plugins to do something after we've done all other stuff
keyparty_common::run_plugins("postprocess", @plugins);

