#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1

GATEWAY_DOMAINS_FILE="/usr/share/kspeeder/gateway-domains.conf"
GATEWAY_KEY_FILE="/etc/kspeeder/gateway.key"

GATEWAY_BINARY="/usr/sbin/iStoreEnhance"
GATEWAY_DNSMASQ_HOSTS="/tmp/kspeeder-gateway.hosts"
GATEWAY_STATUS_FILE="/var/run/kspeeder-gateway.status"

write_mirrors_config() {
    local filename="$1"
    cat > "$filename" << 'EOF'
mirrors:
  - url: "https://docker.1ms.run"
  - url: "https://docker.m.daocloud.io"
  - url: "https://docker.m.ixdev.cn"
  - url: "https://dockerproxy.net"
  - url: "https://image.cloudlayer.icu"
  - url: "https://docker.13140521.xyz"
  - url: "https://docker.1panel.live"
  - url: "https://docker.anye.in"
  - url: "https://docker.amingg.com"
  - url: "https://hub.rat.dev"
EOF
}

get_config() {
	config_get_bool enabled $1 enabled 0
	config_get_bool gateway_mode $1 gateway_mode 0
	config_get port $1 port 5443
	config_get adminport $1 adminport 5003
  config_get cache $1 cache
}

# Generate once and retain across service restarts/upgrades. Never use an
# administrator password or publish this key through the KSpeeder HTTP API.
prepare_gateway_auth() {
 [ "$gateway_mode" = 1 ] || return 0
 [ "$("$GATEWAY_BINARY" --gateway-auth-version 2>/dev/null)" = 1 ] || {
  logger -t istoreenhance "gateway mode requires an updated KSpeeder binary with authentication v1"
  return 1
 }
 local directory temporary key
 directory="$(dirname "$GATEWAY_KEY_FILE")"
 if [ ! -e "$GATEWAY_KEY_FILE" ]; then
  (
   umask 077
   mkdir -p "$directory" || exit 1
   temporary="$(mktemp "$directory/.gateway-key.XXXXXX")" || exit 1
   trap 'rm -f "$temporary"' EXIT HUP INT TERM
   # hexdump is available on standard OpenWrt BusyBox images; od is not.
   if command -v hexdump >/dev/null 2>&1; then
    key="$(hexdump -v -n 32 -e '1/1 "%02x"' /dev/urandom)"
   else
    key="$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')"
   fi
   [ "${#key}" = 64 ] || exit 1
   printf '%s\n' "$key" > "$temporary" || exit 1
   ln "$temporary" "$GATEWAY_KEY_FILE" 2>/dev/null || [ -f "$GATEWAY_KEY_FILE" ]
  ) || return 1
 fi
 key="$(cat "$GATEWAY_KEY_FILE")" || return 1
 [ "${#key}" = 64 ] || return 1
 case "$key" in *[!0-9a-fA-F]*) return 1;; esac
 chmod 600 "$GATEWAY_KEY_FILE"
}

gateway_lan_ip() {
	local address
	if command -v ubus >/dev/null 2>&1 && command -v jsonfilter >/dev/null 2>&1; then
		address="$(ubus call network.interface.lan status 2>/dev/null | jsonfilter -e '@["ipv4-address"][0].address' 2>/dev/null)"
	fi
	[ -n "$address" ] || address="$(uci -q get network.lan.ipaddr 2>/dev/null)"
	case "$address" in
		''|*[!0-9.]*) return 1 ;;
	esac
	printf '%s\n' "$address"
}

render_gateway_dns_config() {
	local address="$1"
	local output="$2"
	awk -v address="$address" '
		$1 == "gateway" && $2 ~ /^[A-Za-z0-9.-]+$/ {
			printf "%s %s\n", address, $2
		}
	' "$GATEWAY_DOMAINS_FILE" > "$output"
}

reload_dnsmasq() {
	[ -x /etc/init.d/dnsmasq ] && /etc/init.d/dnsmasq reload >/dev/null 2>&1
}

gateway_hosts_registered() {
	uci -q get dhcp.@dnsmasq[0].addnhosts 2>/dev/null \
		| tr ' ' '\n' \
		| grep -Fqx "$GATEWAY_DNSMASQ_HOSTS"
}

register_gateway_hosts() {
	gateway_hosts_registered && return 0
	uci add_list "dhcp.@dnsmasq[0].addnhosts=$GATEWAY_DNSMASQ_HOSTS" || return 1
	uci commit dhcp
}

unregister_gateway_hosts() {
	gateway_hosts_registered || return 0
	uci -q del_list "dhcp.@dnsmasq[0].addnhosts=$GATEWAY_DNSMASQ_HOSTS" || return 1
	uci commit dhcp
}

