# TODO: Add comment
# 
# Author: E.Korsching  2021
###############################################################################


# For the  cron.d  version

# R random package
# real random numbers  -  in contrast to deterministic (pseudo) random numbers (generated based on computer programs and hardware features) 
# this package uses a service on https://www.random.org/
# to generate random data by atmospheric noise via a radio-receiver tuned to a low frequency (mixed sources over several receiver on several continents)
# quota: 1 Mio. bits per day, 10K per fetch, and a penalty if exceeding the quota (starting by 200k next day and after 5 days back to full quota) 

# Usually short integer is 16 bits, long integer is 32 bit - between -2^31 and 2^31 - 1
# 1 Mio. bit app. 33300  integer32 numbers (day quota, if no penalty for exceeding the quota)
# 100 integers out of range 1:39306  uses  2848 bits  app. 29 bits per number -- so slightly less than 32

# see help

rnd.fetch <- function(z=NULL, range=c(1,10)){
	# fetch random numbers random package (1 Mio. bits per day)
	# z: fetch a certain amount of integer random numbers
	# range: for random numbers: integer: c(lower,upper)
	require("random", lib.loc="/home/korschi/R/x86_64-pc-linux-gnu-library/4.0")
	# get quota
	q1 <- 32		# integer
	q2 <- 10000		# 10K limit for one fetch
	rq <- randomQuota()
	if(rq<=0){ cat("\n random quota exhausted"); return() }
	if(is.null(z)){
		con1 <- floor(rq/q1)		# bit in integer
		con2 <- con1/q2				# limit for one fetch
		con2 <- floor(con2)
		con3 <- con1%%q2			# rest
		if(con2==0 & con1>0){
			rnd <- randomNumbers(n=con1, min=range[1], max=range[2], col=1, base=10, check=T)
		}
		if(con2>0 & con1>0){
			rnd <- NULL
			for(i in 1:con2){
				rnd <- c(rnd, randomNumbers(n=q2, min=range[1], max=range[2], col=1, base=10, check=T) )
			}
			if(con3>0){ rnd <- c(rnd, randomNumbers(n=con3, min=range[1], max=range[2], col=1, base=10, check=T) ) }
		}
	}else{
		con1 <- floor(rq/q1)		# bit in integer
		if(z>con1){ cat("\n not so many random integers available - only ",con1); return() }
		con2 <- z/q2				# limit for one fetch 10/10000 10%%10000
		con2 <- floor(con2)
		con3 <- z%%q2				# rest
		if(con2==0 & con1>0){
			rnd <- randomNumbers(n=z, min=range[1], max=range[2], col=1, base=10, check=T)
		}
		if(con2>0 & con1>0){
			rnd <- NULL
			for(i in 1:con2){
				rnd <- c(rnd, randomNumbers(n=q2, min=range[1], max=range[2], col=1, base=10, check=T) )
			}
			if(con3>0){ rnd <- c(rnd, randomNumbers(n=con3, min=range[1], max=range[2], col=1, base=10, check=T) ) }
		}
	}
	return(rnd)
}

# start processing

# get calling parameters of bash script  rnd_fetch.sh  which is called from  cron.d/korschi
args <- commandArgs()
#print(args)

# fetch the relevant argument(s)
pathfile <- args[6]

# fetch random numbers
rnd <- rnd.fetch(z=NULL, range=c(1,39306))

write.table(rnd, file=paste(pathfile, sep=""), quote=F, sep="\t", row.names=F, col.names=F)

# end processing

