################################################################
# Title:.......Automatic install/update OScam                  #
# Author:......Prilly                                          #
# Support:.....prilly@speedbox.me                              #
# Date:........15 Mars 2016                                    #
# Description:.Automaticaly install OScam with systemd support #
#              Updates OScam to latest or specific SVN version #
################################################################

run_install(){
if [ $(whoami) != "root" ]; then
	dialog --title "OScam Installer" --msgbox "\n Only ROOT can run this script!" 7 70
	return 1
elif [ -f ${daemon_dir}/oscam1 ]; then
	dialog --title "OScam Installer" --msgbox "\n OScam already installed! Try running OScam upgrade instead!" 7 70
	return 1
else
	dialog --title "Confirmation"  --yesno "\n Install OScam CardServer?" 7 70
	if [ ${?} -eq 1 2>/dev/null ]; then
		return 1
	else
		check_distrib
		if [ ${?} -eq 0 2>/dev/null ]; then
			set_instances_count
			install_reader_fw
			copy_files
			compile_oscam
			restart_oscam
			dialog --title "OScam Installer" --msgbox "\n Installation completed ok!\n Webif: http://IP-of-server:888[1-9]\n Webif user/pass = root/root" 9 70
		fi
	fi
fi
}

run_update(){
dialog --title "OScam Installer" --msgbox "To run an upgrade of OScam, the install routine must have been run once earlier.
This script does NOT support upgrading OScam without OScam has been initially installed by the script. 
IMPORTANT: SysV is now replaced with Systemd, use systemctl start|stop|restart oscam(1-9).service" 13 70
if [ $(whoami) != "root" ]; then
	dialog --title "OScam Installer" --msgbox "\n Only ROOT can run this script!" 7 70
	return 1
elif [ ! -d ${conf_dir}/oscam1 ]; then
	dialog --title "OScam Installer" --msgbox "\n OScam not installed! Try running OScam install instead!" 7 70
	return 1
else
	dialog --title "Confirmation"  --yesno "\n Update OScam CardServer?" 7 70
	if [ ${?} -eq 1 2>/dev/null ]; then
		return 1
	else
		check_distrib
		if [ ${?} -eq 0 2>/dev/null ]; then
			set_instances_count
			copy_files
			compile_oscam
			restart_oscam
			dialog --title "OScam Installer" --msgbox "\n OScam CardServer upgrade completed!" 7 70
		fi
	fi
fi
}

check_distrib(){
local cd_os=""
local cd_ver=""
if [ -f /etc/lsb-release ]; then
	. /etc/lsb-release
	cd_os="${DISTRIB_ID}"
	cd_ver="${DISTRIB_RELEASE}"
elif [ -f /etc/debian_version ]; then
	cd_os="Debian"
	cd_ver="$(cat /etc/debian_version)"
elif [ -f /etc/redhat-release ]; then
	cd_os="Red Hat"
	cd_ver="$(cat /etc/redhat-release)"
elif [ -f /etc/SuSE-release ]; then
	cd_os="SuSE"
	cd_ver="$(cat /etc/SuSE-release)"
else
	cd_os="$(uname -s)"
	cd_ver="$(uname -r)"
fi
if [ "${cd_os}" = "Debian" ] || [ "${cd_os}" = "Ubuntu" ]; then
	install_dep_deb
	return 0
else
	dialog --title "OScam Installer" --msgbox "\n Your distribution: ${cd_os} ${cd_ver} is unsupported" 7 70
	return 1
fi
}

install_dep_deb(){
apt-get update
apt-get -y install cmake sudo curl git build-essential libssl-dev libncurses-dev dialog
apt-get -y install usbutils libusb-dev libusb-1.0-0 libusb-1.0-0-dev
}

set_instances_count(){
local instances_count=$(find ${conf_dir}/oscam? -maxdepth 0 -type d 2>/dev/null | wc -l)
if [ ${instances_count} -eq 0 2>/dev/null ]; then
	exec 3>&1 
	local instances_var=$(dialog --title "OScam Installer" --inputbox "\n How many instances should be installed? (1->9):" 8 70 2>&1 1>&3)
	exec 3>&-;
	while [ ! ${instances_var} -gt 0 ] || [ ! ${instances_var} -le 9 ]; do
		dialog --title "OScam Installer" --msgbox "\n Error -> valid range is: (1 to 9)" 7 70
		exec 3>&1 
		local instances_var=$(dialog --title "OScam Installer" --inputbox "\n How many instances should be installed? (1->9):" 8 70 2>&1 1>&3)
		exec 3>&-;
	done
	instances=${instances_var}
else
	instances=${instances_count}
fi
}

