# shellcheck disable=SC2034
# vim: set ft=sh noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

OTB_TODO_DIR="/tmp/otb-todo"
OTB_DATA_DIR="/tmp/otb-data"
OTB_HEADERS_FILE="/tmp/otb-daemon-headers"
OTB_CONFIG_CHECK_DIR="/usr/share/otb/config-check.d"
OTB_PROVISIONING="otb.eu.ovhapis.com"
OTB_SERVICE_API="169.254.254.1"

mkdir -p "$OTB_DATA_DIR" "$OTB_TODO_DIR"

otb_reload() {
	[ -f /etc/config/overthebox ] || touch /etc/config/overthebox
	OTB_DEVICE_ID=$(uci -q get overthebox.me.device_id || true)
	OTB_SERVICE_ID=$(uci -q get overthebox.me.service || true)
	OTB_TOKEN=$(uci -q get overthebox.me.token || true)
	OTB_DEBUG=$(uci -q get overthebox.me.debug || true)
}

otb_reload

otb_init() {
	# force usb switch in order to switch 4G key from CD-ROM to usb-cdc
	/sbin/usbmode -l
	/bin/sleep 2
	/sbin/usbmode -s
}

otb_alert() {
	logger -t "$(basename "$0")" -p 1 "$*" || true
}

otb_crit() {
	logger -t "$(basename "$0")" -p 2 "$*" || true
}

otb_err() {
	logger -t "$(basename "$0")" -p 3 "$*" || true
}

otb_warn() {
	logger -t "$(basename "$0")" -p 4 "$*" || true
}

otb_notice() {
	logger -t "$(basename "$0")" -p 5 "$*" || true
}

otb_info() {
	logger -t "$(basename "$0")" -p 6 "$*" || true
}

otb_debug()  {
	# shellcheck disable=SC2015
	[ "$OTB_DEBUG" ] && logger -t "$(basename "$0")" -p 7 "$*" || true
}

otb_pretty_print() {
	jq -e -n --argjson output "$1" "\$output" 2>/dev/null || echo "$1"
}

otb_json_get() {
	jq -r -n --argjson content "$1" "\$content.$2"
}

otb_call() {
	method=$1
	path=$2
	shift 2
	jwt="$(uci get overthebox.me.jwt 2>/dev/null || true)"
	otb_debug "call: $method $path $*"
	curl --silent --show-error --max-time 5 \
		-X "$method" \
		-H "Content-Type: application/json" \
		-H "X-Overthebox-Version: $(cat /etc/otb-version || echo 0.0-0)" \
		${jwt:+-H "Authorization: Bearer $jwt"} \
		"https://$OTB_PROVISIONING/1.0/$path" \
		"$@"
}

otb_call_api() {
	[ "$OTB_SERVICE_ID" ] || return
	method=$1
	path=$2
	shift 2
	otb_debug "call api: $method $path $*"
	curl --silent --show-error --max-time 1 \
		-X "$method" \
		-H "Content-Type: application/json" \
		"http://$OTB_SERVICE_API/$path" \
		"$@"
}

otb_device_put() {
	subpath=$1
	shift 1
	[ "$OTB_DEVICE_ID" ] && otb_call PUT "devices/$OTB_DEVICE_ID/$subpath" "$@"
}

otb_device_post() {
	subpath=$1
	shift 1
	[ "$OTB_DEVICE_ID" ] && otb_call POST "devices/$OTB_DEVICE_ID/$subpath" "$@"
}

otb_device_get() {
	subpath=$1
	shift 1
	[ "$OTB_DEVICE_ID" ] && otb_call GET "devices/$OTB_DEVICE_ID/$subpath" "$@"
}

otb_service_put() {
	subpath=$1
	shift 1
	[ "$OTB_SERVICE_ID" ] && otb_device_put "service/$OTB_SERVICE_ID/$subpath" "$@"
}

otb_service_post() {
	subpath=$1
	shift 1
	[ "$OTB_SERVICE_ID" ] && otb_device_post "service/$OTB_SERVICE_ID/$subpath" "$@"
}

otb_service_get() {
	subpath=$1
	shift 1
	[ "$OTB_SERVICE_ID" ] && otb_device_get "service/$OTB_SERVICE_ID/$subpath" "$@"
}

otb_todo() {
	mkdir -p "$OTB_TODO_DIR"
	(echo "$* <<EOF"; cat -; echo EOF) > "$OTB_TODO_DIR/$(date +%s%N)"
}

otb_set_data() {
	mkdir -p "$(dirname "$OTB_DATA_DIR/$1")"
	echo "$2" > "$OTB_DATA_DIR/$1"
}

otb_unset_data() {
	rm -f "$OTB_DATA_DIR/$1"
}

otb_get_data() {
	[ -f "$OTB_DATA_DIR/$1" ] || return 0
	cat "$OTB_DATA_DIR/$1"
}

otb_save_event() {
	details=$2
	[ "$details" ] || details="{}"
	# shellcheck disable=SC2016
	jq -n -c --arg name "$1" --arg timestamp "$(date +%s)" --argjson details "$details" \
		'{event_name: $name, timestamp: $timestamp|tonumber, details: $details}' | otb_todo otb_device_post events -d@-
}

otb_save_action_id() {
	[ -z "$1" ] && return
	id=$(otb_json_get "$1" id)
	[ "$id" ] && [ "$id" != null ] && uci -q batch <<-EOF
	set overthebox.me.action_id=$id
	commit overthebox
	EOF
}

speedtest() {
	LIBRESPEED=$(jq -n \
	    '[{"id": 1,"name": "otb-gra","server": "https://gra.perf.overthebox.net/","dlURL": "garbage","ulURL": "empty","pingURL": "empty","getIpURL": "getIP"}]'
	)

	if [ "$2" = "json" ]; then
		SPEEDTEST=$(echo "${LIBRESPEED}" | librespeed-cli --json --source "$1" --duration 5 --local-json -)
	else
		echo "${LIBRESPEED}" | librespeed-cli --source "$1" --duration 5 --local-json -
	fi
}

speedtest_json() {
	LIBRESPEED=$(jq -n \
	    '[{"id": 1,"name": "otb-gra","server": "https://gra.perf.overthebox.net/","dlURL": "garbage","ulURL": "empty","pingURL": "empty","getIpURL": "getIP"}]'
	)

	SPEEDTEST=$(echo "${LIBRESPEED}" | librespeed-cli --json --source "$1" --duration 5 --local-json -)
}

otb_led() {
	sysfs=$(uci -q get "system.$1_led.sysfs")
	[ "$sysfs" ] || return 0
	# shellcheck disable=SC1091
	. /lib/functions/leds.sh
	case "$2" in
		on) led_on "$sysfs" ;;
		off) led_off "$sysfs" ;;
		blink) led_timer "$sysfs" "500" "500" ;;
	esac
}
