#!/bin/bash
# startscankey: scankey starter.
# Copyright (C) [2017/2], 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.

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

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

LsbRelease=/etc/lsb-release

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

machine=`uname -m`

live_cd="no"
if mount | grep -q -e '/cow[[:space:]]\+on[[:space:]]\+/[[:space:]]\+' \
		   -e '/dev/mapper/live-rw[[:space:]]\+on[[:space:]]\+/[[:space:]]\+' \
		   -e '/UNIONFS.*/KNOPPIX'
then
	live_cd="yes"
fi

if cat /proc/cmdline | grep -q '/casper'
then
	live_cd="yes"
fi

# Do not kill hungup thread and process.
hung_task=/proc/sys/kernel/hung_task_timeout_secs
if [[ -e ${hung_task} ]]
then
	echo 0 | sudo tee ${hung_task} > /dev/null
fi

# disable swaps.
if [[ ( "${live_cd}" == "yes" ) && ( "$machine" != arm* ) ]]
then
	# "Live CD boot" and "not ARM platfrom"
	# @note ARM platform may have less memory, so we keep swap.
	echo "${0}: off swap."
	sudo swapoff -a
fi

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

# Open file manager, GNOME, ubuntu.
open_work_directory=0
if ! ( xwininfo -root -tree | grep -q 'scankeylx[.*]nautilus')
then
	if which nautilus > /dev/null
	then
		nautilus "file://${TempBaseDir}" &
		open_work_directory=1
	fi
fi

# Open file manager, Linux mint.
if (( ${open_work_directory} == 0 ))
then
	if ! ( xwininfo -root -tree | grep -q 'scankeylx[.*]nemo')
	then
		if which nemo > /dev/null
		then
			nemo "${TempBaseDir}" &
			open_work_directory=1
		fi
	fi
fi

# Open file manager, raspberry Pi3.
if (( ${open_work_directory} == 0 ))
then
	if ! ( xwininfo -root -tree | grep -q 'scankeylx[.*]pcmanfm')
	then
		if which pcmanfm > /dev/null
		then
			pcmanfm "${TempBaseDir}" &
			open_work_directory=1
		fi
	fi
fi

# Open file manager, KDE, CentOS, Fedora.
if (( ${open_work_directory} == 0 ))
then
	if ! ( xwininfo -root -tree | grep -q 'scankeylx[.*]dolphin')
	then
		if which dolphin > /dev/null
		then
			dolphin "${TempBaseDir}" &
			open_work_directory=1
		fi
	fi
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}"`

mount_point=`stat -c "%m" /`
if [[ ( "${mount_point}" != "?" ) && ( "${mount_point}" != "m" )  ]]
then
	mount_point=`stat -c "%m" "${full_path}"`
	if (( $? != 0 ))
	then
		mount_point=""
	fi
else
	# stat doesn't support %m
	mount_point=`cat /proc/mounts \
		| awk '{print $2 " " $1}' \
		| ( LANG=C sort -r ) \
		| grep "^${full_dir}" \
		| tail -1 \
		| awk '{print $NF}' \
		`
fi

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

TempLogDir="${TempBaseDir}/logsave"

if (( ${on_temp} == 0 ))
then
	if [[ ( -L "${TempLogDir}" ) ]]
	then
		rm -f "${TempLogDir}"
	fi

	if [[ -e "${TempLogDir}" ]]
	then
		rm -f "${TempLogDir}"
	fi

	if [[ -d "${TempLogDir}" ]]
	then
		mv -f "${TempLogDir}" "${TempLogDir}-`date +%Y%m%d%H%M%S`-$$"
	fi

	ln -s "${full_dir}" "${TempLogDir}"
fi

echo "${0}: INFO: machine=${machine}"
echo "${0}: INFO: me_sourced=${me_sourced}"
echo "${0}: INFO: on_temp=${on_temp}"
echo "${0}: INFO: which_path=${which_path}"
echo "${0}: INFO: full_path=${full_path}"
echo "${0}: INFO: full_dir=${full_dir}"
echo "${0}: INFO: mount_point=${mount_point}"

case "${machine}" in
	(i386|i486|i586|pentium-mmx|c3|c3-2|winchip|winchip2|winchip-c6)
		echo "${0}: WARNING: It may hang or abort by SIGILL (illegal instruction), Processor is too old."
		machine=i686
	;;
	(i686|k6|athlon|k8)
		machine=i686
	;;
	(x86_64)
		# keep machine
		# do nothing.
	;;
	(armv6|armv6[a-z])
		echo "${0}: WARNING: Not tested on armv6 architecture."
		machine=armv7
	;;
	(armv7|armv7[a-z])
		machine=armv7
	;;
	(*)
		echo "${0}: ERROR: Unsupported Processor."
		StartScankeyExit 2
	;;
esac

scankeylx_exe_all=(scankeylx-i686 scankeylx-x86_64 scankeylx-armv7)
scankeylx_exe_file="scankeylx-${machine}"
scankeylx_exe="${TempBaseDir}/${scankeylx_exe_file}"

files_tar_gz="scankeylx.tar.gz"

copy_files=( startscankey reportlog scankeylx.png ${scankeylx_exe_file} )
app_icon="scankeylx.png"
wm_icons="/usr/share/pixmaps"

if (( ${on_temp} == 0 ))
then
	echo "${mount_point}: remount with read/write."
	if [[ "${mount_point:0:1}" == "/" ]]
	then
		sudo mount -o rw,remount "${mount_point}"
	else
		echo "${full_path}: WARNING: Unknown mount point, may fail to write log."
	fi
	files_tar_gz_path="${full_dir}/${files_tar_gz}"
	if [[ -f "${files_tar_gz_path}" ]]
	then
		echo -n "${0}: INFO: pushd, "; pushd "${TempBaseDir}"
		tar zxvf "${files_tar_gz_path}"
		echo -n "${0}: INFO: popd, "; popd
	else
		echo "${files_tar_gz_path}: NOTICE: Not found, try copy files one by one."
		for cf in ${copy_files[*]}
		do
			copy_from="${full_dir}/${cf}"
			copy_to="${TempBaseDir}/${cf}"
			if [[ ! -f "${copy_from}" ]]
			then
				echo "${copy_from}: INFO: Not found, skip."
			else
				cp "${copy_from}" "${copy_to}"
				chmod a+x "${copy_to}"
			fi
		done
	fi
	if [[ ( "${live_cd}" == "yes" ) && ( "${machine}" != arm* ) ]]
	then
		if [[ -f "${TempBaseDir}/${app_icon}" ]]
		then
			echo "${wm_icons}/${app_icon}: INFO: Setup application icon."
			sudo cp "${TempBaseDir}/${app_icon}" "${wm_icons}"
			(	cd "${wm_icons}"
				sudo ln -s "${app_icon}" "${scankeylx_exe_file}"
			)
		fi
		echo "${which_path}: NOTICE: Disable screen saver."
		xset s off
		xset s noblank
		xset -dpms
	fi
	for f in ${scankeylx_exe_all[*]}
	do
		if [[ "$f" != "${scankeylx_exe_file}" ]]
		then
			scankeylx_exe_rm="${TempBaseDir}/${f}"
			if [[ -f "${scankeylx_exe_rm}" ]]
			then
				# Exist unnecessary executable.
				# Remove it, and get more memory free space.
				rm -f "${scankeylx_exe_rm}"
			fi
		fi
	done
fi

echo "${scankeylx_exe}: INFO: Start."
sudo "${scankeylx_exe}" -L "${TempLogDir}" &
StartScankeyExit 0
