#!/bin/sh

export KSROOT=/koolshare
source $KSROOT/scripts/base.sh
alias echo_date='echo 【$(date +%Y年%m月%d日\ %X)】:'
LOG_FILE=/tmp/upload/merlinclash_log.txt

get(){
	a=$(echo $(dbus get $1))
	a=$(echo $(dbus get $1))
	echo $a
}

get_list(){
	b=$(echo $(dbus list $1 | cut -d "=" -f $2 | cut -d "_" -f $3 | sort -n))
	b=$(echo $(dbus list $1 | cut -d "=" -f $2 | cut -d "_" -f $3 | sort -n))
	echo $b
}

### Base64解码函数
b(){
	if [ -f "/koolshare/bin/base64_decode" ]; then #HND有这个
		base=base64_decode
		echo $base
	elif [ -f "/bin/base64" ]; then #HND是这个
		base=base64
		echo $base
	elif [ -f "/koolshare/bin/base64" ]; then #网件R7K是这个
		base=base64
		echo $base
	elif [ -f "/sbin/base64" ]; then
		base=base64
		echo $base
	else
		echo_date "【错误】固件缺少base64decode文件，无法正常订阅，直接退出" >> $LOG_FILE
		echo_date "解决办法请查看MerlinClash Wiki" >> $LOG_FILE
		echo BBABBBBC >> $LOG_FILE
		exit 1
	fi
}

decode_url_link(){
	local link=$1
	local len=$(echo $link | wc -L)
	local mod4=$(($len%4))
	b64=$(b)
	if [ "$mod4" -gt "0" ]; then
		local var="===="
		local newlink=${link}${var:$mod4}
		echo -n "$newlink" | sed 's/-/+/g; s/_/\//g' | $b64 -d 2>/dev/null
	else
		echo -n "$link" | sed 's/-/+/g; s/_/\//g' | $b64 -d 2>/dev/null
	fi
}

urldecode() {
    # 先处理 + 号转为空格
    local encoded="${1//+/ }"
    # 将 %XX 转为 \xXX，然后让printf解释
    printf "$(echo "$encoded" | sed 's/%\([0-9a-fA-F][0-9a-fA-F]\)/\\x\1/g')"
}

download() {
	local ua=$1
    local url=$2
    local save_As=$3

    if [ -z "$url" ] || [ -z "$save_As" ];then
        return 1
    fi

	if [ -n "$ua" ]; then
        curl -sSkL --connect-timeout 30 --max-time 120 --user-agent "$ua" "$url" -o "$save_As"
    else
        curl -sSkL --connect-timeout 30 --max-time 120 "$url" -o "$save_As"
    fi

	if [ $? -ne 0 ]; then
		return 1
	fi

	if [ ! -s "$save_As" ]; then
		return 1
	fi

	return 0
}

### 文件锁
set_lock(){
	mkdir -p /tmp/lock
	lf=$(dbus get merlinclash_lockfile)
	lcfiletmp=/tmp/lock/$lf.txt
	echo_date "Magic Catling 前一进程锁文件:$lcfiletmp"  >> $LOG_FILE

	lc=$$	
	merlinclash_lockfile="$lc"
	dbus set merlinclash_lockfile="$merlinclash_lockfile"
	lcfile1=/tmp/lock/$lc.txt
		echo_date "Magic Catling 创建本新进程锁文件${lcfile1}" >> $LOG_FILE 
		touch $lcfile1	
		i=60
		echo_date "Magic Catling 将本任务pid写入lockfile:$merlinclash_lockfile" >> $LOG_FILE
		echo $$ > ${lcfile1}

		while [ $i -ge 0 ]; do
			if [ -e ${lcfiletmp} ] && kill -0 `cat ${lcfiletmp}`; then 
				echo_date "Magic Catling: $merlinclash_lockfile 锁进程中" >> $LOG_FILE
				echo $$ > ${lcfile1}
				sleep 5s
			else
				let i=0
				echo_date "Magic Catling: 上个重启进程文件锁解除" >> $LOG_FILE
			fi
			let i--
		done
		
		# 确保退出时，锁文件被删除 
		trap "rm -rf ${lcfile1}; exit" INT TERM EXIT 
		
		echo $$ > ${lcfile1} 
		echo_date "Magic Catling: 重新创建进程锁文件${lcfile1}" >> $LOG_FILE

}

unset_lock(){
	rm -rf ${lcfile1} 
}
