#!/usr/bin/env ruby

%w(rubygems model/database model/flags highline/import).each { |lib| require lib}

def print_usage
  puts <<-END
--------------------------------------------------
admin-script for the pruefungssekretariat-service
da-op3n 2008 -- ilo
--------------------------------------------------
usage: admin.rb add      student|professor $name
       admin.rb remove   student|professor $id
       admin.rb list all students|professors|flags
--------------------------------------------------
END
  exit 1
end

def get_password
  begin
    pw1 = ask("password: ") { |q| q.echo = false}
    pw1.chomp!
    pw2 = ask("re-type password: ") { |q| q.echo = false}
    pw2.chomp!
  end until pw1 == pw2
  pw1
end

def add(x)

  begin
    
    if x[:student]
      s = Students.create(:name => x[:student], :password => get_password)
      puts "added student #{s.name} with ID #{s.id}."
    elsif x[:professor]
      p = Professors.create(:name => x[:professor], :password => get_password)
      puts "added professor #{p.name} with ID #{p.id}."
    else
      raise "no type (student|professor) given!"
    end
    
  rescue
    $stderr.puts $!
    # print_usage
    exit 1
  end

end

def remove(x)
  begin
    
    if x[:student]
      s = Students[x[:student]]
      raise "no such student: #{x[:student]}" unless s
      s.delete
      puts "sucessfully removed student \#%s" % x[:student]
    elsif x[:professor]
      p = Professors[x[:professor]]
      raise "no such professor: #{x[:professor]}" unless p
      p.delete
      puts "sucessfully removed professor \#%s" % x[:professor]
    else
      raise "no type (student|professor) given!"
    end
    
  rescue
    $stderr.puts $!
    # print_usage
    exit 1
  end
end

def list(x)
  begin

    case x[:all]
      when 'students'
        Students.to_hash(:id, :name).each { |id, name| puts "{%s,%s}" % [id, name]}
      when 'professors'
        Professors.to_hash(:id, :name).each { |id, name| puts "{%s,%s}" % [id, name]}
      when 'flags'
        Flags.each { |id, flag| puts "{%s,%s}" % [id, flag] }
      else
        raise "no type (students|professors|flags) given!"
    end

  rescue 
    $stderr.puts $!
    # print_usage
    exit 1
  end
end

if __FILE__ == $0

  functions = {
  	'add' => Kernel.method(:add),
  	'remove' => Kernel.method(:remove),
  	'list' => Kernel.method(:list) }

  function, type, name = *ARGV

  print_usage unless ARGV.length == 3 and functions[function]

  functions[function].call(type.intern => name)

end