#!/bin/bash
# reportlog: Build reports from scankeylx log file.
# Copyright (C) [2005/9]-[2015/6], Akinori Furuta (afuruta@m7.dion.ne.jp).
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer
#    in the documentation and/or other materials provided with
#    the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
# THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES  (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

do_parallel=0
temp_1st=""
temp_2nd=""
temp_3rd=""

current_dir=`pwd`

how_run_me=(`history 2 | tail -1`)
me_sourced=0
if [[ ( "X${how_run_me[1]}" == "Xsource" ) || ( "X${how_run_me[1]}" == "X." ) ]]
then
	me_sourced=1
	script_path=`echo "${how_run_me[2]}" | sed "s/^'//" | sed "s/'$//"`
fi

Temp=/tmp
TempBaseDir="${Temp}/scankeylx"
if (! mkdir -p "${TempBaseDir}")
then
	echo "${TempBaseDir}: Can not create directory."
fi


function ReportLogExit() {
	if (( ${me_sourced} == 0 ))
	then
		exit $1
	fi
}

LsbRelease=/etc/lsb-release

if [[ -f "${LsbRelease}" ]]
then
	source "${LsbRelease}"
fi

if (( ${me_sourced} == 0 ))
then
	which_path=`which "$0"`
else
	which_path="${script_path}"
fi

full_path=`readlink -f "${which_path}"`
full_dir=`dirname "${full_path}"`
script_name=`basename "${full_path}"`

on_temp=0
if [[ "${TempBaseDir}/X" == "${full_dir}/X" ]]
then
	on_temp=1
fi

TempLogDir="${TempBaseDir}/logsave"

echo "me_sourced=${me_sourced}"
echo "on_temp=${on_temp}"
echo "which_path=${which_path}"
echo "full_path=${full_path}"
echo "full_dir=${full_dir}"
echo "script_name=${script_name}"


# Left curly bracket.
cBL='{'
# Right curly bracket.
cBR='}'
# Dollar.
cDL='$'
# Double quotation.
cQQ='"'
# Exclamation mark.
cEX='!'

# find gawk or awk.
AWK=`   ( [ -x /bin/gawk ] && echo /bin/gawk )         || ( [ -x /bin/awk ] && echo /bin/awk ) \
     || ( [ -x /usr/bin/gawk ] && echo /usr/bin/gawk ) || ( [ -x /usr/bin/awk ] && echo /usr/bin/awk ) \
    `

# Get process name.
function PidToName() {
	PidToName_tmp=`cat /proc/$1/status | grep -i '^Name:' | ${AWK} -F: '{print $2}'`
	echo -n ${PidToName_tmp}
}

# Get parent process id.
function PidToParent() {
	cat /proc/$1/status | grep -i '^PPid:' | ${AWK} -F: '{print $2}'
}

# message to show at exit, wait time before close terminal window.
exit_message="Exit."
exit_waits=0

# Print message at exit.
function AtExitMessage() {
	if [[ "X${REPORTLOG_SCANKEY}" == "Xon_termnew" ]]
	then
		echo "${exit_message}"
		sleep ${exit_waits}
	fi
}

# Test if my parent process is command line shell.
if [[ "X${REPORTLOG_SCANKEY_PARENT}" == "X" ]]
then
	parent_pid=`PidToParent $$`
	parent_name=`PidToName ${parent_pid}`

	export REPORTLOG_SCANKEY_PARENT_PID=${parent_pid}

	case "X${parent_name}" in
	(X | Xsh | Xash | Xbash | Xbash2 | Xash | Xbsh | Xcsh | Xtcsh | Xzsh | Xksh)
		# Run from command line.
		echo "${script_name}: Start from command-line shell ${parent_name}."
		export REPORTLOG_SCANKEY_PARENT=command_line
	;;
	(*)
		# Run from gui.
		echo "${script_name}: Start from GUI shell ${parent_name}."
		export REPORTLOG_SCANKEY_PARENT=gui
	;;
	esac
fi

