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

# Do not kill hungup thread and process.
echo 0 | sudo tee /proc/sys/kernel/hung_task_timeout_secs > /dev/null

# disable swaps.
sudo swapoff -a

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

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

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

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}"`
mount_point=`stat -c "%m" "${full_path}"`
if (( $? != 0 ))
then
	mount_point=""
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 "${TempLogDir}"
	fi

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

	if [[ -d "${TempLogDir}" ]]
	then
		rmdir "${TempLogDir}"
	fi

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

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 "mount_point=${mount_point}"

scankeylx_exe="${TempBaseDir}/scankeylx"

files_tar_gz=scankeylx.tar.gz
copy_files=(startscankey scankeylx reportlog scankeylx.png)
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}: 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
		pushd "${TempBaseDir}"
		tar zxvf "${files_tar_gz_path}"
		popd
	else
		echo "${files_tar_gz_path}: 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}: Not found, skip."
			else
				cp "${copy_from}" "${copy_to}"
				chmod a+x "${copy_to}"
			fi
		done
	fi
	if [ -f ${TempBaseDir}/${app_icon} ]
	then
		echo "${wm_icons}/${app_icon}: Setup application icon."
		sudo cp ${TempBaseDir}/${app_icon} ${wm_icons}
	fi
	echo "${which_path}: Disable screen saver."
	xset s off
	xset s noblank
	xset -dpms
fi

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