#!/bin/bash

# 定义颜色
RED='\033[0;31m' #红色
GREEN='\033[0;32m' #绿色
BLUE='\033[0;34m' #蓝色
CYAN='\033[0;36m' #青色
YELLOW='\033[0;33m' #黄色
PURPLE='\033[0;35m' #紫色
NC='\033[0m' # 清除颜色
L_PURPLE='\033[1;35m' # 亮紫色
L_GREEN='\033[1;32m'  # 亮绿色
L_RED='\033[1;31m'    # 亮红色
scriptfilepath=$(cd "$(dirname "$0")"; pwd)/$(basename $0)
read -p "$(echo -e "\n${L_PURPLE}注意：${NC} ${L_RED}\n\n由于使用了root用户权限，群晖及NAS重要系统请慎用此脚本，此脚本是安装成系统服务运行，适合VPS云服务器安装，重要存储系统请使用Docker，非要使用此脚本安装在NAS里请务必先查看此脚本内容（${YELLOW}${scriptfilepath}${NC}${L_RED}）是否会对NAS造成影响或不兼容！${NC}\n\n${L_PURPLE}请确认是否需要安装？输入${NC}${L_GREEN} yes ${NC}${L_PURPLE}表示已知悉继续执行：${NC}") " confirm
confirm=$(echo "$confirm" | tr '[:upper:]' '[:lower:]')
if [ "$confirm" != "yes" ]; then
    echo -e "\n${L_RED}用户退出，${YELLOW}${scriptfilepath}${NC}${L_RED}脚本将终止执行。${NC}\n"
    exit 1
fi
clear

# 打印带颜色的 NetLink Banner
echo -e "\n\n${RED} ██████   █████           █████    █████        ███             █████     ${NC}"
echo -e "${GREEN}▒▒██████ ▒▒███           ▒▒███    ▒▒███        ▒▒▒             ▒▒███      ${NC}"
echo -e "${BLUE} ▒███▒███ ▒███  ▒██████  ███████   ▒███       ▒▒███ ▒▒████████  ▒███ █████${NC}"
echo -e "${CYAN} ▒███▒▒███▒███ ▒███ ▒███ ▒▒███▒    ▒███        ▒███  ▒███▒▒███  ▒███▒▒███ ${NC}"
echo -e "${YELLOW} ▒███ ▒▒██████ ▒███████   ▒███     ▒███        ▒███  ▒███ ▒███  ▒██████▒  ${NC}"
echo -e "${PURPLE} ▒███  ▒▒█████ ▒███▒▒▒    ▒███ ███ ▒███      █ ▒███  ▒███ ▒███  ▒███▒▒███ ${NC}"
echo -e "${RED} █████  ▒▒█████ ▒██████   ▒▒█████  ███████████ █████ ████ █████ ████ █████${NC}"
echo -e "${GREEN}▒▒▒▒▒    ▒▒▒▒▒  ▒▒▒▒▒▒     ▒▒▒▒▒  ▒▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒ ▒▒▒▒▒ ${NC}"
echo -e "\n${CYAN}                项目地址：https://github.com/rustp2p/NetLink   \n\n${NC}"

APP="netlink"
PRJ="rustp2p/NetLink"
# 检查系统是否使用 systemd
if [[ "$(ps -p 1 -o comm=)" == "systemd" || -d /run/systemd/system ]]; then
    # 如果使用 systemd，则继续执行
    :
else
    echo -e "\n当前系统没有使用${L_RED} systemd ${NC}系统服务，无法使用此脚本！"
    exit 1
fi
if [ "$(id -u)" != "0" ]; then
  echo -e "${L_RED}需要在root用户权限下运行此安装脚本${YELLOW}${scriptfilepath}${NC}${L_RED}！${NC}\n"
  exit 1
fi