# Random uuid path.
uuid_path=/proc/sys/kernel/random/uuid

# Generate temporal filename in 8.3 format.
function Temp8NAME() {
	cat ${uuid_path} | md5sum | tr a-z A-Z | cut -c1-8
}

# Get memory usage from /proc/meminfo

temp_meminfo=${TempBaseDir}/meminfo.${script_name}_`cat "${uuid_path}"`

function TrapMemFree() {
	[  "x${temp_meminfo}" != "x" ] && [ -e "${temp_meminfo}" ] && rm "${temp_meminfo}"
	cd "${current_dir}"
	ReportLogExit 1
}

trap TrapMemFree SIGHUP SIGTERM SIGINT

# Get free memory size. Cache + Free.
function MemFree() {
	cp /proc/meminfo "${temp_meminfo}"

	meminfo_free=`cat "${temp_meminfo}" \
		| grep -i "^MemFree" \
		| ${AWK} -F: '{print $2}' \
		| ${AWK} '{print $1}' \
		| head -1`

	meminfo_cached=`cat "${temp_meminfo}" \
		| grep -i "^Cached" \
		| ${AWK} -F: '{print $2}' \
		| ${AWK} '{print $1}' \
		| head -1`

	echo $(( ${meminfo_free} + ${meminfo_cached} ))
	rm -f "${temp_meminfo}"
}

# Get free memory size.
mem_free=`MemFree`

# Reserved memory size to do parallel processing.
mem_para_reserve=8192

on_terminal=0
if ( tty -s )
then
	# Assigned standard input to terminal.
	on_terminal=1
fi

if (( ( ${on_terminal} == 0 ) && ( ${me_sourced} == 0 ) ))
then
	# We need open terminal window.
	# We continue process in terminal window.
	# Mark environment variable "on terminal".
	export REPORTLOG_SCANKEY=on_termnew

	terminal_title="Progress message - ${script_name}"
	screen_size=80x24

	# start xterm
	which xterm > /dev/null 2>&1
	if (( $? == 0 )) 
	then
		# we found xterm command.
		xterm -geometry ${screen_size} -sl 10240 -sb -rightbar -T "${terminal_title}" -e "${full_path} $*" &
		ReportLogExit 0
	fi
fi

# Feed argument by self.
auto_argument=0

# Update exit message and hold time.
exit_message="Done! All report files are created. This window will be closed after 30 seconds."
exit_waits=30

