#!/usr/bin/env perl
use strict;
use warnings;

use lib '/mit/jifty/perl';
use YAML qw(LoadFile DumpFile);
use URI;

sub prompt
{
    my ($query, $default) = @_;
    print "$query [$default]? ";
    my $response = <STDIN>;
    chomp($response);
    $response = $default unless $response =~ /\S/;
    return $response;
}

sub write_file
{
    my $path = shift;
    my $mode = shift;
    my $contents = shift;
    print "Creating $path...\n";
    open(my $fh, ">", $path) or die("Unable to write $path: $!");
    print $fh $contents;
    close($fh);
    chmod($mode, $path);
}

if(! -f "Makefile.PL" ||  ! -f "bin/jifty" || ! -f "etc/config.yml") {
    die("This doesn't look like a Jifty application...\n");
}

my ($global, $conf);

if( -f "etc/site_config.yml" ) {
    $conf = LoadFile("etc/site_config.yml");
} else {
    $conf = {};
}

$global = LoadFile("etc/config.yml");

my ($sqlhost, $user, $pass) = split(/\s+/, `/mit/scripts/sql/bin/get-password`);
my $appname = lc $global->{framework}{ApplicationName};

my $dbname = prompt("What database name should this application use", "$appname");
my $db = `/mit/scripts/sql/bin/create-database "$dbname"`;

unless($db) {
    warn "[WARN] Unable to create database $db\n";
    $db = "$ENV{USER}+$dbname";
}

$conf->{framework}{Database}{Driver} = 'mysql';
$conf->{framework}{Database}{Host} = $sqlhost;
$conf->{framework}{Database}{Password} = $pass;
$conf->{framework}{Database}{User} = $user;
$conf->{framework}{Database}{Database} = $db;
$conf->{framework}{Database}{Attributes}{mysql_auto_reconnect} = 1;

my $host;
my $path;
my $uri;
if($conf->{framework}{Web}{BaseURL}) {
    $uri = URI->new($conf->{framework}{Web}{BaseURL});
    $host = $uri->host;
    $path = $uri->path;
} else {
    $host = "$ENV{USER}.scripts.mit.edu";
    $path = "/";
}

$host = prompt("What host will this application run on", "$host");
$path = prompt("What path will this application run under", "$path");

$uri = URI->new("http://$host");
$uri->path($path);

$conf->{framework}{Web}{BaseURL} = $uri->as_string;
$conf->{framework}{Web}{Port} = 80;

print "Configuring etc/site_config.yml...\n";

DumpFile("etc/site_config.yml", $conf);

eval {
write_file("bin/jifty-fastcgi", 0555, <<'END_FASTCGI');
#!/bin/sh
export PERL5LIB=/mit/jifty/perl
exec $(dirname $0)/jifty fastcgi "$@"
END_FASTCGI
};
if($@) {
    warn "[WARN] Unable to write bin/jifty-fastcgi: $!\n";
}

write_file("bin/.htaccess", 0777, <<'END_HTACCESS');
<Files jifty-fastcgi>
  SetHandler fcgid-script
  Options +ExecCGI
</Files>
END_HTACCESS

write_file(".htaccess", 0777, <<'END_HTACCESS');
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/bin/jifty-fastcgi
RewriteRule ^(.*)$ bin/jifty-fastcgi/$1
END_HTACCESS
