#!/usr/bin/perl
#
# ---------------------------[ MIT-LICENSE ]-------------------------------
# 
#    Copyright (c) 2006, Warren Konkel
# 
#    Permission is hereby granted, free of charge, to any person obtaining
#    a copy of this software and associated documentation files (the
#    "Software"), to deal in the Software without restriction, including
#    without limitation the rights to use, copy, modify, merge, publish,
#    distribute, sublicense, and/or sell copies of the Software, and to
#    permit persons to whom the Software is furnished to do so, subject to
#    the following conditions:
# 
#    The above copyright notice and this permission notice shall be
#    included in all copies or substantial portions of the Software.
# 
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
#    LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
#    OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
#    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
#
# -----------------------------[ README ]---------------------------------
#
#    This is a perl script designed to be executed on a freshly installed
#    debian 4.0 server with nothing checked but "Standard install".  It
#    asks a few quick questions and then sets up a whole bunch of packages.
#    The end result is a nicely configured debian box.
#
#                       USE AT YOUR OWN RISK!!!!

sub run {
  $command = $_[0];
  print("---[".$command . "]---\n");
  system($command);
}

# this does some crazy ruby hacking so it gets the ruby-only versions of the platform
sub install_gem {
  $gem_name = $_[0];
  
  $ruby = "
    require 'rubygems'
    Gem.manage_gems

    Gem::RemoteInstaller.class_eval do
      alias_method :find_gem_to_install_without_ruby_only_platform, :find_gem_to_install
      def find_gem_to_install(gem_name, version_requirement, caches)
        caches.each { |k,v| caches[k].each { |name, spec| caches[k].remove_spec(name) unless spec.platform == 'ruby' } }
        find_gem_to_install_without_ruby_only_platform(gem_name, version_requirement, caches)
      end
    end

    Gem::GemRunner.new.run(['install', '$gem_name', '--include-dependencies', '--no-rdoc', '--no-ri'])
  ";
  print("---[installing gem: $gem_name]---\n");
  system("ruby -e \"$ruby\"");
}

sub yes_or_no {
  $display = $_[0];
  do {
    print $display . " (y,n) [Y]? ";
  } while (($doit=<STDIN>) && chomp($doit) && !($doit =~ m/^(y|n|)$/));

  return ($doit =~ m/^(y|)$/);
}

sub get_val {
  $display = $_[0];
  $default = $_[1];
  
  if ($default) {
    print "$display [$default]: ";
    $doit=<STDIN>;
    chomp($doit);
    return length($doit) ? $doit : $default;
  } else {
    do {
      print "$display: ";
    } while (($doit=<STDIN>) && chomp($doit) && !length($doit));
    return $doit;
  }
}

$hostname = get_val("Enter full hostname (example: server1.yourdomain.com)");
$ruby_stuff = yes_or_no("Install ruby, rails, gem, etc");
$mysql_server = yes_or_no("Install mysql server");
$apache_server = yes_or_no("Install apache");
$mongrel_server = $ruby_stuff && yes_or_no("Install mongrel/mongrel_cluster");
$reboot_at_end = yes_or_no("Reboot when done");

print("\n\nUpdating dist and setting up crontab to auto-update packages...\n");
run("dpkg --configure -a");
run("apt-get update");
run("apt-get dist-upgrade -y");
if (!`crontab -l | grep "apt-get upgrade -y"`) {
  run("(crontab -l; echo \"0 0 * * * apt-get update > /dev/null; apt-get upgrade -y > /dev/null\") | crontab -");
}

print("\n\nInstalling sshd just in case it's not already there...\n");
run("apt-get install -y openssh-server");

print("\n\nInstalling some base packages...\n");
run("apt-get install -y build-essential dnsutils traceroute unzip rsync links-ssl subversion subversion-tools mysql-client libmysqlclient15-dev");

