#!/bin/bash
#########################################################
# 							#
# This is BashStyle-NG					#
#							#
# Licensed under GNU GENERAL PUBLIC LICENSE v3    	#
#							#
# Copyright 2007 - 2017 Christopher Bratusek		#
#							#
#########################################################

_randomfunc() {

	command=""

	if [ $# -lt 2 ] || [[ ! "$*" =~ [[:space:]]--[[:space:]] ]];then
			echo "Invalid syntax." >&2; exit 1
	fi

	until [[ ${1} =~ -- ]]; do
		command="$command$1"; shift
	done
	shift

	if [[ ! "${*}" ]]; then
		files=(*)
	else	files=("${@}")
	fi

	n=${#files[@]}
	RANDOMFILE="${files[RANDOM % n]}"

	if [[ "${command}" == "+" ]]; then
		echo "${RANDOMFILE}" >> /tmp/randomtmp
	else
		${command} "${RANDOMFILE}"
		echo "${RANDOMFILE}" >> "${HOME}/.randomhistory"
	fi

}

case ${1} in

	--help | -h | "")
		bashstyle-help -a "Christopher Roy Bratusek" -e "nano@jpberlin.de" -h "http://www.nanolx.org/"\
				-l "GNU GPL v3" -n "randomfile" -s "run a command on a random file" -v "${BSNG_VERSION}" -y "${BSNG_YEAR}"\
				-o "command:|command to run for file"\
				-o "--:|end of command"\
				-o "files:|list of possible files"\
				-o "\tor:|--"\
				-o "-f:|print first entry of random history"\
				-o "-L:|print last entry of random history"\
				-o "-i:decimal|print nth entry of random history"\
				-o "-l:|print number of entries in random history"\
				-o "-c:|clear random history"\
				-o "\tor:|--"\
				-o "-n:decimal|repeat process n times"\
				-o "--:|delimiter"\
				-o "files:|for given files and print result"
	;;


	-f | --first)
		sed -n '1p' "${HOME}"/.randomhistory
	;;

	-L | --last)
		sed -n '$p' "${HOME}"/.randomhistory
	;;

	-i | --item)
		sed -n "${2}p" "${HOME}"/.randomhistory
	;;

	-l | --length)
		wc -l "${HOME}"/.randomhistory | gawk '{print $1}'
	;;

	-c | --clear)
		rm "${HOME}"/.randomhistory
	;;

	-n | --count)
		shift
		count=$1
		shift

		while test "${count}" -gt 0; do
			_randomfunc + -- "${@}"
			count=$((count-1))
		done

		sort /tmp/randomtmp | uniq -c | sort -n | tail | sort -nr
		rm /tmp/randomtmp
	;;

	*)
		_randomfunc "${@}"
	;;

esac