install_reader_fw(){
dialog --title "Confirmation" --yesno "\n Install HID Omnikey USB card reader firmware?\n OMNIKEY: 512x, 532x, 1021, 3x21, 6121" 8 70
if [ ${?} -eq 0 2>/dev/null ]; then
	apt-get -y install pcscd pcsc-tools libpcsclite-dev
	if [ $(getconf LONG_BIT) -eq 64 2>/dev/null ]; then
		tar -xvzf pcsc/${fw_hid_64}.tar.gz -C pcsc
		cd pcsc/${fw_hid_64}
		./install
	else
		tar -xvzf pcsc/${fw_hid_86}.tar.gz -C pcsc
		cd pcsc/${fw_hid_86}
		./install
	fi
	cd - >/dev/null
fi
}

copy_files(){
if [ ! -d ${conf_dir} ]; then
	mkdir -p ${conf_dir}
fi
for i in $(seq 1 ${instances}); do
	if [ ! -f ${sysd_dir}/oscam${i}.service ]; then
		cp script/systemd/oscam${i}.service ${sysd_dir}/oscam${i}.service
	else
		cp -u script/systemd/oscam${i}.service ${sysd_dir}/oscam${i}.service
	fi
	if [ ! -d ${log_dir}/oscam${i} ]; then
		mkdir -p ${log_dir}/oscam${i}
	fi
	if [ ! -d ${conf_dir}/oscam${i} ]; then
		mkdir -p ${conf_dir}/oscam${i}
	fi
	if [ ! -f ${conf_dir}/oscam${i}/oscam.conf ]; then
		cp config/oscam${i}.conf ${conf_dir}/oscam${i}/oscam.conf
	fi
	chmod 755 ${sysd_dir}/oscam${i}.service
	chmod 755 -R ${conf_dir}/oscam${i}
	systemctl enable oscam${i}.service
done
}

compile_oscam(){
local co_build_opt="OSCAM_BIN=oscam"
local now=$(date +"%m_%d_%Y")
exec 3>&1 
local compile_var=$(dialog --title "OScam Installer" --inputbox "\n Compile OScam source: version or HEAD?: (10255/HEAD)" 8 70 2>&1 1>&3)
exec 3>&-;
if [ ${compile_var} -eq ${compile_var} 2>/dev/null ]; then
	git clone --depth 1 --branch ${compile_var} ${git_url} ${work_dir}/oscam-svn
else
	git clone --depth 1 ${git_url} ${work_dir}/oscam-svn
fi
cd ${work_dir}/oscam-svn
make config
if [ $(dpkg-query -W -f='${Status}' libpcsclite* 2>/dev/null | grep -c "ok installed") -eq 1 2>/dev/null ]; then
	dialog --title "Confirmation" --yesno "\n Found libpcsclite -> Add USE_PCSC=1 to build option? (Default YES)" 7 80
	if [ ${?} -eq 0 2>/dev/null ]; then
		co_build_opt+=" USE_PCSC=1"
	fi
fi
if [ $(dpkg-query -W -f='${Status}' libusb-1.0-0-dev 2>/dev/null | grep -c "ok installed") -eq 1 2>/dev/null ]; then
	dialog --title "Confirmation" --yesno "\n Found libusb -> Add USE_LIBUSB=1 to build option? (Default YES)" 7 80
	if [ ${?} -eq 0 2>/dev/null ]; then
		co_build_opt+=" USE_LIBUSB=1"
	fi
fi
make ${co_build_opt}
cd - >/dev/null
for i in $(seq 1 ${instances}); do
	if [ -f ${sysd_dir}/oscam${i}.service ]; then
		systemctl stop oscam${i}.service
	else
		killall -9 oscam${i}
	fi
	if [ -f ${daemon_dir}/oscam${i} ]; then
		mv -f ${daemon_dir}/oscam${i} ${daemon_dir}/old_oscam${i}_${now}
	fi
	cp ${work_dir}/oscam-svn/oscam ${daemon_dir}/oscam${i}
	chmod 755 ${daemon_dir}/oscam${i}
done
rm -rf ${work_dir}/oscam-svn
dialog --title "OScam Installer" --msgbox "\n OScam CardServer compiled successfully!" 7 70
}

restart_oscam(){
for i in $(seq 1 ${instances}); do
	if [ -f ${sysd_dir}/oscam${i}.service ]; then
		systemctl stop oscam${i}.service
		systemctl start oscam${i}.service
	else
		dialog --title "OScam Installer" --msgbox "\n ${sysd_dir}/oscam${i}.service file is missing!" 7 70
	fi
	sleep 1
done
}