#!/bin/sh

dnspod_enable=$1
dnspod_ak=$2
dnspod_sk=$3
dnspod_domain=$4
dnspod_name=$5
ip=$6
dnspod_record_id=$7
my=$8

log_file="/var/log/koolddns.log"

DATE=$(date +'%Y-%m-%d %H:%M:%S')
timestamp=`date -u "+%Y-%m-%dT%H%%3A%M%%3A%SZ"`

check_dnspod() {
	echo "$DATE: 当前路由IP: ${ip}" >> $log_file
	current_ip=`echo $query_result | sed 's/.*,"Value":"\([0-9\.]*\)",.*/\1/'`
	isip=`echo $current_ip | grep -E "([0-9]{1,3}[\.]){3}[0-9]{1,3}"`
	[ -n "$isip" ] && echo "$DATE: 远程解析IP: ${current_ip}" >> $log_file
	if [ "$ip" = "$current_ip" ];then
		echo "$DATE: IP未改变，无需更新" >> $log_file
		exit 0
	else
		echo "$DATE: 更新中..." >> $log_file  
	fi
}

urlencode() {
    # urlencode <string>
    local length="${#1}"
    i=0
    out=""
    for i in $(awk "BEGIN { for ( i=0; i<$length; i++ ) { print i; } }")
    do
        local c="${1:$i:1}"
        case $c in
            [a-zA-Z0-9._-]) out="$out$c" ;;
            *) out="$out`printf '%%%02X' "'$c"`" ;;
        esac
        i=$(($i + 1))
    done
    echo -n $out
}

send_request() {
	local args="login_token=$dnspod_ak,$dnspod_sk&Format=json&$2"
	/usr/bin/wget --no-check-certificate --post-data "$args" "https://dnsapi.cn/$1" -O /tmp/ddnspod
	isinvalid=`cat /tmp/ddnspod | egrep -C8 "<message>" | grep "<message>" | awk -F'>' '{print $2}' | awk -F'<' '{print $1}' | grep invalid`
	if [ -n "$isinvalid" ];then
		echo "$DATE: token更新0！" >> $log_file
		exit 0
	fi
}

get_recordid() {
   egrep -C8 "<name>$dnspod_name</name>"|grep "<id>"|awk -F'>' '{print $2}'|awk -F'<' '{print $1}'
}

get_recordid2() {
   grep 'id'|awk -F'>' '{print $2}'|awk -F'<' '{print $1}' 
}

query_recordid() {
	send_request "Record.List" "domain=$dnspod_domain"
}

update_record() {
	send_request "Record.Ddns" "domain=$dnspod_domain&record_id=$1&record_line=默认&sub_domain=$dnspod_name&value=$ip"
}

add_record() {
	 send_request "Record.Create" "domain=$dnspod_domain&sub_domain=$dnspod_name&record_type=A&record_line=默认&value=$ip"
}

go_record() {
	if [ "$dnspod_record_id" = "" ];then
		query_recordid
		dnspod_record_id=`cat /tmp/ddnspod | get_recordid`
	fi
	
	if [ "$dnspod_record_id" = "" ];then
		add_record
		dnspod_record_id=`cat /tmp/ddnspod | get_recordid2`
	else
		update_record $dnspod_record_id
	fi
	
	# save to file
	if [ "$dnspod_record_id" = "" ];then
		echo "$DATE: 更新出错,请检查设置！" >> $log_file
		exit 0 
	else
		uci set koolddns.$my.record_id=$dnspod_record_id
		uci commit
		echo "$DATE: 更新成功！($ip)" >> $log_file 
	fi  
}


if [ "$dnspod_enable" != "1" ]; then
    echo "$DATE: dnspod没有开启！" >> $log_file
else
	query_recordid
    query_result=`cat /tmp/ddnspod`
    check_dnspod
    go_record
fi
