#!/usr/bin/perl
use strict;
use FindBin qw($Bin);
use lib $Bin;
use onserver;
use Cwd;
use File::Path;
use URI::Escape;
use DBI;
use Config::IniFiles;

setup();

print "\nEnter the name of your project (the title of this Trac instance).\n";
print "Project name: ";
my $name=<STDIN>;
chomp($name);

my $dbh = DBI->connect("DBI:mysql:database=$sqldb;host=$sqlhost", $sqluser, $sqlpass, {RaiseError => 1});
$dbh->do('alter database collate utf8_general_ci');

my $dbstring = "mysql://" . uri_escape($sqluser) . ":" . uri_escape($sqlpass) . "\@$sqlhost/$sqldb";

print "\nEnter the type of version-control repository this project uses.\n";
print "You'll have to set up the repo yourself; feel free to ask scripts@ for help.\n";
print "If you don't want version-control integration, take the default.\n";
print "Repository type (default svn; also bzr, git, hg): ";
my $repotype=<STDIN>;
chomp($repotype);
$repotype = $repotype ? $repotype : 'svn';

print "\nEnter the path to the version-control repository.\n";
print "If you don't want version-control integration, leave blank.\n";
print "Path to repository: ";
my $repopath=<STDIN>;
chomp($repopath);

print STDERR "running trac-admin:\n";
system(qw(/usr/bin/trac-admin tracdata initenv),
       $name, $dbstring, $repotype, $repopath);
# XXX this exposes the SQL password on the command line

#aka perl -pe 's/\@ADDREND\@/$addrend/g' <.htaccess.in >.htaccess
open IN, '<.htaccess.in'; open OUT, '>.htaccess';
while (<IN>) {
    s/\@ADDREND\@/~$USER\/$addrend/g;
    print OUT $_;
}
close IN; close OUT;

my $cfg = Config::IniFiles->new(-file => 'tracdata/conf/trac.ini');
$cfg->setval('trac', 'default_charset', 'utf-8');
$cfg->AddSection('components');
$cfg->newval('components', 'webadmin.*', 'enabled');
$cfg->newval('components', 'gitplugin.*', 'enabled') if $repotype eq "git";
$cfg->RewriteConfig();

system(qw(/usr/bin/trac-admin tracdata permission add), $human, 'TRAC_ADMIN');

chmod 0777, '.htaccess';
unlink '.htaccess.in';

open OUT, '>tracdata/.htaccess';
print OUT "Deny from all\n";
close OUT;
chmod 0777, 'tracdata/.htaccess';

exit 0;
