#!/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/$name")
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 flup.server.fcgi import WSGIServer
from $name.wsgi import application
WSGIServer(application).run()
EOF
close FASTCGI;
chmod 0755, "index.fcgi";

open HTACCESS, ">.htaccess";
print HTACCESS <<EOF;
RewriteEngine On

RewriteRule ^\$ index.fcgi/ [QSA,L]

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/";

my @djangoadmin = qw{python -m django};
if (system("@djangoadmin version &>/dev/null")) {
  @djangoadmin = ("django-admin");
}

system(@djangoadmin, "startproject", $name)==0 or die "\nFailed to create app.\n\n";
chdir "$name/$name";

open SETTINGS, "settings.py";
open NEWSETTINGS, ">settings.py.new";
my $dbname = 0;
while (<SETTINGS>) {
  chomp;
  if (/Your Name/) {
    $_ = "    ('$USER', '$email'),";
  } elsif (/^DEBUG = /) {
      $_ =~ s/DEBUG/import os\n\nDEBUG/;
  } elsif (/'ENGINE'/) {
    $_ = "        'ENGINE': 'django.db.backends.mysql',";
  } elsif  (/'NAME'/ && !$dbname) {
    $_ = "        'NAME': '$sqldb',";
    print NEWSETTINGS <<EOF;
        'OPTIONS': {
            'read_default_file' : os.path.expanduser('~/.my.cnf'),
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
EOF
    $dbname = 1;
  } elsif (/'PASSWORD'/) {
      next;
  } elsif (/'HOST'/) {
      next;
  } elsif (/Chicago/) {
    $_ =~ s/Chicago/New_York/;
  } elsif (/^ADMIN_MEDIA_PREFIX/) {
    $_ = "ADMIN_MEDIA_PREFIX = '/__scripts/django/static/'";
  } elsif (/^STATIC_URL/) {
    $_ = "STATIC_URL = '/__scripts/django/static/'";
  } elsif (/^INSTALLED_APPS/) {
    $_ .= "\n    'django.contrib.admindocs',";
  } elsif (/^MIDDLEWARE/) {
    print NEWSETTINGS <<EOF;
# Django requires a list of hosts this site is served from; since users can
# add new hosts with Pony at any time, we just trust SERVER_NAME (set by
# Apache) to be the correct hostname. If you want to restrict which virtual
# hosts your application can run on, disable this middleware and set
# ALLOWED_HOSTS by hand.
class AllowedHostsMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response
    def process_request(self, request):
        # Django 1.6
        global ALLOWED_HOSTS
        name = request.META.get('SERVER_NAME')
        if name and name not in ALLOWED_HOSTS:
            ALLOWED_HOSTS.append(name)
    def __call__(self, request):
        # Django 1.11+
        self.process_request(request)
        return self.get_response(request)
EOF
    $_ .= "\n    '$name.settings.AllowedHostsMiddleware',";
  }
  print NEWSETTINGS "$_\n";
}
close NEWSETTINGS;
close SETTINGS;
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";

chdir "..";

print "Initializing your project's SQL database schema...\n";
chmod 0755, "manage.py";
# Django 1.6 has syncdb, Django 1.11 has migrate.
# Run migrate if syncdb returns an error.
if (system qw{./manage.py syncdb --noinput}) {
  system qw{./manage.py migrate --noinput};
}
print "...done\n";

print "Creating your superuser account... ";
system qw{./manage.py createsuperuser --username}, $admin_username, "--email", $email, "--noinput" and die "Failed to create user: $!";
print "done\n";
print "Setting your superuser password... ";
open my $chpasswd, "|-", qw{setsid ./manage.py changepassword}, $admin_username or die "Failed to set password: $!";
print $chpasswd "$admin_password\n";
print $chpasswd "$admin_password\n";
unless (close $chpasswd) {
  # Probably not complicated enough.
  print "Failed to set password. Please enter a new password:\n";
  while (system(qw{./manage.py changepassword}, $admin_username)) {
    # Nothing
  }
}
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 "  https://django-doc-test1.readthedocs.io/en/stable-1.6.x/howto/deployment/fastcgi.html\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 "  https://django-doc-test1.readthedocs.io/en/stable-1.6.x/intro/tutorial01.html#creating-models\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;
