#!/usr/bin/ruby
# vim:ts=4:autoindent

require 'Log'
require 'DeeDial'
#require 'Bot'
#require 'WheelOfWords'

#require 'optparse'
require 'yaml'

#
# Start Bot
#
# The YAML config files must know:
#
# The HOST and PORT on which a virtual Applecat modem is listening
# The PASSCODE by which I will be automagically remoted.
# The HANDLE by which I will be known to the ddial.
# If I want to connect to the huntgroup software, DO_ADMIN = true
#

here = binding
begin
    if ARGV[0].nil?
        puts "Usage: #{$0} CONTEXT"
        puts "  where CONTEXT is the environment context (eg, 'Production', 'Test9001')"
        exit
    end

    globals = YAML.load(File.open("bot-globals.yaml"))          # Universal settings
    environ = YAML.load(File.open("bot-#{ARGV[0]}.yaml"))       # Environment context (production, test)

    [ :host, :port, :passcode, :handle, :do_admin ].each do |key|
        k = key.to_s
        eval("#{k} = !environ[:#{k}].nil? ? environ[:#{k}] : globals[:#{k}]", here)
        raise "cannot continue - no config for #{k}" if eval("#{k}.nil?", here)
    end
    host, port, passcode, handle, do_admin = host, port, passcode, handle, do_admin
    ACCT = passcode[/^(\d+) /].to_i

    load_services = [
        "Email",
        "WhosOn",
        "Notify",
        "Special",
        "WheelOfWords"
    ]
    opts = { :load_services => load_services }

    dd = DeeDial.new( host, port, passcode, do_admin, opts )
    dd.on_raw_event( :type => :loginout, :acct => ACCT, :oneshot => true ) do |ev|
        dd.write("/h#{handle}\r")
    end

    dd.start
end