#
#   Copyright (C) Stonesoft Corporation 2010 - 2011.
#   All rights reserved.
#
#   The StoneGate software, manuals, and technical
#   literature may not be reproduced in any form or
#   by any means except by permission in writing from
#   Stonesoft Corporation.
#

Thread.abort_on_exception = true
$root = File.expand_path( File.dirname( __FILE__ ) )

require "pty"
require "timeout"
require 'rbconfig'
require 'socket'
require 'rubygems'
#require 'sinatra'
#require 'sinatra/base'

require "#{$root}/lib/util.rb"

def print_usage()
  puts "Generic restarter daemon"
  puts "Usage: ruby restarter.rb <options>"
  puts ""
  puts "Options:"
  puts "\t--port=<port> \t\t Server port."
  puts "\t--command=<path> \t\t Command to run."
  puts "\t--title=<path> \t\t Web server title."
end

def kill()
  log "requested kill"
  Process.kill("SIGKILL", $program.pid)
end

if ARGV.empty?
  print_usage()
  exit()
end

$server_port = nil
$command = nil
$title = nil
$program = nil

ARGV.each do |arg|
  if arg =~ /^--port=(\d+)/
    $server_port = $1.to_i()
  elsif arg =~ /^--command=(.*)/
    $command = $1
  elsif arg =~ /^--title=(.*)/
    $title = $1
  else
    puts "* Unrecognized option \"#{arg}\""
    print_usage()
    exit()
  end
end

ARGV.clear()
require 'sinatra'
require 'sinatra/base'

if $server_port.nil?
  puts "* Server port missing, use --port"
  exit()
elsif $server_port < 0 or $server_port > 0xffff
  puts "* Invalid server port #{$server_port}, expecting a number between 0 and 65535"
  exit()
end

if $command.nil?
  puts "* Command missing, use --command"
  exit()
end

if $title.nil?
  puts "* Title missing, use --title"
  exit()
end

# Done parsing input
$log_file = File.new( "restarter.log", "w" )


class HTTPRestarterHandler < Sinatra::Base
  #set :logging, true
  set :logging, false
  set :sessions, true
  set :public, "#{$root}/webgui/public"
  set :environment, :production
  set :server, %w[ thin webrick ]

  get '/' do
    redirect '/index.html'
  end

  get '/index.html' do
    if not params[ "restart" ].nil?
      # Restart!
      begin
        kill()
      rescue Exception => e
        puts "Restart exception #{e}!"
      end

      redirect '/index.html'
    end

    arr = []
    arr.push "<html>"
    arr.push "<head>"
    arr.push "<title> #{$title} </title>"
    arr.push "<link href='css/predator4.css' rel='stylesheet' type='text/css'/>"
    arr.push "</head>"
    arr.push "<body>"
    arr.push "<table valign='top' align='center'>"
    arr.push "<tr><td class='main'> <p class='header'> #{$title} </p> </tr></td>"
    arr.push "<tr><td class='main'> </br> </tr></td>"
    arr.push "<tr><td class='main'> <p class='header'> <a href=\"index.html?restart=true\"> Restart </a></p> <br/> </tr></td>"
    arr.push "</table>"
    arr.push "</body></html>"

    return arr.join( "\r\n" )
  end
end

puts "Running command \"#{$command}\""

Thread.new do
  while(true)
    begin
      $program = ATFExpect.new( $command )
      sleep 1
      $program.time_out = 1
      while true
        begin
          log_nlf $program.expect(/./)
          $stdout.flush
        rescue TimeoutError
        end
      end
    rescue Exception => e
      log "#{$command} has ended: #{e} .. restarting"
      sleep 1
      #log e.backtrace.join("\n")
    end
  end
end

HTTPRestarterHandler.run! :host => 'localhost', :port => $server_port


log( "Shutdown at #{Time.new()}")

$log_file.close()
