#!/usr/bin/perl -wT
# -*- Mode: perl; tab-width: 4; indent-tabs-mode: nil; -*-
#
# Referrer Tracking: Setup

use strict;
use CGI::Carp;
use HTML::Entities;
use lib 'lib';

use vars '@ISA';
@ISA = qw(TheCommon);
require TheCommon;

sub main {
    my $self = shift;

    # /setup?password=<password>
    #    if password matches internal password, set up databases

    # if password matches internal password, set up databases

    my $password = $self->{query}->param('password');

    if (not ((defined $self->{config}->{password}) and (defined $password) and ($password eq $self->{config}->{password}))) {
        return $self->{http}->error('401 Unauthorised', 'You are not allowed to run this script.');
    }

    eval {
        $self->{database}->setup();
        $self->{database}->addDestination($self->{config}->{home}, 0, 0); # 1st 0 is 'not a download', second is 'use id 0'
    };
    my $error = $@;

    my @passwords = ();
    while (@passwords < 20) {
        push(@passwords, encode_entities($self->newPassword()));
    }

    my $uri = encode_entities($self->{config}->{home});
    $self->{http}->page('Setup Complete');
    if ($error) {
        $error = encode_entities($error);
        $self->{http}->print("<p>Failed: $error</p>\n");
    } else {
        $self->{http}->print("<p>Done.</p>\n");
    }
    local $" = ', ';
    $self->{http}->print("<p>Sample passwords: @passwords.</p>\n");
    $self->{http}->print("<p><a href=\"$uri\">Return to home page</a>.</p>");

}
