#!/bin/sh /etc/rc.common
# Copyright (C) 2021 Tianling Shen <cnsztl@immortalwrt.org>

USE_PROCD=1
START=99

CONF="cloudflared"
PROG="/usr/bin/cloudflared"

append_param_arg() {
	local value
	config_get value "config" "$1" $2
	[ -n "$value" ] && procd_append_param command "--${1//_/-}" "$value"
}

start_service() {
	config_load "$CONF"

	local enabled
	config_get_bool enabled "config" "enabled"
	[ "$enabled" -eq "1" ] || return 1

	procd_open_instance "$CONF"
	procd_set_param command "$PROG" "tunnel"
	procd_append_param command "--no-autoupdate"

	append_param_arg "config" "/etc/cloudflared/config.yml"
	append_param_arg "origincert" "/etc/cloudflared/cert.pem"
	append_param_arg "edge_bind_address"
	append_param_arg "edge_ip_version"
	append_param_arg "grace_period"
	append_param_arg "protocol"
	append_param_arg "region"
	append_param_arg "retries"
	append_param_arg "tag"
	append_param_arg "metrics"
	append_param_arg "loglevel"
	append_param_arg "logfile"

	procd_append_param command "run"
	append_param_arg "token"

	procd_set_param respawn
	procd_set_param stderr 1

	procd_close_instance
}

reload_service() {
	stop
	start
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
	procd_add_interface_trigger "interface.*.up" "wan" /etc/init.d/cloudflared restart
}