cputype=$(uname -ms | tr ' ' '_' | tr '[A-Z]' '[a-z]')
[ -n "$(echo $cputype | grep -E "linux.*armv.*")" ] && cpucore="arm"
[ -n "$(echo $cputype | grep -E "linux.*armv7.*")" ] && [ -n "$(cat /proc/cpuinfo | grep vfp)" ] && cpucore="armv7"
[ -n "$(echo $cputype | grep -E "linux.*aarch64.*|linux.*armv8.*")" ] && cpucore="aarch64"
[ -n "$(echo $cputype | grep -E "linux.*86.*")" ] && cpucore="i386"
[ -n "$(echo $cputype | grep -E "linux.*86_64.*")" ] && cpucore="x86_64"
if [ -n "$(echo $cputype | grep -E "linux.*mips.*")" ] ; then
	mipstype=$(echo -n I | hexdump -o 2>/dev/null | awk '{ print substr($2,6,1); exit}') ##通过判断大小端判断mips或mipsle
	[ "$mipstype" = "0" ] && cpucore="mips" || cpucore="mipsel"
fi
[ -z "$cputype" ] && echo -e "${L_RED}无法识别当前CPU架构！脚本退出，无法安装！${NC}\n" && exit 1
 
dowload() {
curltest=`which curl`
user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
proxys="
https://github.moeyy.xyz/
https://gh.llkk.cc/
https://mirror.ghproxy.com/
https://ghproxy.net/
https://dl.cnqq.cloudns.ch/
"
tag=$1
ver="$(/opt/${APP}/${APP} -V 2>/dev/null | awk {'print $2'})"
if [ -z "$tag" ] ; then
	echo -e "\n${L_PURPLE}开始从GitHub获取${APP}的最新版本号...${NC}\n"
	if [ -z "$curltest" ] || [ ! -s "`which curl`" ] ; then
		tag="$( wget -T 5 -t 3 --user-agent "$user_agent" --max-redirect=0 --output-document=-  https://api.github.com/repos/${PRJ}/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"
		[ -z "$tag" ] && tag="$( wget -T 5 -t 3 --user-agent "$user_agent" --quiet --output-document=-  https://api.github.com/repos/${PRJ}/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"
		[ -z "$tag" ] && tag="$( wget --no-check-certificate -T 5 -t 3 --user-agent "$user_agent" --quiet --output-document=-  https://dl.cnqq.cloudns.ch/https://api.github.com/repos/${PRJ}/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"
	else
		tag="$( curl --connect-timeout 3 --user-agent "$user_agent"  https://api.github.com/repos/${PRJ}/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"
		[ -z "$tag" ] && tag="$( curl -L --connect-timeout 3 --user-agent "$user_agent" -s  https://api.github.com/repos/${PRJ}/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"
		[ -z "$tag" ] && tag="$( curl -Lk --connect-timeout 5 --user-agent "$user_agent" -s  https://dl.cnqq.cloudns.ch/https://api.github.com/repos/${PRJ}/releases/latest  2>&1 | grep 'tag_name' | cut -d\" -f4 )"	
	fi
fi
[ -z "$tag" ] && echo -e "\n${L_RED}未获取到${APP}的版本号，请手动指定版本号${NC}\n" && return 1
if [ "$ver"x = "$tag"x ] ; then
	echo -e "${L_PURPLE}当前${YELLOW}${APP}${NC}${L_PURPLE}版本${YELLOW} ${ver} ${NC}${L_PURPLE}已是最新版本，无需更新！${NC}\n"
	exit 0
fi
case "${cpucore}" in 
	"mipsel") url="netlink-mipsel-unknown-linux-musl-${tag}.tar.gz"
	;;
	"mips") url="netlink-mips-unknown-linux-musl-${tag}.tar.gz"
	;;
	"x86_64") url="netlink-x86_64-unknown-linux-musl-${tag}.tar.gz"
	;;
	"i386") echo -e "${L_RED}当前CPU架构 $(uname -m) 不支持！脚本退出，无法安装！${NC}\n" && exit 0
	;;
	"aarch64") url="netlink-aarch64-unknown-linux-musl-${tag}.tar.gz"
	;;
	"armv7") url="netlink-armv7-unknown-linux-musleabi-${tag}.tar.gz"
	;;
	"arm") url="netlink-arm-unknown-linux-musleabi-${tag}.tar.gz"
	;;
