#!/usr/bin/ruby

require 'dbi'
require 'digest/sha1'
require 'yaml'
require 'socket'
require 'timeout'

yml = YAML.load_file('/home/genkidama/genkidama_stats/config.yml')

dbh = DBI.connect("DBI:Mysql:#{yml['db_name']}:#{yml['db_host']}", yml['db_user'], yml['db_pass'])
sth = dbh.execute('SELECT address, port, version FROM online_users')
sth.fetch do |row|
  begin
    timeout(yml['connection_timeout']) do
      s = TCPSocket.open(row[0], row[1])
      s.close
    end
    true
  rescue TimeoutError, SystemCallError => e
    print e
    dbh.do('DELETE FROM online_users WHERE address = ? AND port = ?',
           row[0], row[1])
    dbh.do("INSERT INTO user_log (datetime, hash, version, status) VALUES (NOW(), ?, ?, 'purge')",
           Digest::SHA1.hexdigest("#{row[0]}:#{row[1]}"), row[2])
    dbh.do('DELETE FROM online_data WHERE `hash` = ?',
           Digest::SHA1.hexdigest("#{row[0]}:#{row[1]}"))
    dbh.do("INSERT INTO data_log (`datetime`, `hash`, `version`, `key`, `status`) VALUES (NOW(), ?, ?, 'all', 'purge')",
           Digest::SHA1.hexdigest("#{row[0]}:#{row[1]}"), row[2])
    print "#{row[0]}:#{row[1]} deleted"
  end
end
dbh.disconnect