remove_gateway_dns() {
	local changed=0
	if [ -e "$GATEWAY_DNSMASQ_HOSTS" ]; then
		rm -f "$GATEWAY_DNSMASQ_HOSTS" || return 1
		changed=1
	fi
	if gateway_hosts_registered; then
		unregister_gateway_hosts || return 1
		changed=1
	fi
	[ "$changed" = 0 ] || reload_dnsmasq
}

apply_gateway_dns() {
	local address temporary
	[ "$gateway_mode" = 1 ] || {
		remove_gateway_dns
		return 0
	}
	[ -r "$GATEWAY_DOMAINS_FILE" ] || {
		logger -t istoreenhance "gateway mode: missing domain manifest $GATEWAY_DOMAINS_FILE"
		remove_gateway_dns
		return 1
	}
	address="$(gateway_lan_ip)" || {
		logger -t istoreenhance "gateway mode: cannot determine LAN IPv4 address"
		remove_gateway_dns
		return 1
	}
	temporary="$(mktemp "${GATEWAY_DNSMASQ_HOSTS}.XXXXXX")" || return 1
	if ! render_gateway_dns_config "$address" "$temporary" || [ ! -s "$temporary" ]; then
		rm -f "$temporary"
		logger -t istoreenhance "gateway mode: cannot render dnsmasq configuration"
		remove_gateway_dns
		return 1
	fi
	local changed=0
	if [ -f "$GATEWAY_DNSMASQ_HOSTS" ] && cmp -s "$temporary" "$GATEWAY_DNSMASQ_HOSTS"; then
		rm -f "$temporary"
	else
		if ! chmod 644 "$temporary" || ! mv "$temporary" "$GATEWAY_DNSMASQ_HOSTS"; then
			rm -f "$temporary"
			remove_gateway_dns
			return 1
		fi
		changed=1
	fi
	if ! gateway_hosts_registered; then
		if ! register_gateway_hosts; then
			logger -t istoreenhance "gateway mode: cannot register dnsmasq hosts file"
			remove_gateway_dns
			return 1
		fi
		changed=1
	fi
	if [ "$changed" != 0 ] && ! reload_dnsmasq; then
		logger -t istoreenhance "gateway mode: cannot reload dnsmasq"
		remove_gateway_dns
		return 1
	fi
	logger -t istoreenhance "gateway mode: mapped KSpeeder domains to $address"
}

start_service() {
	config_load istoreenhance
	config_foreach get_config istoreenhance
	if [ $enabled != 1 ]; then
		disabled_mirrors
		remove_gateway_dns
		return 1
	fi

  if [ -z $cache ]; then
		remove_gateway_dns
    return 2
  fi

 # Gateway setup is optional. Never stop the original local service on failure.
 local gateway_ready=0
 if [ "$gateway_mode" = 1 ]; then
  if prepare_gateway_auth && apply_gateway_dns; then
   gateway_ready=1
   rm -f "$GATEWAY_STATUS_FILE"
  else
   logger -t istoreenhance "gateway initialization failed; local service remains available"
   remove_gateway_dns || logger -t istoreenhance "gateway DNS cleanup failed"
   printf 'failed\n' > "$GATEWAY_STATUS_FILE"
  fi
 else
  remove_gateway_dns || logger -t istoreenhance "gateway DNS cleanup failed"
  rm -f "$GATEWAY_STATUS_FILE"
 fi

	if [ ! -f $cache/kspeeder.yml ]; then
		parent_dir=$(dirname "$cache")
		[ -d "$parent_dir" ] || mkdir "$parent_dir"
		[ -d "$cache" ] || mkdir "$cache"
		write_mirrors_config $cache/kspeeder.yml
	fi

	procd_open_instance
 procd_set_param env KS_USER_MIRROR_CONFIG="$cache/kspeeder.yml"
 [ "$gateway_ready" != 1 ] || procd_append_param env KSPEEDER_GATEWAY_KEY_FILE="$GATEWAY_KEY_FILE"
	procd_set_param limits nofile="65535 65535"
	procd_set_param command /usr/sbin/iStoreEnhance
	[ -n "$port" ] && procd_append_param command --localAddr ":$port" --adminAddr ":$adminport" --cachePath $cache
	procd_set_param respawn
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "istoreenhance"
	procd_add_reload_trigger "network"
}

disabled_mirrors() {
	local mirror=$(uci get dockerd.globals.registry_mirrors | grep -oE 'https://registry\.linkease\.net:[0-9]+')
	[ -n "$mirror" ] || return 0
	uci del_list "dockerd.globals.registry_mirrors=$mirror"
	uci commit dockerd
	/etc/init.d/dockerd reload
}

service_stopped() {
 rm -f "$GATEWAY_STATUS_FILE"
	disabled_mirrors
	remove_gateway_dns
}
