#!/usr/bin/env ruby
 
require "mysql"
require 'date'
 
host = "127.0.0.1"
user = "username"
pass = "password"
daba = "databasename"
 
# Database connection object
$my = Mysql::new(host, user, pass, daba)
 
# Verify email address isn't already being used
def check_email(email)
	res = $my.query("SELECT `email` FROM invites WHERE `email` = '" + email + "'")
 
	if res.num_rows == 0
		puts "E-mail: [OK]"
	else
		puts "E-mail: [IN USE]"
		exit
	end
end
 
# Check if we haven't generated a duplicate key
def check_key(key)
	res = $my.query("SELECT `key` FROM invites WHERE `key` = '" + key + "'")
 
	if res.num_rows == 0
		puts "Key:    [OK]"
		return true
	else
		return false
	end
end
 
# Generate random key
def gen_key()
	o =  [('a'..'z'),('0'..'9')].map{|i| i.to_a}.flatten
	return  (0..63).map{ o[rand(o.length)]  }.join
end
 
# Create new database record for invite and update user last generated record
def sql_new_key(email, key)
	$my.query("INSERT INTO invites (`email`, `key`, `parent`) VALUES ('" + email + "','" + key + "','" + $user + "')")
	$my.query("UPDATE invites SET `last` = '" + Date.today.to_s + "' WHERE `username` = '" + $user + "'")
end
 
# Check if user is allowed to generate invites
def sql_get_allowed(name)
	res = $my.query("SELECT * FROM invites WHERE `username` = '" + name + "'")
 
	if !(res.num_rows == 0)
		res.each do |row|
			strikes = row[5]
			last = row[6]
			privs =  row[7]
 
			# Users with privs 1 are always allowed to generate invites
			if privs.to_i == 1
				return true
			else
				daysago = (Date.today - Date.parse(last)).to_i
				waittime = 30 * (strikes.to_i + 1)
 
				if daysago > waittime
					return true
				else
					# Recently generated an invite
					puts "Sending invite not allowed yet!"
					puts "Wait #{(waittime - daysago)} days before generating an invite."
					exit
				end
			end
		end
	else
		# User not in database
		puts "You are not allowed to generate invites."
		exit
	end
end
 
# Check arguments
if !(ARGV.size == 2)
	puts "Usage: " + $0 + " currentuser new_user@email.com"
	exit
else
	$user = ARGV[0]
	$mail = ARGV[1]
	check_email $mail
end
 
# Generate the key
good_key = false
while !good_key
	$key = gen_key
	good_key = check_key $key
end
 
# Check permissions
sql_get_allowed $user
 
# Insert new key
sql_new_key $mail, $key
 
# Send noticfication email
puts "Sending invite key #{$key} to #{$mail}"
puts "Note: The invite mail is likely to end up in the spam folder."
 
mailcmd = "mailer \"smtp.ziggozakelijk.nl\" \"#{$user}@insomnia247.nl\" \"#{$mail}\" \"#{$user} sent you have a shell invite\" \"Your invite code is #{$key}\nGo to http://www.insomnia247.nl/page/shells/index to request your shell.\""
mailcmd.untaint
system mailcmd