#!/bin/sh

#MEDIA_UNLOCKER_CONFIG_URL=https://cdn.libz.so/gist/JohnnySun/fae443904c7266613887e3f1d55e6c4a/raw/RNCN-MEDIA-UNLOACKER-CN.yaml
#DNS_CONFIG_URL=https://cdn.libz.so/gist/JohnnySun/fae443904c7266613887e3f1d55e6c4a/raw/RNCN-DNS-CONFIG-CN.yaml

MEDIA_UNLOCKER_CONFIG_URL=https://gist.githubusercontent.com/JohnnySun/fae443904c7266613887e3f1d55e6c4a/raw/RNCN-MEDIA-UNLOACKER-OVERSEA.yaml
DNS_CONFIG_URL=https://gist.githubusercontent.com/JohnnySun/fae443904c7266613887e3f1d55e6c4a/raw/RNCN-DNS-CONFIG-OVERSEA.yaml

get_version() {
	sed -En 's/^ *"?rncn-config-version"? *: *([0-9]+),?$/\1/p'
}

# Usage: check_and_update_config <remote-url> <local-path> <service-name>
check_and_update_config() {
	cfg="`wget --no-verbose \"$1\" -O -`" || return
	remote_version="`printf '%s\\n' "$cfg" | get_version`"
	if [ -z "$remote_version" ]; then
		echo "Newly fetched configuration file has no version field?!" 1>&2
		return 1
	fi
	local_version="`get_version < \"$2\"`"
	[ -n "$local_version" ] && [ "$local_version" -ge "$remote_version" ] && return
	rm -f "$2.old"
	printf %s\\n "$cfg" > "$2"
	if ! service "$3" restart; then
		printf "Failed to restart %s, rollback to old version\\n" "$2"
		mv "$2.old" "$2"
		service "$3" restart
		return
	fi
	echo "Newer configuration has been found and updated." 1>&2
}

while true; do
	check_and_update_config $MEDIA_UNLOCKER_CONFIG_URL /etc/rncn_dns/media_unlocker/config.yaml rncn-media-unlocker
	check_and_update_config $DNS_CONFIG_URL /etc/rncn_dns/dns/config.yaml rncn-dns
	sleep 600
done
