#!/bin/sh

PLUGIN_ID="smartdns"
MODEL=`uname -m`
INSTALL_DIR="/userdisk/appdata/${PLUGIN_ID}"

check_model() {
	if [ "$MODEL" != "aarch64" ];then
		echo "目前仅支持aarch64！"
		return 1
	fi
	
	return 0
}

install() {
	echo "开始安装..."
	
	if [ -f "${INSTALL_DIR}/smartdns" ];then
		echo "检测到已经安装，退出"
		return 1
	fi
	
	wget -q http://down.asdi998.com/AX6/smartdns.tar.gz -O /tmp/smartdns.tar.gz
	[ ! -d "${INSTALL_DIR}" ] && mkdir ${INSTALL_DIR}
	tar xzvf /tmp/smartdns.tar.gz -C ${INSTALL_DIR} 1>/dev/null
	cp $0 ${INSTALL_DIR}/install.sh
	
	chown -R root:root ${INSTALL_DIR}
	chmod u+x ${INSTALL_DIR}/smartdns
	chmod u+x ${INSTALL_DIR}/smartdns.sh
	chmod u+x ${INSTALL_DIR}/S99smartdns
	
	local link_script="/etc/rc.d/S99smartdns"
	ln -sf ${INSTALL_DIR}/S99smartdns ${link_script}
	
	/bin/sh ${INSTALL_DIR}/smartdns.sh start
	
	echo "安装完成！"
	return 0
}


uninstall() {
	echo "开始卸载..."
	
	if [ ! -d "${INSTALL_DIR}" ];then
		echo "检测到安装目录不存在，退出"
		return 1
	fi

	/bin/sh ${INSTALL_DIR}/smartdns.sh stop
    
	local link_script="/etc/rc.d/S99smartdns"
    [ -h "${link_script}" ] && rm ${link_script}
	
	if [ -d "${INSTALL_DIR}" ];then
        rm -r "${INSTALL_DIR}"/* 1>/dev/null 2>&1
		rm -r "${INSTALL_DIR}" 1>/dev/null 2>&1
    fi
	
	echo "卸载完成！"
	return 0
}

check_model
[ "$?" != "0" ] && return 1
[ "$1" == "install" ] && install
[ "$1" == "uninstall" ] && uninstall
