#!/bin/sh

# sddns, a dnspod ddns client for linux and FreeBSD.
# Written by vinoca, June 2013
# Distributed under the MIT License
#
# more visit www.vinoca.org

VERSION=0.0.8

config_file="/etc/sddns.conf"

# load config file
[ ! -f $config_file ] && echo "ERROR: config file $config_file does not exist." && exit 1
. $config_file

# check $wanip
[ -z "$wanip" ] &&  echo "ERROR: Please check \"$config_file\", \"wanip\" is invalid ." && exit 1
# this regular expression from http://www.regular-expressions.info/examples.html
cur_wanip=`wget -qO- $wanip | grep -Eo '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'`
[ -z "$cur_wanip" ] && ignore_wanip=1 && echo "WARNING: \"wanip\" is invalid." 

# wrap some routines
post() {
	wget  -q -O- --no-check-certificate -U "sddns/$VERSION(vinoca@vinoca.org)" --post-data "login_email=$login_email&login_password=$login_password&format=json&error_on_empty=no&$1" "https://dnsapi.cn/$2"
}

get_domain_id() {
	sed -rn 's/.*("domain":\{.[^}]+\}).*/\1/g;s/.*"id":"([0-9]+)".*/\1/p'
}

get_record_id() {
	sed -rn "s/.*(\"records\":\[.[^]]+\]).*/\1/g;s/.*\{\"id\":\"([0-9]+)\",\"name\":\"$1\".*\"type\":\"A\".*/\1/p"
}

save_value() {
		grep "$1" $config_file >/dev/null 2>&1 || { echo "$1=$2" >> $config_file; return 0; }
		sed -i "s/$1=.*/$1=$2/g" $config_file
}		

# save domain_id and record_id if that is not in config_file 
#
[ -z "$domain_id" ] && {
	domain_id=`post "domain=$main_domain" Domain.Info | get_domain_id`
	save_value domain_id $domain_id
}

[ -z "$record_id" ] && {
	record_id=`post "domain_id=$domain_id" Record.List | get_record_id $sub_domain`
	save_value record_id $record_id
}

# update subdomain record if wanip is changed.
#
if [ -z $ignore_wanip ]; then
	[ "$cur_ip" != "$cur_wanip" ] && {
		save_value cur_ip $cur_wanip
		post "domain_id=$domain_id&record_id=$record_id&sub_domain=$sub_domain&record_line=默认" Record.Ddns
	}
else
	post "domain_id=$domain_id&record_id=$record_id&sub_domain=$sub_domain&record_line=默认" Record.Ddns
fi

exit 0
# vim: set ts=2 sw=2 noet:
