#  Créé par AppleStorm { Hwc-crew (http://www.orgasm.re)
#  le 26 - 09 - 2012
#  Gestion de ban plage ip pour serveur nginx

#!/usr/bin/env ruby
# CONSTANTES PARAMETRABLES 
@line = 0
@fichier = "/etc/nginx/banips.conf" # Votre fichier de listing banip
@exe = "/etc/init.d/nginx restart"
# ------------------------- #

# FONCTIONS Personalisables #
def outputUsage()
	puts "============== BanIps :: You Fail bitch ! =============="
	puts " usage : <dir>/<script> [command]   [ip]"
	puts " Commandes :"
	puts "		add [ip]	:	Ajoute le deny à [ip]"
	puts "		del [ip]	:	Delette le ban à [ip]"
	puts "		view		:	Afficher les ips ban."
	puts "		view [ip]	: 	Retourne Oui ou Non. "
	puts ""
	puts " example :"
	puts "		<dir>/<script> add 192.168.0.0"
	puts "		<dir>/<script> del 192.168.0.0"
	puts "========================================================"
end
def find_ip(masque)
	tableau = File.open(@fichier, "r")
	i = 1
	a = false
	tableau.each_line { |ligne|
		if not ligne.match( masque ).nil?
			puts "Trouvé : #{i} - #{ligne}"
			@line = i-1
			a = true
			i += 1
		else
			i += 1
		end
	}
	if a != true
		puts "---- #{masque} non trouvé -----"
	end	
end
def delete_ip(line)
	line_arr = File.readlines(@fichier)
	line_arr.each do |index|
		line_arr.delete_at(line)
	end
	File.open(@fichier, "w") do |f|
		line_arr.each{ |ligne| f.puts(ligne) }
	end
end
if not ARGV[0].nil?
	if not ARGV[1].nil?
		# Commandes
		ip = ARGV[1].split('.')
		masque = ip[0]+'.'+ip[1]
		pip = "deny "+ip[0]+'.'+ip[1]+'.0.0/24;'
		case ARGV[0]
			when "add"
				#lignedecode
				puts "======================================================="
				puts "BanIps : Vous avez ajouté un ban : " + pip
				puts "======================================================="
				fichier = File.open(@fichier, "a+")
				fichier.write pip+"\n"
				fichier.close
				exec(@exe)
			when "del"
				#lignedelete
				find_ip(pip)
				delete_ip(@line)
				exec(@exe)
			when "view"
				#ligneview
				puts "Vous souhaitez voir le ban : " + pip
				find_ip(pip)
			else
				outputUsage()
		end
	else
		if ARGV[0] == "view"
			file = File.open(@fichier, "r")
			i = 1
			file.each_line { |ligne|
				puts "#{i} - #{ligne}"
				i += 1
			}
			file.close
		end
	end
else
	outputUsage()
end