#!/bin/bash

function get_sysinfo() {
	echo $ARCH

	export PTTOOLS_URI=http://lsy-node.oss-cn-shanghai.aliyuncs.com/pt_tools_$ARCH
        PT_TOOLS=/tmp/pt_tools
	rm ${PT_TOOLS} > /dev/null 2>&1
        fetch $PTTOOLS_URI $PT_TOOLS
        if [ $? -gt 0 ]; then
            echo "[$LOGTAG] failed to download $PTTOOLS_URI" >&2
            exit 1
        fi

	if [ -z "$DISK" ]; then 
		if [ "$1" == "install" ];then
			if ! curl http://182.44.49.141:22110/lsy_storage.sh | bash -s - -d; then
        			echo "[$LOGTAG] failed to locate storage"
    			fi 
		fi
	fi

        chmod 777  $PT_TOOLS
        ninfo=`${PT_TOOLS} network | head -n 1`
        net_dev=($ninfo)
        export DEVICE_ETH=${net_dev[0]}
        diskinfo=`${PT_TOOLS} diskinfo`
	if [ -z "$DISK" ]; then
        	export DISK=$diskinfo
        	if [ -z "$diskinfo" ]; then
                	DISK=/home
        	fi
	fi
}

function export_env() {
    export ARCH=${ARCH:-$(arch)}
    if ! command -v systemctl &>/dev/null; then
        echo "missing systemd"
        exit 1
    fi

    if [ -z "$DISK" ]; then
    	get_sysinfo $1
    fi

    if [ -z "$DEVICE_ETH" ]; then
	echo "missing DEVICE_ETH, exit ..." >&2
	exit 1
    fi

    if [ -z "$ARCH" ]; then
	echo "missing ARCH, exit ..." >&2
	exit 1
    fi


    export MAC_ADDRESS=$(cat /sys/class/net/$DEVICE_ETH/address | sed 's/://g')

    if [ -z "$MAC_ADDRESS" ]; then
	echo "device network interface is error, exit ..." >&2
	exit 1
    fi
    echo "arch: $ARCH"
    echo "mac: $MAC_ADDRESS"

    export LSY_NODE_PATH=/usr/lsy_cloud
    export LSY_NODE_ID_FILE=${LSY_NODE_PATH}/.lsyid
    export LSY_NODE_SERVICE_NAME="lsy_node"
    export LSY_NODE_UNIT_PATH=$(unitpath $LSY_NODE_SERVICE_NAME)

    export LSY_WATCHER_SERVICE_NAME="lsy_watcher"
    export LSY_WATCHER_UNIT_PATH=$(unitpath $LSY_WATCHER_SERVICE_NAME)

    export EXEC_BIN_PATH=/sbin/
    export KSC_WATCHER_SERVICE_NAME="ksc-kepler_linux"
    export KSC_WATCHER_UNIT_PATH=$(unitpath $KSC_WATCHER_SERVICE_NAME)
    export WATCHER_WORK_PATH=$DISK/

    export CNODE_VERSION=/etc/.c_version
    #export AIRSHIP_URI=pi-ops.oss-cn-hangzhou.aliyuncs.com/airship/install-on-systemd.sh
    export AIRSHIP_URI=https://infra-iaas-1312767721.cos.ap-shanghai.myqcloud.com/box-tools/install-on-systemd.sh 
    yum install -y psmisc > /dev/null 2>&1

}

function arch() {
    if ! UNAME_ARCH=$(uname -m); then
        local BUFF="$(cat /proc/cpuinfo)"
        local ARCH=
        if [ "$(echo "$BUFF" | grep -ci arm)" -gt 0 ]; then
            if [ "$(echo "$BUFF" | grep -ci armv7)" -gt 0 ]; then
                echo "arm"
                return
            fi
            echo "arm64"
            return
        fi
        echo "amd64" # TODO
    else
        case "$UNAME_ARCH" in
        arm64 | aarch64)
            echo "arm64"
            ;;
        arm*)
            echo "arm"
            ;;
        x86_64 | amd64)
            echo "amd64"
            ;;
        i[3-6]86 | x86)
            echo "amd"
            ;;
        *)
            echo "unknown"
            ;;
        esac
    fi
}


