#!/bin/sh

#  Script.sh
#  BaiduIM
#
#  Created by moligaloo on 13-10-18.
#  Copyright (c) 2013年 baidu. All rights reserved.

if [ -z "$1" ]; then
	exit 1
fi

# cp -r 会使得 BaiduIM.app 的签名失效
cp -R "$1" /Library/Preferences

OLD_CONFIG_DIR="$HOME/Documents/Baidu/input"
NEW_CONFIG_DIR="$HOME/Library/Application Support/BaiduInput"

BAIDUIMBUNDLE_DIR="/Library/Input Methods"
BAIDUIMBUNDLE="$BAIDUIMBUNDLE_DIR/BaiduIM.app"

# create new config directory and set mode to 777
function CreateConfigDir(){
	mkdir -p "$NEW_CONFIG_DIR"
	chmod 777 "$NEW_CONFIG_DIR"
}

function MoveOldFileToNewDirectory(){
	folder="$1"
	if [ -e "$OLD_CONFIG_DIR/$folder" ]; then
		mv "$OLD_CONFIG_DIR/$folder" "$NEW_CONFIG_DIR"
		chmod -R 777 "$NEW_CONFIG_DIR/$folder"
	fi
}

function KillBaiduIMProcess(){
	baiduimexe="/BaiduIM.app/Contents/MacOS/BaiduIM"
	info=$(ps -A)
	pid=$(echo "${info}" | grep "$baiduimexe" | awk '{print $1}')

	if [ -n "$pid" ] ; then
	    kill -9 $pid
	fi
}

CreateConfigDir
MoveOldFileToNewDirectory "thirdskin"
MoveOldFileToNewDirectory "userdict"

for file in ucc ucq ucr ucl ; do
    if [ -e "${NEW_CONFIG_DIR}/userdict/${file}.bin" ]; then
        rm "${NEW_CONFIG_DIR}/userdict/${file}.bin"
    fi
done

rm -rf /Library/LaunchDaemons/com.baidu.baiduService.plist
rm -rf /Library/LaunchAgents/com.baidu.baiduService.plist
cp -r /Library/Preferences/BaiduIM.app/Contents/Resources/com.baidu.baiduService.plist /Library/LaunchDaemons
sudo chown root /Library/LaunchDaemons/com.baidu.baiduService.plist

rm -rf /Library/LaunchAgents/com.baidu.InputService.plist
cp -r /Library/Preferences/BaiduIM.app/Contents/Resources/com.baidu.InputService.plist /Library/LaunchAgents
#sudo chown root /Library/LaunchAgents/com.baidu.InputService.plist

KillBaiduIMProcess
rm -rf "$BAIDUIMBUNDLE"
mv /Library/Preferences/BaiduIM.app "$BAIDUIMBUNDLE_DIR"

chmod -R 777 "$BAIDUIMBUNDLE"
chmod +rx "/Library/Input Methods"

stillRunning=$(ps -ef | grep "System Preferences" | grep -v "grep")
if [ "$stillRunning" ] ; then
killall System\ Preferences
fi

killall BaiduIM
killall SystemUIServer

# 设置开机启动并立即启动该服务
open -a /bin/launchctl --args load -wF /Library/LaunchDaemons/com.baidu.baiduService.plist
#open -a /bin/launchctl --args load -wF /Library/LaunchAgents/com.baidu.InputService.plist

# 清除输入法文件的 com.apple.quarantine 标记，规避输入法出现无法打开的情况
xattr -d com.apple.quarantine "$BAIDUIMBUNDLE"
