#!/usr/bin/perl
#
# Copyright 2007-2009 Kees Cook <kees@outflux.net>
# License: GPLv3
#
# This script builds the SQLite DB.  It needs to write to the current
# directory as the Apache CGI user:
#  chmod o+w .
#  *run CGI*
#  chmod o-w .
#
package SQL_Good;
use base 'CGI::Application';
use strict;
use warnings;
use CGI qw/:standard/;
use DBI;

sub setup {
    my $self = shift;
    $self->start_mode('init');
    $self->run_modes(
        'init' => 'do_init',
    );

    my $dbfile = "./sql-demo.dbl";

    if (-w $dbfile) {
        $self->{'dbh'} = DBI->connect("dbi:SQLite:$dbfile");
        $self->{'dbh'}->do("PRAGMA journal_mode = OFF") if ($self->{'dbh'});
        $self->{'dbh'}->do("PRAGMA synchronous = ON") if ($self->{'dbh'});
    }
}

sub do_init {
    my $self = shift;
    my $output = '';
    my $q = $self->query();

    if (!defined($self->{'dbh'})) {
        my $title = "SQL Init Unavailable";
        return $q->start_html(-title => $title).
               $q->h1($title)."\nPermission denied.\n".$q->end_html();
    }

    $self->{'dbh'}->do("CREATE TABLE IF NOT EXISTS
            users (    id         integer primary key autoincrement,
                secret    char(64),
                password  char(32) ) ");
    my $query = $self->{'dbh'}->prepare(
        "REPLACE INTO users ( id, secret, password ) VALUES ( ?, ?, ? )");
    $query->execute(1,'OMGPONIES!','super-secret-password');
    $query->finish;

    my $title = "Initialized";
    $output .= $q->start_html(-title => $title );
    $output .= $q->h1($title)."\n";
    $output .= $q->end_html();

    return $output;
}

sub teardown {
    my $self = shift;

    $self->{'dbh'}->disconnect if ($self->{'dbh'});
}

package main;
use strict;
use warnings;

my $webapp = SQL_Good->new();
$webapp->run();