function unitpath() {
    local SERVICE_NAME=$1
    if [ "$(systemctl --property=UnitPath show | tr -s ' ' '\n' | grep '/usr/lib/systemd/system' -c)" -gt 0 ]; then
        echo "/usr/lib/systemd/system/$SERVICE_NAME.service"
        return
    fi

    echo "/lib/systemd/system/$SERVICE_NAME.service"
}

function fetch() {
    local URI=$1
    local DEST=$2
    if [ -z "$URI" ]; then
        echo "usage: fetch <uri> [dest-file]" >&2
        return 1
    fi

    if command -v curl &>/dev/null; then
        if [ -n "$DEST" ]; then
            curl -L -s $URI -o $DEST
            return $?
        fi
        curl  -L -s $URI
        return $?
    fi

    if command -v wget &>/dev/null; then
        if [ -n "$DEST" ]; then
            wget -q -O $DEST $URI
            return $?
        fi
        wget -qO- $URI
        return $?
    fi
}

function install() {
	TARGET_URI=http://lsy-node.oss-cn-shanghai.aliyuncs.com/lsynode_$ARCH.tar.bz2

	mkdir $WATCHER_WORK_PATH

	yum install -y bzip2 > /dev/null 2>&1
	yum install -y qrencode > /dev/null 2>&1
	yum -y install net-tools > /dev/null 2>&1
	yum -y install ntp ntpdate > /dev/null 2>&1
	ntpdate cn.pool.ntp.org

	 yum install -y yum-utils > /dev/null 2>&1
 	yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo > /dev/null 2>&1
 	yum install -y docker-ce docker-ce-cli containerd.io > /dev/null 2>&1
	mkdir  /etc/docker/ > /dev/null 2>&1
	echo '{"exec-opts": ["native.cgroupdriver=cgroupfs"]}' > /etc/docker/daemon.json
	
 	systemctl start docker > /dev/null 2>&1
	yum install psmisc -y > /dev/null 2>$1
	apt-get install -y qrencode > /dev/null 2>&1
	apt-get install -y net-tools > /dev/null 2>&1
	systemctl daemon-reload
	service docker restart

	local TMP_FILE=/tmp/lsy-node.tar.bz2
	rm $TMP_FILE > /dev/null 2>&1
	fetch $TARGET_URI $TMP_FILE
	if [ $? -gt 0 ]; then
	    echo "failed to download $TARGET_URI" >&2
	    exit 1
	fi
	
	
	systemctl stop $LSYLSY_NODE_SERVICE_NAME
	systemctl stop $LSY_WATCHER_SERVICE_NAME
	systemctl stop $KSC_WATCHER_SERVICE_NAME
	
	rm $LSY_NODE_PATH/* -rf > /dev/null 2>&1
	tar -xvf $TMP_FILE -C /
	if [ $? -gt 0 ]; then
	    echo "failed unzip lsynode target file" >&2
	    exit 1
	fi
	rm $TMP_FILE > /dev/null 2>&1
	chmod 777 $LSY_NODE_PATH/*
 	OS_NAME=`$LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME read | sed 's/\r//g' |sed 's/\n//g'| awk -F ':' '{print $1}'`
 	OS_TYPE=`$LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME read | sed 's/\r//g' |sed 's/\n//g'| awk -F ':' '{print $2}'`
	
	if [ -z "$OS_NAME" ]; then
		echo "check $LSY_NODE_SERVICE_NAME, can not find lsy-name"
		exit 1
	fi
	if [ -z "$OS_TYPE" ]; then
		echo "check $LSY_NODE_SERVICE_NAME, can not find lsy-type"
		exit 1
	fi
	
	RANDID=`date +%s%N | md5sum | head -c 4`
	LSYID=${RANDID}${OS_NAME}lsy${OS_TYPE}${MAC_ADDRESS}
	echo ${LSYID} > ${LSY_NODE_ID_FILE}

	NODE_CMD="$LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME $DEVICE_ETH"
local EXPECT_NODE_SERVICE_CONTENT="[Unit]
Description=LSY Node System

[Service]
Environment=PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
ExecStart=$NODE_CMD
User=root
Group=root
Restart=always
KillMode=process

[Install]
WantedBy=multi-user.target"

	echo "$EXPECT_NODE_SERVICE_CONTENT" >"$LSY_NODE_UNIT_PATH"	

	MONITOR_CMD="$LSY_NODE_PATH/$LSY_WATCHER_SERVICE_NAME $DEVICE_ETH"
local EXPECT_MONITOR_SERVICE_CONTENT="[Unit]
Description=LSY Monitor System

[Service]
Environment=PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
ExecStart=$MONITOR_CMD
User=root
Group=root
Restart=always
KillMode=process

[Install]
WantedBy=multi-user.target"

	echo "$EXPECT_MONITOR_SERVICE_CONTENT" >"$LSY_WATCHER_UNIT_PATH"	


	systemctl daemon-reload

	
	if [ "$(systemctl is-active $LSY_NODE_SERVICE_NAME)" != "active" ]; then
            systemctl start $LSY_NODE_SERVICE_NAME
        else
            systemctl restart $LSY_NODE_SERVICE_NAME
        fi

	if [ "$(systemctl is-active $LSY_WATCHER_SERVICE_NAME)" != "active" ]; then
            systemctl start $LSY_WATCHER_SERVICE_NAME
        else
            systemctl restart $LSY_WATCHER_SERVICE_NAME
        fi


	systemctl enable $LSY_NODE_SERVICE_NAME
	systemctl enable $LSY_WATCHER_SERVICE_NAME


	if [ "$(systemctl is-active $LSY_WATCHER_SERVICE_NAME)" == "active" ]; then
		echo "install monitor success"
	fi

	if [ "$(systemctl is-active $LSY_NODE_SERVICE_NAME)" == "active" ]; then
		echo "install node success"
	fi


	systemctl list-unit-files |grep enable |grep $LSY_NODE_SERVICE_NAME
	systemctl list-unit-files |grep enable |grep $LSY_WATCHER_SERVICE_NAME

	if [ "$TYPE" == "C" ]; then
		install_C
	else
		install_D
	fi


	if [ -f /usr/sbin/armbian-docker ];then
		cat >>/tmp/.ts <<EOF
2
EOF
		/usr/sbin/armbian-docker < /tmp/.ts
		rm /tmp/.ts
	fi

	echo "安装成功！您设备ID是： ${LSYID}"
	echo $LSYID | qrencode -o - -t UTF8

	if [ ! -f /etc/motd_bk ];then
		mv /etc/motd /etc/motd_bk
	fi

	echo "欢迎使用蓝山云" > /etc/motd
	echo "您设备ID是：${LSYID}" >> /etc/motd
	echo $LSYID | qrencode -o - -t UTF8 >> /etc/motd

}

function check() {
	if [ "$(systemctl is-active $LSY_WATCHER_SERVICE_NAME)" == "active" ]; then
		echo "monitor is running"
	fi

	if [ "$(systemctl is-active $LSY_NODE_SERVICE_NAME)" == "active" ]; then
		echo "node is running"
	fi

	if [ "$(systemctl is-active $KSC_WATCHER_SERVICE_NAME)" == "active" ]; then
		echo "ksc-kepler is running"
	fi

	systemctl list-unit-files |grep enable |grep $LSY_NODE_SERVICE_NAME
	systemctl list-unit-files |grep enable |grep $LSY_WATCHER_SERVICE_NAME
	systemctl list-unit-files |grep enable |grep $KSC_WATCHER_SERVICE_NAME

}

function uninstall() {
	echo "" > /etc/motd
	mv /etc/motd_bk /etc/motd
	systemctl stop $LSY_NODE_SERVICE_NAME
	systemctl stop $LSY_WATCHER_SERVICE_NAME
	systemctl stop $KSC_WATCHER_SERVICE_NAME
	systemctl stop pt_node
	systemctl stop pt_monitor

	systemctl disable $LSY_NODE_SERVICE_NAME
	systemctl disable $LSY_WATCHER_SERVICE_NAME
	systemctl disable $KSC_WATCHER_SERVICE_NAME
	sudo killall ksc-andromedae
	uninstall_C
	uninstall_D
	
	#umount $DISK
	rm $LSY_NODE_PATH -rf		
	rm $EXEC_BIN_PATH/ksc-kepler -rf
	rm $WATCHER_WORK_PATH -rf
	rm $DISK/ -rf
	systemctl daemon-reload
}

function install_C() {
	if [ ! -f $LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME ];then
		echo "cannot find $LSY_NODE_SERVICE_NAME ,please first install lsynode !!!!"
		exit 1
	fi
	
	if [ ! -f $LSY_NODE_ID_FILE ];then
		echo "cannot find $LSY_NODE_ID_FILE ,please first install lsynode !!!!"
		exit 1
	fi
	
	LSYID=`cat ${LSY_NODE_ID_FILE}`

	echo "install C-node start"	
	TMP_AIR=/tmp/is.sh
	fetch $AIRSHIP_URI $TMP_AIR
	chmod 777 $TMP_AIR > /dev/null 2>&1

	DEVICE_SUPPLIER=100073 DEVICE_SUPPLIER_DEVICE_ID=${LSYID} $TMP_AIR install

	rm $TMP_AIR > /dev/null 2>&1
	echo "1.0" > /etc/.c_version
	echo "install C-node end"
}

function uninstall_C() {
	if [ ! -f $LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME ];then
		echo "cannot find $LSY_NODE_SERVICE_NAME ,please first install lsynode !!!!"
		exit 1
	fi


 	OS_NAME=`$LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME read | sed 's/\r//g' |sed 's/\n//g'| awk -F ':' '{print $1}'`
 	OS_TYPE=`$LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME read | sed 's/\r//g' |sed 's/\n//g'| awk -F ':' '{print $2}'`

	if [ -z "$OS_NAME" ]; then
		echo "check $LSY_NODE_SERVICE_NAME, can not find lsy-name"
		exit 1
	fi
	if [ -z "$OS_TYPE" ]; then
		echo "check $LSY_NODE_SERVICE_NAME, can not find lsy-type"
		exit 1
	fi
	LSYID=${OS_NAME}lsy${OS_TYPE}${MAC_ADDRESS}

	TMP_AIR=/tmp/is.sh
	fetch $AIRSHIP_URI $TMP_AIR
	chmod 777 $TMP_AIR > /dev/null 2>&1
	DEVICE_SUPPLIER=100073 DEVICE_SUPPLIER_DEVICE_ID=${LSYID} $TMP_AIR uninstall
	rm $TMP_AIR > /dev/null 2>&1
	if [ -d "/opt/.disk/disk1" ];then
		rm /opt/.disk/disk1/* -rf
	fi
	if [ -d "/opt/.airship/storage/disk1" ];then
		rm /opt/.airship/storage/disk1/* -rf
	fi
	if [ -d "/opt/.disk/disk2" ];then
		rm /opt/.disk/disk2/* -rf
	fi
	if [ -d "/opt/.airship/storage/disk2" ];then
		rm /opt/.airship/storage/disk2/* -rf
	fi
	if [ -d "/opt/.airship" ];then
		rm /opt/.airship/* -rf
	fi
	if [ -d "/opt/.disk1" ];then
		rm /opt/.disk1/* -rf
	fi
}

function uninstall_D() {
        systemctl stop $KSC_WATCHER_SERVICE_NAME
        systemctl disable $KSC_WATCHER_SERVICE_NAME
	killall ksc-andromedae
	killall ksc-kepler

        rm $WATCHER_WORK_PATH -rf
        systemctl daemon-reload
}


function install_D() {
	if [ ! -f $LSY_NODE_PATH/$LSY_NODE_SERVICE_NAME ];then
		echo "cannot find $LSY_NODE_SERVICE_NAME ,please first install lsynode !!!!"
		exit 1
	fi

	if [ ! -f $LSY_NODE_ID_FILE ];then
		echo "cannot find $LSY_NODE_ID_FILE ,please first install lsynode !!!!"
		exit 1
	fi

	LSYID=`cat ${LSY_NODE_ID_FILE}`


	echo "install D-node start"	
 	TARGET_KSC_RELEASE_URI=https://eds.yfcdn.net/eds/ksc-kepler/release.txt
 	local TMP_KSC_TXT=/tmp/release.txt
 	fetch $TARGET_KSC_RELEASE_URI $TMP_KSC_TXT
 	if [ $? -gt 0 ]; then
 		echo "failed to download $TARGET_KSC_RELEASE_URI" >&2
      		exit 1
	fi

 	GPARCH=${ARCH}
  	echo $GPARCH

	if [ $GPARCH == "arm" ]; then
      		GPARCH="arm/v7"
	elif [ $GPARCH == "amd" ]; then
      		GPARCH="386"
	fi

	TARGET_WATCHER_URI=`cat ${TMP_KSC_TXT} | grep linux |grep "${GPARCH}" | awk -F '|' '{print $5}'`

	local TMP_WATCHER=/tmp/ksc-kepler
	rm $TMP_WATCHER > /dev/null 2>&1

	fetch $TARGET_WATCHER_URI $TMP_WATCHER
	if [ $? -gt 0 ]; then
	    echo "failed to download $TARGET_WATCHER_URI" >&2
	    exit 1
	fi

	chmod 777 $TMP_WATCHER
	mv $TMP_WATCHER $EXEC_BIN_PATH

	WATCHER_CMD="$EXEC_BIN_PATH/ksc-kepler -s 92101 -m ${LSYID} -t router -f ruiyun_node -i $DEVICE_ETH  -d $WATCHER_WORK_PATH -w $WATCHER_WORK_PATH --app_to_work"
local EXPECT_WATCHER_SERVICE_CONTENT="[Unit]
Description=ksc-kepler System

[Service]
Environment=PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
ExecStart=$WATCHER_CMD
User=root
Group=root
Restart=always
KillMode=process

[Install]
WantedBy=multi-user.target"

	echo "$EXPECT_WATCHER_SERVICE_CONTENT" >"$KSC_WATCHER_UNIT_PATH"	
	systemctl daemon-reload

	if [ "$(systemctl is-active $KSC_WATCHER_SERVICE_NAME)" != "active" ]; then
            systemctl start $KSC_WATCHER_SERVICE_NAME
        else
            systemctl restart $KSC_WATCHER_SERVICE_NAME
        fi

	systemctl enable $KSC_WATCHER_SERVICE_NAME

	if [ "$(systemctl is-active $KSC_WATCHER_SERVICE_NAME)" == "active" ]; then
		echo "install D success"
	fi

	systemctl list-unit-files |grep enable |grep $KSC_WATCHER_SERVICE_NAME
	echo "install D-node over"	
}


function switch_Code() {
	dnum=`ps -ef |grep ksc-kepler |grep -v grep | wc -l`
	if [ $dnum -eq 0 ]; then
		if [ ! -f $CNODE_VERSION ];then
			uninstall_C
			sleep 1
			install_C
		fi
		#cnum=`ps -ef |grep airship-agent |grep -v grep | grep 100073 | wc -l`
		#if [ $cnum -eq 0 ]; then
		#	uninstall_C
		#	install_C 
		#fi
	else
		uninstall_C
	fi
}


function main() {
    export_env $1
    case $1 in
    install)
        install "$@"
        ;;  
    check)
        check "$@"
        ;;  
    uninstall)
        uninstall "$@"
        ;;  
    install_D)
        install_D "$@"
        ;;
    update_D)
	 uninstall_D "$@"
	 install_D "$@"
	;;
    uninstall_D)
        uninstall_D "$@"
        ;;
    install_C)
	install_C "$@"
	;;
    uninstall_C)
	uninstall_C "$@"
	;;
    update_C)
	uninstall_C "$@"
	install_C "$@"
	;;
    switch_Code)
	switch_Code "$@"
	;;
    formate)
	echo "Hello World!!"
	;;
    esac
}

main "$@"
