#!/bin/bash
#default install path
target_dir="/opt/pqlabs/platform"
platform_air_app_id="com.pqlabs.MultiTouchPlatform"

#get the install target from the arguments
if [ $# -gt 0 ]; then
	target_dir=$1
fi

cd $(dirname "$0")
cur_dir=$(pwd)

echo "install MultiTouchPlatform to: \"$target_dir\"..."
# test the sudo
echo "testing the \"sudo\" ..."
sudo echo "OK."
if [ $? -ne 0 ]; then
    echo "Failed. please retry later, or switch to \"root\" by \"su\" and retry."
    exit 1
fi

sudo mkdir -p $target_dir

# close the enforcing selinux firstly
is_selinux_enabled=0
is_selinux_enforced=0
sudo id -Z
if [ $? -eq 0 ]; then
    echo "selinux enabled"
    is_selinux_enabled=1
    selinux_mode=$(getenforce)
    if [ "Enforcing" = ${selinux_mode} ]; then
        echo "selinux enforcing"
        is_selinux_enforced=1
        sudo setenforce 0
    fi
fi

function prepare_air_lib() {
	echo "prepare air lib.."
        tmp_cur_dir=$(pwd)
	# copy libgnome-keyring for AdobeAIRRuntimeInstaller
	sudo mkdir -p ${target_dir}/air_lib
	sudo cp -f air_lib/* ${target_dir}/air_lib
	cd ${target_dir}/air_lib
	sudo ln -sf libgnome-keyring.so.0.1.1 libgnome-keyring.so.0
	cd ${tmp_cur_dir}
}

#prepare_air_lib;

sudo ./arh -isRuntimeInstalled
is_air_installed=$?
if [ 0 -ne $is_air_installed ]; then 
    echo " Adobe AIR not installed."
else
if [ 1 -eq $is_selinux_enabled ]; then
    sudo chcon -t textrel_shlib_t "/opt/Adobe AIR/Versions/1.0/Resources/libcurl.so" "/opt/Adobe AIR/Versions/1.0/Resources/libadobecertstore.so" 
fi
fi

# unistall old firstly
echo " uninstall old ..."
sudo killall -q pqmtpdaemon
sudo killall -q MultiTouchPlatformHelper
sudo killall -q MultiTouchPlatf
sudo ./arh -isAppInstalled "${platform_air_app_id}"
if [ 0 -eq $? ]; then
    echo " uninstall old UI ..."
    sudo ./arh -uninstallAppSilent "${platform_air_app_id}"
fi

if [ -d ${target_dir} ]; then
    echo " remove old files ..."
    cd ${target_dir}
    if [ -e ${target_dir}/AdobeAIRInstaller.bin ]; then
        sudo rm -rf $(ls ${target_dir} | grep -v "AdobeAIRInstaller.bin")
    else
        sudo rm -rf ${target_dir}
    fi
    cd ${cur_dir}
fi
# install begin
sudo mkdir -p ${target_dir}/Report
sudo mkdir -p ${target_dir}/lib
sudo cp -f lib/* ${target_dir}/lib
prepare_air_lib;

# add user command "pqmtplatform"
sudo cp -f pqmtplatform "/usr/local/bin"
sudo chmod +x "/usr/local/bin/pqmtplatform"

# add auto start
sudo cp -f pqmtd "/etc/init.d"
sudo chmod +x "/etc/init.d/pqmtd"
type -a update-rc.d
if [ $? -eq 0 ]; then # it's Ubuntu
    sudo update-rc.d -f pqmtd remove
    sudo update-rc.d -f pqmtd defaults
else
    is_chkconfig_exist=0
    type -a chkconfig
    if [ $? -eq 0 ]; then
        is_chkconfig_exist=1
    fi
    type -a systemctl
    if [ $? -eq 0 ]; then # it's Fedora 15 later
        if [ $is_chkconfig_exist -eq 1 ]; then
            sudo chkconfig --del pqmtd
        fi
        fedora_ver=$(uname -r)
        if [[ "$fedora_ver" == *".fc14."* ]]; then
            echo "it's Fedora 14"
            sudo chkconfig --add pqmtd
            sudo chkconfig --level 234 pqmtd on
        else 
            sudo rm -f /etc/init.d/pqmtd
            sudo cp -f pqmtd.service /lib/systemd/system
            sudo systemctl enable pqmtd.service
        fi
    elif [ $is_chkconfig_exist -eq 1 ]; then # it's Fedora
        sudo chkconfig --del pqmtd
        sudo chkconfig --add pqmtd
        sudo chkconfig --level 234 pqmtd on
    else
        echo "no update-rc.d or chkconfig, ln manually"
        sudo ln -sf /etc/init.d/pqmtd /etc/rc0.d/K20pqmtd
        sudo ln -sf /etc/init.d/pqmtd /etc/rc1.d/K20pqmtd
        sudo ln -sf /etc/init.d/pqmtd /etc/rc2.d/S20pqmtd
        sudo ln -sf /etc/init.d/pqmtd /etc/rc3.d/S20pqmtd
        sudo ln -sf /etc/init.d/pqmtd /etc/rc4.d/S20pqmtd
        sudo ln -sf /etc/init.d/pqmtd /etc/rc5.d/S20pqmtd
        sudo ln -sf /etc/init.d/pqmtd /etc/rc6.d/K20pqmtd
    fi
fi
# 
if [ -d /etc/X11/Xsession.d ]; then
    sudo cp -f 99pqlocalhost_start /etc/X11/Xsession.d
fi
if [ -d /etc/X11/xinit/xinitrc.d ]; then
    sudo cp -f pqlocalhost.sh /etc/X11/xinit/xinitrc.d
    sudo chmod +x /etc/X11/xinit/xinitrc.d/pqlocalhost.sh
fi

# copy files to the target dir
sudo cp -f MultiTouchPlatformHelper pqmtpdaemon uninstall.sh *.pqx *.xml *.so output.log daemon.log version $target_dir
sudo cp -f arh MultiTouchPlatform.air $target_dir

# change to the target directory
cd $target_dir
sudo chmod +x MultiTouchPlatformHelper pqmtpdaemon uninstall.sh

# for selinux
if [ 1 -eq $is_selinux_enabled ]; then
    sudo restorecon MultiTouchPlatformHelper
    sudo chcon -t textrel_shlib_t libMultiTouchPlatformHelper.so
    #ffmpeg for selinux
    cd ./lib
    sudo chcon -t textrel_shlib_t libavcodec.so*
    sudo chcon -t textrel_shlib_t libavformat.so*
    sudo chcon -t textrel_shlib_t libavutil.so*
    sudo chcon -t textrel_shlib_t libswscale.so*
    cd ..
fi
#
cd ${target_dir}/lib
sudo chmod +x link_util
sudo ./link_util -m
cd ..

sudo chmod g+w mtsvrset.xml
sudo chmod o+w mtsvrset.xml
sudo chmod g+w service.pqx
sudo chmod o+w service.pqx
sudo chmod g+w parsercfg.pqx
sudo chmod o+w parsercfg.pqx
sudo chmod g+w output.log
sudo chmod o+w output.log
sudo chmod g+w daemon.log
sudo chmod o+w daemon.log

# start to install the AIR runtime
sudo chmod +x arh
sudo ./arh -isRuntimeInstalled
if [ 1 -eq $? ]; then  # if not, install it firstly
    echo " install AIR run time ..."
    sudo cp -f AdobeAIRInstaller.bin ${target_dir}
    sudo chmod +x ${target_dir}/AdobeAIRInstaller.bin
    sudo LD_LIBRARY_PATH=${target_dir}/air_lib ${target_dir}/AdobeAIRInstaller.bin
#    if [ 0 -ne $? ]; then 
#        echo " failed."
#        type -a yum
#        if [ 0 -eq $? ]; then
#           type -a rpmbuild
#           if [ 0 -ne $? ]; then
#               echo " We guess the system is Fedora or RedHat. here, the \"rpmbuild\" is necessary for installing Adobe AIR, so we'll try to install \"rpmbuild\" through \"yum install rpm-build\", is that ok?[y/n](y)"
#               read input
#               if [ "$input" != "n" ]; then
#                   sudo yum install rpm-build
#                   if [ 0 -eq $? ]; then
#                       echo "reinstall Adobe AIR..."
#                       sudo LD_LIBRARY_PATH=${target_dir}/air_lib ${target_dir}/AdobeAIRInstaller.bin
#                   fi
#               fi
#           fi
#        fi
#    fi
fi

# install UI 
sudo chmod +x arh
echo " installing the UI ... "
is_platform_installed=0
sudo ./arh -installAppSilent -location ${target_dir} -desktopShortcut -programMenu ${target_dir}/MultiTouchPlatform.air
if [ 0 -ne $? ]; then
    echo "MultiTouch Platform UI will be installed manually."
else
    is_platform_installed=1
fi

# restore the selinux
if [ 1 -eq ${is_selinux_enforced} ]; then
    sudo setenforce 1
fi

#install Adobe AIR
if [ 0 -ne $is_air_installed ]; then 
	#echo "install Adobe AIR"
        cd $cur_dir
	#sudo chmod -R 777 ${cur_dir}/AIR_Manual_Installer
	cd ${cur_dir}/AIR_Manual_Installer
	sudo cp -r Adobe\ AIR /opt/
	sudo cp -r MultiTouchPlatform /opt/pqlabs/platform
 
	sudo mkdir -p /root/.appdata/Adobe/AIR/
	#can't creat file if not login with 'su'
	sudo echo -n 2 > /root/.appdata/Adobe/AIR/eulaAccepted

	sudo cat /etc/passwd | awk -F: '$3>=500' | cut -f 1 -d : > ${cur_dir}/userlist
	for UserName in `sudo cut -f 1 ${cur_dir}/userlist`
	do
		for FolderName in `sudo ls /home -F | grep '/$'`
		do
			FolderName=${FolderName%/*}
			if [ $FolderName = $UserName ];then
				sudo mkdir -p /home/"$FolderName"/.appdata/Adobe/AIR/
				sudo chmod -R go+rwx /home/"$FolderName"/.appdata/Adobe
				sudo echo -n 2 > /home/"$FolderName"/.appdata/Adobe/AIR/eulaAccepted
			fi
		done
	done

	sudo chmod -R go+rwx /root/.appdata/Adobe
        is_platform_installed=1
fi

if [ 0 -ne $is_platform_installed ]; then
    sudo cp ${target_dir}/MultiTouchPlatform/share/service128.png /usr/share/icons
    sudo mv -f /usr/share/icons/service128.png /usr/share/icons/com.pqlabs.multitouchplatform.png
    sudo rm -f /usr/share/applications/com.pqlabs.multitouchplatform.desktop
    sudo cp ${target_dir}/MultiTouchPlatform/share/META-INF/AIR/com.pqlabs.multitouchplatform.desktop /usr/share/applications
    sudo chmod 777 /usr/share/applications/com.pqlabs.multitouchplatform.desktop
fi


cd $cur_dir
echo " Install completed."
echo " Version: $(cat version)"
echo " Staring pqmtplatform ..."
sudo /usr/local/bin/pqmtplatform
echo "------------------------------"
echo " \"Reboot\" or running \"pqmtplatform\" in the terminal."
