#!/bin/bash
local_dir="/opt/packer"
sys_log="/var/log/install.log"
huayunrepo="http://220.231.216.27/cmigrate/"
ver="2.4.0"

INSTALLSUCCEES="0"
INSTALLFAILED="1"
REPOACCESSABLE="2"
REPONOTACCESSABLE="3"
NOSUITABLEPACKAGE="4"

log () {
	date=`date +"%Y-%m-%d %H:%M:%S"`
	para=$1
	echo "[$date] $1" >> $sys_log
}

update_datto () {
	uname=`uname -a`
	if [[ "$uname" =~ "x86_64" ]];then
		log "update datto for x86_64"
	else
		log "update datto only works for x86_64"
		echo "$INSTALLSUCCESS"
		return
	fi

	cd /usr/src
	dattobd_dir=""
	for f in `ls`
	do
		if [[ "$f" =~ "dattobd" ]]; then
			dattobd_dir="$f"
			break
		fi
	done
	if [ -z "$dattobd_dir" ]; then
		log "can not find dattobd dir in /usr/src"
		echo "$INSTALLFAILED"
		return
	fi

	version=`echo $dattobd_dir | cut -d "-" -f 2`
	log "dattobd version is $version"
	cd "$dattobd_dir"
	ret=`cat dattobd.c | grep "This Version Fixed Kernel Panic in cow_read_mapping"`
	if [ ! -z "$ret" ]; then
		log "patch already installed!"
	else
		url="$huayunrepo/datto/patch/$version/0001-fix-kernel-panic-in-cow_read_mapping.patch"
		if [ -f "0001-fix-kernel-panic-in-cow_read_mapping.patch" ]; then
			rm -rf 0001-fix-kernel-panic-in-cow_read_mapping.patch
		fi
		if [ -f "$local_dir/$version/0001-fix-kernel-panic-in-cow_read_mapping.patch" ];then
			cp $local_dir/$version/0001-fix-kernel-panic-in-cow_read_mapping.patch ./
		else
			wget $url -O ./0001-fix-kernel-panic-in-cow_read_mapping.patch >> $sys_log 2>&1
			if [ ! -f "0001-fix-kernel-panic-in-cow_read_mapping.patch" ]; then
				log "download patch failed"
				echo "$INSTALLFAILED"
				return
			fi
		fi

		patch < 0001-fix-kernel-panic-in-cow_read_mapping.patch >> $sys_log 2>&1
		if [ $? -ne 0 ]; then
			log "patch failed"
			echo "$INSTALLFAILED"
			return
		fi
	fi

	modprobe -r dattobd >> $sys_log 2>&1
	ret=`lsmod | grep dattobd`
	if [ ! -z "$ret" ]; then
		log "modprobe -r failed"
		echo "$INSTALLFAILED"
		return
	fi

	dkms remove -m dattobd -v $version --all >> $sys_log 2>&1
	ret=`dkms status | grep "dattobd"`
	if [ ! -z "$ret" ]; then
		log "remove dattobd from dkms failed($ret)"
	        ehco "$INSTALLFAILED"
		return
	fi

	/usr/lib/dkms/common.postinst dattobd $version >> $sys_log 2>&1
	if [ $? -ne 0 ]; then
		log "dkms install failed"
		echo "$INSTALLFAILED"
		return
	fi

	modprobe dattobd >> $sys_log 2>&1
	if [ $? -ne 0 ]; then
		log "modprobe failed"
		echo "$INSTALLFAILED"
		return
	fi

	echo "$INSTALLSUCCESS"
}

install() {
	echo "update datto"
	ret=`update_datto`
	if [ "$ret" = "$INSTALLFAILED" ];then
		echo "Install terminated, update datto failed, please check log for more details"
		exit
	elif [ "$ret" = "$INSTALLSUCCESS" ];then
		echo "Update datto success"
	else
		echo "Update datto failed due to unknown reasons, please check log for more details"
		exit
	fi
}

main () {
	echo "Update dattobd start, more details can be found in $sys_log"
	install
	echo "Successful update!"
}

main