print("\n\nSetting up hostname ($hostname)...\n");
run('rm /etc/hosts.tmp > /dev/null');
run('mv /etc/hosts /etc/hosts.tmp');
run("echo \"127.0.0.1\t\t\t$hostname localhost\" > /etc/hosts");
run("cat /etc/hosts.tmp | grep -v '127\.0\.' >> /etc/hosts");
run("rm /etc/hosts.tmp");
run("echo \"$hostname\" > /etc/hostname");
run("hostname $hostname");

print("\n\nInstalling exim for sendmail...\n");
run("apt-get install -y exim4-daemon-light");
run("cp /etc/exim4/update-exim4.conf.conf /etc/exim4/update-exim4.conf.conf.tmp");
run("cat /etc/exim4/update-exim4.conf.conf.tmp | sed -e \"s/dc_minimaldns='false'/dc_minimaldns='true'/g\" | sed -e \"s/dc_eximconfig_configtype='local'/dc_eximconfig_configtype='internet'/g\" > /etc/exim4/update-exim4.conf.conf");
run("rm /etc/exim4/update-exim4.conf.conf.tmp");
run("update-exim4.conf");


if (!(-e "/root/.ssh/id_rsa")) {
  print("\n\nGenerating local SSH key...\n");
  run("ssh-keygen -N '' -t rsa -f /root/.ssh/id_rsa");
}


print("\n\nSetting timezone to UTC and adding crontab for auto time sync...\n");
run("apt-get install -y ntpdate");
run("echo 'UTC' > /etc/timezone");
run("rm /etc/localtime");
run("ln -s /usr/share/zoneinfo/UTC /etc/localtime");
run("ntpdate pool.ntp.org");
run("hwclock --systohc --utc");
if (!`crontab -l | grep "ntpdate pool.ntp.org"`) {
  run("(crontab -l; echo \"0 * * * *    /usr/sbin/ntpdate pool.ntp.org; /sbin/hwclock --systohc --utc\") | crontab -");
}

if ($ruby_stuff) {
  print("\n\nInstalling ruby, rails, gem, etc...\n");
  run("apt-get install -y ruby1.8 ruby1.8-dev rubygems imagemagick pkg-config libredcloth-ruby1.8 librmagick-ruby1.8 libopenssl-ruby1.8 irb libsvn-ruby");

  install_gem("rails");
  install_gem("gem_plugin");
  install_gem("meta_project");
  install_gem("json");
}

if ($mysql_server) {
  print("\n\nInstalling mysql server...\n");
  run("apt-get install -y mysql-server");
}

if ($apache_server) {
  print("\n\nInstalling apache...\n");
  run("apt-get install -y apache2 libapache2-mod-proxy-html");
  run("a2enmod rewrite");
  run("a2enmod proxy_balancer");
  run("/etc/init.d/apache2 force-reload");
}

if ($mongrel_server) {
  print("\n\nInstalling mongrel and mongrel_cluster...\n");
  install_gem("mongrel");
  install_gem("mongrel_cluster");
  install_gem("daemons");

  if (!(-e "/etc/init.d/mongrel_cluster")) {
    run("ln -s /var/lib/gems/1.8/gems/mongrel_cluster-0.2.1/resources/mongrel_cluster /etc/init.d/mongrel_cluster");
    run("chmod +x /etc/init.d/mongrel_cluster");
    run("/usr/sbin/update-rc.d mongrel_cluster defaults");
  }
  
  if (!(-e "/etc/mongrel_cluster")) {
    run("mkdir /etc/mongrel_cluster");
  }
}

print("\n\nCleaning up .deb packages...\n");
run("rm /var/cache/apt/archives/*.deb 2> /dev/null");

print("\n\nUpdating locatedb for 'find'...\n");
run("updatedb");

if ($reboot_at_end) {
  print("\n\nAll done! Rebooting...\n");
  run("shutdown -r now");
} else {
  print("\n\nAll done!\n\n");
}

