#!/bin/sh

aliddns_enable=$1
aliddns_ak=$2
aliddns_sk=$3
aliddns_domain=$4
aliddns_name=$5
ip=$6
aliddns_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_aliddns() {
	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="AccessKeyId=$aliddns_ak&Action=$1&Format=json&$2&Version=2015-01-09"
	local hash=$(urlencode $(echo -n "GET&%2F&$(urlencode $args)" | openssl dgst -sha1 -hmac "$aliddns_sk&" -binary | openssl base64))
	wget -qO- "http://alidns.aliyuncs.com/?$args&Signature=$hash" 2> /dev/null
}

get_recordid() {
	grep -Eo '"RecordId":"[0-9]+"' | cut -d':' -f2 | tr -d '"'
}

query_recordid() {
	send_request "DescribeSubDomainRecords" "SignatureMethod=HMAC-SHA1&SignatureNonce=$timestamp&SignatureVersion=1.0&SubDomain=$(urlencode "$aliddns_name").$aliddns_domain&Timestamp=$timestamp"
}

update_record() {
	send_request "UpdateDomainRecord" "RR=$(urlencode "$aliddns_name")&RecordId=$1&SignatureMethod=HMAC-SHA1&SignatureNonce=$timestamp&SignatureVersion=1.0&Timestamp=$timestamp&Type=A&Value=$ip"
}

add_record() {
	send_request "AddDomainRecord&DomainName=$aliddns_domain" "RR=$(urlencode "$aliddns_name")&SignatureMethod=HMAC-SHA1&SignatureNonce=$timestamp&SignatureVersion=1.0&Timestamp=$timestamp&Type=A&Value=$ip"
}

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


if [ "$aliddns_enable" != "1" ]; then
    echo "$DATE: aliddns没有开启！" >> $log_file
else
    query_result=$(query_recordid)
    check_aliddns
    go_record
fi
