#!/usr/bin/perl
use strict;
use FindBin qw($Bin);
use lib $Bin;
use onserver;

setup();

print "\nEnter the code name for your project (a valid Python package name).\n";
print "Do not use 'django' or the name of any other Python library.\n";
print "Project name: ";
my $name = <STDIN>;
chomp $name;

open FASTCGI, ">index.fcgi";
print FASTCGI <<EOF;
#!/usr/bin/env python
import sys, os, time, threading, django.utils.autoreload
sys.path.insert(0, "/mit/$USER/Scripts/django")
os.chdir("/mit/$USER/Scripts/django/$name")
os.environ['DJANGO_SETTINGS_MODULE'] = "$name.settings"

def reloader_thread():
  while True:
    if django.utils.autoreload.code_changed():
      os._exit(3)
    time.sleep(1)
t = threading.Thread(target=reloader_thread)
t.daemon = True
t.start()

from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
EOF
close FASTCGI;
chmod 0755, "index.fcgi";

open HTACCESS, ">.htaccess";
print HTACCESS <<EOF;
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\$ index.fcgi/\$1 [QSA,L]
EOF
close HTACCESS;
chmod 0777, ".htaccess";

chdir "/mit/$USER/Scripts/django/";
system qw{django-admin startproject}, $name;
chdir "$name";

open SETTINGS, "settings.py";
open NEWSETTINGS, ">settings.py.new";
while (<SETTINGS>) {
  chomp;
  if (/Your Name/) {
    $_ = "    ('$USER', '$email'),";
  } elsif (/'ENGINE'/) {
    $_ = "        'ENGINE': 'django.db.backends.mysql',";
  } elsif  (/'NAME'/) {
    $_ = "        'NAME': '$sqldb',";
  } elsif (/'USER'/) {
    $_ = "        'USER': '$sqluser',";
  } elsif (/'PASSWORD'/) {
    $_ = "        'PASSWORD': '$sqlpass',";
  } elsif (/'HOST'/) {
    $_ = "        'HOST': '$sqlhost',";
  } elsif (/Chicago/) {
    $_ =~ s/Chicago/New_York/;
  } elsif (/^ADMIN_MEDIA_PREFIX/) {
    $_ = "ADMIN_MEDIA_PREFIX = '/__scripts/django/media/'";
  } elsif (/^INSTALLED_APPS/) {
    print NEWSETTINGS "$_\n";
    while (<SETTINGS>) {
      if (/^\)/) {
        print NEWSETTINGS "    'django.contrib.admin',\n";
        print NEWSETTINGS "    'django.contrib.admindocs',\n";
      }
      print NEWSETTINGS $_;
    }
  }
  print NEWSETTINGS "$_\n";
}
close NEWSETTINGS;
close SETTNGS;
rename "settings.py.new", "settings.py";

open URLS, "urls.py";
open NEWURLS, ">urls.py.new";
while (<URLS>) {
  chomp;
  if (/^#.*from django\.contrib import admin/) {
    $_ =~ s/^# *//;
  } elsif (/^#.*admin.autodiscover/) {
    $_ =~ s/^# *//;
  } elsif (/^ *# *\(r\'\^admin\//) {
    $_ =~ s/# *//;
  }
  print NEWURLS "$_\n";
}
close NEWURLS;
close URLS;
rename "urls.py.new", "urls.py";

print "Initializing your project's SQL database schema...\n";
system qw{./manage.py syncdb --noinput};
print "...done\n";

print "Creating your superuser account... ";
system qw{./manage.py createsuperuser --username}, $admin_username, "--email", $email, "--noinput";
print "done\n";
print "Setting your superuser password... ";
system qw{mysql -D}, "$USER+$addrlast", "-e", "UPDATE auth_user SET password=MD5(\'$admin_password\') WHERE username=\'$admin_username\'";
print "done\n";

print "\nDjango has been installed. The setup is roughly what's described\n";
print "in the shared-hosting section of\n";
print "  http://docs.djangoproject.com/en/dev/howto/deployment/fastcgi/\n";
print "We've also enabled the admin app. You can start from the 'Creating\n";
print "models' step of the Django tutorial:\n";
print "  http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3\n\n";
print "Your project is located in:\n";
print "  /mit/$USER/Scripts/django/$name/\n";
print "To access manage.py, run 'ssh -k $USER\@scripts' and cd to the above directory.\n\n";
press_enter;

exit 0;
