#!/usr/bin/env ruby
require 'webrick'
require 'drb'
require 'yaml'

# A quick hack for giving you control of the SCGI server based on
# code from Gnome's guide.  It basically provides a set of URIs you 
# can hit to control the SCGI server.  It uses the DRb API to do all
# of this.
#
# /stop -- stops it.  give force=true to force it.
# /restart -- restarts.  again, give force=true.
# /status -- dump YAML status.
# /reconfigure -- Reloads the configuration for things like maxconns and soft configurables.
#
# All URIs need a password=<password> given to them so they can properly control
# the scgi_service.  And yes, this is not secure so you're screwed if you put this
# on the internet bare.  You've been warned.

include WEBrick    

def start_webrick(config = {})
  # always listen on port 8080
  config.update(:Port => 8080)     
  server = HTTPServer.new(config)
  yield server if block_given?
  ['INT', 'TERM'].each {|signal| 
    trap(signal) {server.shutdown}
  }
  server.start
end

def require_password(req, resp)
    if not req.query['password']
        resp.body = "ERROR: No password."
    else
        yield req.query['password'].to_s
    end
end

config = YAML.load_file("config/scgi.yaml")

start_webrick(:DocumentRoot => '/var/www') do |s|
    s.mount_proc("/status") {|req,resp|
        require_password(req,resp) do |pass|
            c = DRbObject.new(nil, config[:control_url])
            status = c.status(pass).to_yaml
            resp.body = "<pre>" + status + "</pre>"
        end
    }
    
    s.mount_proc("/reconfig") {|req,resp|
        require_password(req,resp) do |pass|
            c = DRbObject.new(nil, config[:control_url])
            c.reconfigure(pass)
            resp.body = "OK"
        end
    }
    
    s.mount_proc("/stop") {|req,resp|
        require_password(req, resp) do |pass|
            c = DRbObject.new(nil, config[:control_url])
            if req.query["force"]
                c.shutdown(pass, true)
            else
                c.shutdown(pass, false)
            end
            resp.body = "OK"
        end
    }
    
    s.mount_proc("/restart") {|req,resp|
        require_password(req, resp) do |pass|
            c = DRbObject.new(nil, config[:control_url])
            if req.query["force"]
                c.restart(pass, true)
            else
                c.restart(pass, false)
            end

            resp.body = "OK"
        end
    }
end


