require 'pstore'
require 'singleton'
require 'monitor'

class Login
  include Singleton
  include MonitorMixin

  @@filename = 'login.db'

  def self.filename=(fname)
    @@filename = fname
  end

  def initialize
    super
    @pstore = PStore.new(@@filename)
  end
  
  def login(user, passwd)
    synchronize do
      @pstore.transaction do |db|
	if db.root?(user)
	  raise('login failed') unless db[user] == passwd
	else
	  db[user] = passwd
	  db.commit
	end
      end
      return true
    end
  end

  def setpw(user, oldpw, newpw)
    synchronize do
      @pstore.transaction do |db|
	if db.root?(user) && db[user] == oldpw
	  db[user] = newpw
	  db.commit
	  return true
	else
	  raise('login failed') unless db[user] == passwd
	end
      end
      false
    end
  end

  def list
    synchronize do
      @pstore.transaction do |db|
	db.roots
      end
    end
  end
end
    
if __FILE__ == $0
  require 'drb/drb'

  front = Login.instance
  DRb.start_service(ARGV.shift || 'druby://localhost:7982', front)
  puts DRb.uri
  gets
end