esac
echo -e "${L_PURPLE}开始下载${YELLOW}${APP}${NC}${L_PURPLE}-${YELLOW}${tag}${NC}${L_PURPLE}版本${NC}\n"
for proxy in $proxys ; do
	echo -e "${L_PURPLE}下载${YELLOW}${proxy}https://github.com/${PRJ}/releases/download/${tag}/${url} ${NC}${L_PURPLE}到${YELLOW} /tmp/${APP}.tar.gz ${NC}\n"
	curl -#Lkso "/tmp/${APP}.tar.gz" "${proxy}https://github.com/${PRJ}/releases/download/${tag}/${url}" || wget --no-check-certificate -q -O "/tmp/${APP}.tar.gz" "${proxy}https://github.com/${PRJ}/releases/download/${tag}/${url}"
	if [ "$?" = 0 ] ; then
		echo -e "${L_PURPLE}下载完成${YELLOW}/tmp/${APP}.tar.gz${NC}${L_PURPLE}开始解压...${NC}\n"
		rm /tmp/${APP} >/dev/null 2>&1
		tar -zxf /tmp/${APP}.tar.gz -C /tmp/
		rm /tmp/${APP}.tar.gz >/dev/null 2>&1
		if [ ! -f "/tmp/${APP}" ]; then
			echo -e "\n${L_RED}解压失败，可能下载文件不完整${NC}"
			return 1
		else
			chmod +x /tmp/${APP}
			dlmd5=$(md5sum /tmp/${APP} | awk '{print $1}')
			if [ $(($(/tmp/${APP} -h | wc -l))) -gt 3 ] ; then
				echo -e "${L_PURPLE}解压完成，替换${YELLOW}/tmp/${APP}${NC}${L_PURPLE}到${YELLOW}/opt/${APP}/${APP}${NC}\n"
				mv -f /tmp/${APP} /opt/${APP}/${APP}
				ln -sf /opt/${APP}/${APP} /usr/bin/${APP}
				md5=$(md5sum "/opt/${APP}/${APP}" | awk '{print $1}')
				if [ "$dlmd5"x = "$md5"x ] ; then
					echo -e "${L_PURPLE}下载${YELLOW}${tag}${NC}${L_PURPLE}成功${NC}！\n"
					break
					return 0
				fi
			fi
		 fi
	fi
done

}

install() {
mkdir -p /opt/${APP}
app_ser="/etc/systemd/system/${APP}.service"
if [ ! -f "/opt/${APP}/${APP}" ] ; then
	echo -e "${L_RED}没有发现主程序${YELLOW}/opt/${APP}/${APP}${NC}${L_RED}开始下载...${NC}\n"
	dowload
	if [ $? -eq 0 ] ; then
		echo -e "${L_PURPLE}下载主程序${YELLOW}/opt/${APP}/${APP}${NC}${L_PURPLE}成功${NC}\n"
		
else
		echo -e "${L_RED}下载失败，请检查！${NC}\n"
		exit 0
fi
fi
export LANG="zh_CN.utf8"
if [ ! -f "$app_ser" ] ; then
	echo -e "${L_PURPLE}创建系统服务文件 ${YELLOW}/etc/systemd/system/${APP}.service${NC}\n\n"
	/opt/${APP}/${APP} -h
	echo -e "\n "
	read -p  "请参考上方的帮助信息，输入你的启动参数（直接填写参数即可 不用填写程序名），如果使用配置文件启动，配置文件要使用绝对路径（Ctrl + C 退出)： " CMD
	cat >$app_ser <<EOF
[Unit]
Description=${APP} Service
Wants=network.target
After=network.target network.service
StartLimitIntervalSec=0

[Service]
WorkingDirectory=/opt/${APP}
ExecStart=${APP} ${CMD}
Restart=always
RestartSec=3
Environment="LANG=zh_CN.utf8"

[Install]
WantedBy=multi-user.target
EOF
else
	echo -e "${L_RED}发现已有系统服务文件 ${YELLOW}/etc/systemd/system/${APP}.service${NC}${L_RED} ，脚本退出，请卸载后重新安装${NC}\n"
	cat /etc/systemd/system/${APP}.service
fi

if [ ! -L "/opt/${APP}/${APP}.service" ] ; then
	ln -sf /etc/systemd/system/${APP}.service /opt/${APP}/${APP}.service
fi
echo -e "${L_PURPLE}后续修改启动参数，请编辑${YELLOW}/opt/${APP}/${APP}.service${NC} ${L_PURPLE}即可${NC}\n"
systemctl daemon-reload
echo -e "${L_PURPLE}如果使用了配置文件启动，请先创建好配置文件，再启动${NC}\n"
read -p  "是否立即启动 y 或 n  请输入：" Start
Start=$(echo "${Start}" | tr '[:upper:]' '[:lower:]' | sed 's/ //g')
if [ "$Start" = "y" ]; then
	echo -e "${L_PURPLE}安装已完成！设置开机自启，并启动...${NC}\n"
	systemctl enable ${APP} >/dev/null 2>&1
	systemctl start ${APP}
else
    echo -e "${L_PURPLE}安装已完成！稍候请自行输入命令启动服务，还需要配置开机自启 ${YELLOW}systemctl enable ${APP}${NC}\n"
fi 
echo -e "${L_PURPLE}修改${APP}.service文件后重载配置：${NC} ${L_GREEN}systemctl daemon-reload ${NC}\n"
echo -e "${L_PURPLE}设置开机启动：${NC} ${L_GREEN}systemctl enable ${APP}${NC}"
echo -e "${L_PURPLE}启动服务命令：${NC} ${L_GREEN}systemctl start ${APP}${NC}"
echo -e "${L_PURPLE}停止服务命令：${NC} ${L_GREEN}systemctl stop ${APP}${NC}"
echo -e "${L_PURPLE}重启服务命令：${NC} ${L_GREEN}systemctl restart ${APP}${NC}"
echo -e "${L_PURPLE}取消开机启动：${NC} ${L_GREEN}systemctl disable ${APP}${NC}\n"
echo -e "${L_PURPLE}查看运行状态：${NC} ${L_GREEN}systemctl status ${APP}${NC}\n"
echo -e "${YELLOW}注意防火墙放行服务端口，默认服务端口是TCP UDP 的 23333 ${NC}\n"
}

