#!/usr/bin/ruby -w

#=======================================================================
# eda.rb - codificar datos de forma segura. Utiliza la gema ezcrypto
#-----------------------------------------------------------------------
# A partir de la receta 12.6 del libro ruby cookbook
#-----------------------------------------------------------------------
# FJA - neocipres@gmail.com			Septiembre de 2008
#=======================================================================


require 'rubygems'
require 'ezcrypto'

begin
 textoE = ''
 textoS = ''
 aezc = ''
 clave = ''
 archivo, metodo, clave  = ARGV
 raise if ARGV.size < 2
 m = metodo[0].chr
 tipo = archivo.include?('.ezc')
 raise if !tipo && m == 'd'
 clave = 'ultravioleta' if !clave
 open(archivo) do |f|
	textoE = f.read
 end
 ezcrypto_key = EzCrypto::Key.with_password clave, 'salt string'  # 'system salt' 'salt string'
 case m
 	when 'e'
		textoS = ezcrypto_key.encrypt(textoE)
	when 'd'
		textoS = ezcrypto_key.decrypt(textoE)
 end
 aezc << archivo << '.ezc' if m == 'e'
 aezc << archivo.sub('.ezc','') if m == 'd'
 open(aezc, 'w') do |f|
	f << textoS # o bien, f.write(textoS)
 end
rescue
 if ARGV.size < 2
 	print "\n\t", "="*65
  	print "\n\t Uso: eda <archivo> <e|d> [clave] \n"
	print "\n\t\t e -> encripta el fichero\n "
        print "\n\t\t d -> desencripta el fichero\n "
	print "\n\t\t eda es un enlace simbólico a cb21.rb \n "
	print "\t", "="*65, "\n\n"
 elsif !tipo
 	print "\n\t el archivo debe ser del tipo .ezc  #{$!} \n\n"
 else
  print "\n\t Error-> #{$!} \n\n"
 end
 
end