#!/bin/sh /etc/rc.common
#copyright by koolshare.cn crwnet

START=95
STOP=10
EXTRA_COMMANDS="update"
EXTRA_HELP="	update	Perform the update immediately"
LOGFILE="/var/log/koolddns.log"

DATE=$(date +'%Y-%m-%d %H:%M:%S')

Reduce_Log(){
	local log=$1
	[ ! -f "$log" ] && return
	local sc=100
	[ -n "$2" ] && sc=$2
	local count=$(grep -c "" $log)
	if [ $count -gt $sc ];then
		let count=count-$sc
		sed -i "1,$count d" $log
	fi
}

get_config()
{
	config_get_bool enable $1 enable 0
	config_get service $1 service
	config_get domain $1 domain
	config_get name $1 name
	config_get interface $1 interface
	[ $enable -eq 0 ] || [ -z "$service" ] || [ -z "$domain" ] || [ -z "$name" ] || [ -z "$interface" ] && return
	echo $DATE: -------------------------------------------------- >>$LOGFILE
	echo $DATE: 目标域名: $name.$domain >>$LOGFILE
	if [ "$interface" = "url" ]; then
		config_get ipurl $1 ipurl
		config_get urlinterface $1 urlinterface
		[ -n "$urlinterface" ] && urlif=$(uci -P /var/state get network.$urlinterface.ifname 2>/dev/null)
		[ -n "$urlif" ] && urlface="--interface $urlif"
		ip=$(curl $urlface -s $ipurl 2>&1)
		[ -z $(echo $ip|grep -E "([0-9]{1,3}[\.]){3}[0-9]{1,3}") ] && echo $DATE: "通过URL获取公网IP出错" >>$LOGFILE && echo >>$LOGFILE && return    
	else
		ifname=`uci -P /var/state get network.$interface.ifname 2>/dev/null`
		[ $? -eq 1 ] && echo $DATE: "获取网络 $interface 信息出错" >>$LOGFILE && echo >>$LOGFILE && return
		ip=$(ifconfig $ifname 2>/dev/null | grep 'inet addr' | awk '{print $2}' | cut -d: -f2 2>/dev/null)
		[ -z "$ip" ] && echo $DATE: "获取网络 $interface 接口 $ifname 信息出错" >>$LOGFILE && echo >>$LOGFILE && return    
	fi
	
	config_get record_id $1 record_id
	
	if [ "$service" = "aliddns" ]; then
		config_get accesskey $1 accesskey
		config_get signature $1 signature
		/usr/share/koolddns/aliddns "$enable" "$accesskey" "$signature" "$domain" "$name" "$ip" "$record_id" "$1" >>$LOGFILE
	fi
	
	if [ "$service" = "dnspod" ]; then
		config_get accesskey $1 accesskey
		config_get signature $1 signature
		/usr/share/koolddns/dnspod "$enable" "$accesskey" "$signature" "$domain" "$name" "$ip" "$record_id" "$1" >>$LOGFILE
	fi
}

update(){
	Reduce_Log $LOGFILE
	config_load koolddns
	config_foreach get_config koolddns
}

reload(){
	stop
	start
	update
}

del_cru(){
	if [ -f "/etc/crontabs/root" ] && [ $(cat /etc/crontabs/root | grep koolddns | wc -l) -ne 0 ]; then
		sed -i '/koolddns/d' /etc/crontabs/root >/dev/null 2>&1
	fi
}

add_cru(){
	local time=$(uci get koolddns.@global[0].time)
	local cmd="*/$time * * * * /etc/init.d/koolddns update"
	if [ ! -f "/etc/crontabs/root" ] || [ $(cat /etc/crontabs/root | grep "$cmd" | wc -l) -eq 0 ]; then
		sed -i '/koolddns/d' /etc/crontabs/root >/dev/null 2>&1
		echo "$cmd" >> /etc/crontabs/root
	fi
}

start() {
	local enabled=$(uci get koolddns.@global[0].enabled)
	[ "$enabled" -eq 0 ] && exit
	add_cru
}

stop() {
	del_cru
}