update() {
echo -e "${L_PURPLE}1：${NC} ${L_GREEN}更新GitHub最新版本${NC}\n"
echo -e "${L_PURPLE}2：${NC} ${L_GREEN}手动指定已发布的版本${NC}\n"
read -p  "请输入对应数字： " tag
if [ ! -z "$tag" ] && [ "$tag" = "1" ] ; then
	dowload
elif [ ! -z "$tag" ] && [ "$tag" = "2" ] ; then
	read -p  "请输入GitHub已发布的版本： " tag
	if [ -z "$tag" ] ; then
		echo -e "\n${L_RED}输入为空，更新GitHub最新版本${NC}\n"
		dowload
	else
		tag="$(echo $tag | tr -d ' ')"
		dowload "$tag"
	fi
elif [ -z "$tag" ] ; then
	dowload
fi
if [ $? -eq 0 ] ; then
    echo -e "${L_PURPLE}更新成功${NC}\n"
    systemctl stop ${APP} >/dev/null 2>&1
    systemctl start ${APP} >/dev/null 2>&1
else
    echo -e "${L_RED}更新失败，请检查${NC}\n"
fi
}

uninstall() {
echo -e "\n开始卸载${L_PURPLE}${APP}${NC}...\n"
systemctl disable ${APP} >/dev/null 2>&1
systemctl stop ${APP} >/dev/null 2>&1
echo -e "删除${L_PURPLE}${APP}${NC}相关文件..."
rm -rf /usr/bin/${APP} /etc/systemd/system/${APP}.service /opt/${APP}/ >/dev/null 2>&1
systemctl daemon-reload
echo -e "\n${L_GREEN}卸载${YELLOW}${APP}${NC}${L_GREEN}完成，江湖有缘再见！${NC}\n"

}

status() {
echo -e "\n执行${YELLOW}systemctl status ${APP}${NC}\n"
systemctl status ${APP}
exit 0
}
mkdir -p /opt/${APP}
echo -e "${L_PURPLE}1：${NC} ${L_GREEN}安装${NC}"
echo -e "${L_PURPLE}2：${NC} ${L_GREEN}更新${NC}"
echo -e "${L_PURPLE}3：${NC} ${L_GREEN}卸载${NC}"
echo -e "${L_PURPLE}4：${NC} ${L_GREEN}状态${NC}\n"
read -p  "请输入对应数字： " main
case "${main}" in 
	"1") install
	;;
	"2") update
	;;
	"3") uninstall
	;;
	"4") status
	;;
	*) echo -e "\n${L_RED}输入错误，用户退出，脚本${YELLOW}${scriptfilepath}${NC}${L_RED}终止执行。${NC}\n" ; exit 0
	;;
esac