if [[ "x$1" == "x" ]]
then
	# No argument.

	# Run from file browser.
	# Automatically complete arguments.

	logfiles=(` ( ls ${TempLogDir}/scan_[0-9]*_[0-9]*[0-9].log \
		         ${TempLogDir}/scan_[0-9]*_[0-9]*[0-9]_[0-9][0-9]*.log 2>/dev/null \
		    ) | sort -u \
		`)
	if (( ${#logfiles[*]} <=0 ))
	then
		# No log file.
		echo "${script_name}: No files to report."
		# Update exit message, and hold time.
		exit_message="This window will close after 10 seconds."
		exit_waits=10
		AtExitMessage
		ReportLogExit 1
	fi

	auto_argument=1
else
	# There are arguments.
	echo "${script_name}: start with argument(s)."
	logfiles=( $* )
fi

function TrapReportLoop() {
	[ "x${temp_1st}" != "x" ]  && [ -e "${temp_1st}" ]  && sudo rm "${temp_1st}"
	[ "x${temp_2nd}" != "x" ]  && [ -e "${temp_2nd}" ]  && sudo rm "${temp_2nd}"
	[ "x${temp_3rd}" != "x" ]  && [ -e "${temp_3rd}" ]  && sudo rm "${temp_3rd}"
	cd "${current_dir}"
	ReportLogExit 1
}

# Clean temp files at signaled(Ctrl-C).
trap TrapReportLoop SIGHUP SIGTERM SIGINT

# @param $1 Directory to place temporal text file.

function TempTextFileFat() {
	temp_file_name=""

	while [[ "X${temp_file_name}" == "X" ]]
	do
		temp_file_name="$1/`Temp8NAME`.TXT"
		if [ -e "${temp_file_name}" ]
		then
			# A same name file already exist.
			temp_file_name=""
		fi
	done
	echo "${temp_file_name}"
}

function ParallelPoint() {
	if (( ${do_parallel} == 0 ))
	then
		# do in sequential.
		for pid in $*
		do
			wait ${pid}
		done
	fi
}

function SequentialPoint() {
	if (( ${do_parallel} == 0 ))
	then
		wait $1
	else
		# do in sequential.
		pid_index=$#
		while (( ${pid_index} > 0 ))
		do
			pid=${!pid_index}
			wait ${pid}
			pid_index=$(( pid_index - 1 ))
		done
	fi
}

echo "auto_argument=${auto_argument}"

File20D="20Digits.txt"
File25D="25Digits.txt"
File20DSort="20DigitsSort.txt"
File25DSort="25DigitsSort.txt"
File25D20="25Digits20.txt"
File10D="10Digits.txt"
FilePId="ProductId.txt"
FilePKey="ProductKey.txt"
FileDigPKey7="DigitalProductId7.txt"
FileDigPKey8="DigitalProductId8.txt"
FileDigPKey4_7="DigitalProductId4-7.txt"
FileDigPKey4_8="DigitalProductId4-8.txt"

FileSerial="Serial.txt"
FileLicence="Licence.txt"
FilePidKey="PidKey.txt"

for f in ${logfiles[*]}
do
	# do filter process in parallel. default do filter sequential.
	do_parallel=0

	# Get file length to filter.
	flength=( `stat -c %s "${f}" ` )
	flength=${flength[0]}

	# Convert to Kbyte.
	flength=$(( ( ${flength} + 1023 ) / 1024 ))

	# Guess memory usage.
	mem_use=$(( ( ( ${flength} * 12 ) / 8 ) + ${mem_para_reserve} ))

	if (( ${mem_free} > ${mem_use} ))
	then
		# There are enough memory.
		do_parallel=1
	fi

	if [[ "X${do_parallel_force}" != "X" ]]
	then
		# Forced do in parallel.
		do_parallel=1
	fi

	if (( ${do_parallel} != 0 ))
	then
		echo "${f}: Start parallel process."
	else
		echo "${f}: Start sequential process."
	fi

	# Convert log file name to output directory.
	output_dir="${f%.*}.dir"

	if [[ -d "${output_dir}" ]]
	then
		# The same name directory exist.
		if (( ${auto_argument} != 0 ))
		then
			# Feed argument by self.
			# Already made report.
			echo "${f}: Skip making report. Directory "${output_dir}" is exist."
			continue;
		fi
	else
		# The same name directory is not exist.
		sudo mkdir -p "${output_dir}"
	fi

	# Prepare temporal file names.
	temp_1st=`TempTextFileFat "${output_dir}"`
	temp_2nd=`TempTextFileFat "${output_dir}"`
	temp_3rd=`TempTextFileFat "${output_dir}"`

	# Output 20Digits.txt report.
	# Do in parallel.

	(	report_file="${output_dir}/${File20D}"
		echo "${script_name}: ${report_file}: Building report."
		grep -i '[[:alnum:]]\{5\}-[[:alnum:]]\{3\}-[[:alnum:]]\{7\}-[[:alnum:]]\{4\}' "${f}" \
		| sudo dd "of=${report_file}"
		sync
		echo "${script_name}: ${report_file}: Done."
	) &

	# Get Process ID to wait done.
	pid_1st=${!}

	ParallelPoint ${pid_1st}

	# Output 25Digits.txt report
	# Do in parallel.

	(	report_file="${output_dir}/${File25D}"
		echo "${script_name}: ${report_file}: Building report."
		grep -i '[[:alnum:]]\{5\}-[[:alnum:]]\{5\}-[[:alnum:]]\{5\}-[[:alnum:]]\{5\}-[[:alnum:]]\{5\}' "${f}" \
		| sudo dd "of=${report_file}"
		sync
		echo "${script_name}: ${report_file}: Done."
	) &

	# Get Process ID to wait done.
	pid_2nd=${!}

	SequentialPoint ${pid_2nd} ${pid_1st}

	# Output 20DigitsSort.txt report.
	# Do in sequential.

	(	report_base="${output_dir}/${File20D}"
		report_file="${output_dir}/${File20DSort}"
		echo "${script_name}: ${report_file}: Building report."
		sort -u "${report_base}" \
		| sudo dd "of=${report_file}"
		sync
		echo "${script_name}: ${report_file}: Done."
	)

	# Output 25DigitsSort.txt report.
	# Do in sequential.

	(	report_base="${output_dir}/${File25D}"
		report_file="${output_dir}/${File25DSort}"
		echo "${script_name}: ${report_file}: Building report."
		sort -u "${report_base}" \
		| sudo dd "of=${report_file}"
		sync
		echo "${script_name}: ${report_file}: Done."
	)

	# Output 25Digits20.txt report.
	# Do in sequential.

	(	report_base="${output_dir}/${File25DSort}"
		report_file="${output_dir}/${File25D20}"
		echo "${script_name}: ${report_file}: Building report."
		grep -e '[[:alnum:]]\{7\}-[[:alnum:]]\{4\}' -e '-[[:alnum:]]\{3\}-' "${report_base}" \
		| sudo dd "of=${report_file}"
		sync
		echo "${script_name}: ${report_file}: Done."
	)

	# Output ProductId.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FilePId}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_1st}"
		grep -i '^ProductId' "${f}" \
		| sudo dd "of=${temp_1st}"
	) &

	# Get Process ID to wait done.
	pid_1st=${!}

	ParallelPoint ${pid_1st}


	# Output ProductKey.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FilePKey}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_3rd}"
		grep -i '^ProductKey' "${f}" \
		| sudo dd "of=${temp_2nd}"
		sync
	) &

	# Get Process ID to wait done.
	pid_2nd=${!}

	SequentialPoint ${pid_2nd} ${pid_1st}

	# Output ProductId.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FilePId}"
		sort -u "${temp_1st}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_1st}"
		sync
		echo "${script_name}: ${report_file}: Done."
	)

	# Output ProductKey.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FilePKey}"
		sort -u "${temp_2nd}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_2nd}"
		sync
		echo "${report_file}: Done."
	)

	# Output 10Digits.txt report (post-process step 1).
	# Do in sequential.

	(	report_file="${output_dir}/${File10D}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_2nd}"
		grep -i '^ProductId[[:space:]]*=*[[:space:]]*[0-9]\{5\}[[:alnum:]]\{3\}[0-9]\{12\}' \
			"${output_dir}/${FilePId}" \
		| sudo dd "of=${temp_3rd}"
	)

	# Output 10Digits.txt report (post-process step 2).
	# Do in sequential.

	(	report_file="${output_dir}/${File10D}"
		sort -u "${temp_3rd}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_3rd}"
		sync
		echo "${script_name}: ${report_file}: Done."
	)

	# Output DigitalProductId7.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FileDigPKey7}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_1st}"
		grep -i '^DigitalProductId' "${f}" | grep -i -v '^DigitalProductId4' \
		| grep -i -v '(win8-10)' \
		| sudo dd "of=${temp_1st}"
		sync
	) &

	# Get Process ID to wait done.
	pid_1st=${!}

	ParallelPoint ${pid_1st}

	# Output DigitalProductId8.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FileDigPKey8}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_2nd}"
		grep -i '^DigitalProductId' "${f}" | grep -i -v '^DigitalProductId4' \
		| grep -i '(win8-10)' \
		| sudo dd "of=${temp_2nd}"
		sync
	) &

	# Get Process ID to wait done.
	pid_2nd=${!}

	SequentialPoint ${pid_2nd} ${pid_1st}

	# Output DigitalProductId7.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FileDigPKey7}"
		sort -u "${temp_1st}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_1st}"
		sync
		echo "${report_file}: Done."
	)

	# Output DigitalProductId8.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FileDigPKey8}"
		sort -u "${temp_2nd}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_2nd}"
		sync
		echo "${report_file}: Done."
	)

	# Output DigitalProductId4-7.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FileDigPKey4_7}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_1st}"
		grep -i '^DigitalProductId4' "${f}" | grep -i -v '(win8-10)' \
		| sudo dd "of=${temp_1st}"
		sync
	) &

	# Get Process ID to wait done.
	pid_1st=${!}

	ParallelPoint ${pid_1st}

	# Output DigitalProductId4-8.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FileDigPKey4_8}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_2nd}"
		grep -i '^DigitalProductId4' "${f}" | grep -i '(win8-10)' \
		| sudo dd "of=${temp_2nd}"
		sync
	) &

	# Get Process ID to wait done.
	pid_2nd=${!}

	SequentialPoint ${pid_2nd} ${pid_1st}

	# Output DigitalProductId4-7.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FileDigPKey4_7}"
		sort -u "${temp_1st}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_1st}"
		sync
		echo "${report_file}: Done."
	)

	# Output DigitalProductId4-8.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FileDigPKey4_8}"
		sort -u "${temp_2nd}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_2nd}"
		sync
		echo "${report_file}: Done."
	)

	# Output Serial.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FileSerial}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_1st}"
		grep -i '^Serial' "${f}" \
		| sudo dd "of=${temp_1st}"
		sync
	) &

	# Get Process ID to wait done.
	pid_1st=${!}

	ParallelPoint ${pid_1st}

	# Output Licence.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FileLicence}"
		echo "${script_name}: ${report_file}: Building report. temp=${temp_2nd}"
		grep -i '^Licence' "${f}" \
		| sudo dd "of=${temp_2nd}"
		sync
	) &

	# Get Process ID to wait done.
	pid_2nd=${!}

	SequentialPoint ${pid_2nd} ${pid_1st}

	# Output Serial.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FileSerial}"
		sort -u "${temp_1st}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_1st}"
		sync
		echo "${report_file}: Done."
	)

	# Output Licence.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FileLicence}"
		sort -u "${temp_2nd}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_2nd}"
		sync
		echo "${report_file}: Done."
	)

	# Output PidKey.txt report (pre-process).
	# Do in parallel.

	(	report_file="${output_dir}/${FilePidKey}"
		echo "${script_name}: ${report_file}: Building report."
		grep -i '^PIDKEY' "${f}" \
		| sudo dd "of=${temp_1st}"
		sync
	) &

	# Get Process ID to wait done.
	pid_1st=${!}

	ParallelPoint ${pid_1st}

	# Output LMXXX.txt report (no post-process).
	# Do in parallel.

	(	report_file="${output_dir}/LMXXX.txt"
		echo "${script_name}: ${report_file}: Building report."
		grep -i -e '^LMLIC' -e '^LMKEY' "${f}" \
		| sudo dd "of=${report_file}"
		sync
		echo "${report_file}: Done."
	) &

	# Get Process ID to wait done.
	pid_2nd=${!}

	SequentialPoint ${pid_2nd} ${pid_1st}

	# Output PidKey.txt report (post-process).
	# Do in sequential.

	(	report_file="${output_dir}/${FilePidKey}"
		sort -u "${temp_1st}" \
		| sudo dd "of=${report_file}"
		sudo rm "${temp_1st}"
		sync
		echo "${report_file}: Done."
	)

	if [[ -e "${temp_1st}" ]]
	then
		sudo rm "${temp_1st}"
	fi

	if [[ -e "${temp_2nd}" ]]
	then
		sudo rm "${temp_2nd}"
	fi

	if [[ -e "${temp_3rd}" ]]
	then
		sudo rm "${temp_3rd}"
	fi

	sync
done

AtExitMessage
ReportLogExit 0
