#!/bin/sh
# vim: set noexpandtab tabstop=4 shiftwidth=4 softtabstop=4 :

set -e

# shellcheck disable=SC1091
. /lib/overthebox

content="$1"
_get() {
	otb_json_get "$content" "arguments.$1"
}

remote_access_id="$(_get remote_access_id)"
if [ -z "$remote_access_id" ] || [ "$remote_access_id" = null ]; then
    echo "Invalid remote access ID"
    exit 1
fi
uci_id=$(echo "$remote_access_id" | tr - _)

luci_user="$(_get luci_user)"
luci_password="$(_get luci_password)"

otb_debug "Preparing remote access $remote_access_id with custom user '$luci_user'"

if [ "$luci_user" != 'null' ] && [ "$luci_password" != 'null' ]; then
	uci -q batch <<-EOF
		set otb-remote.${uci_id}=remote
		set otb-remote.${uci_id}.luci_user='${luci_user}'
		set rpcd.${uci_id}=login
		set rpcd.${uci_id}.username='${luci_user}'
		set rpcd.${uci_id}.password='\$p\$${luci_user}'
		add_list rpcd.${uci_id}.read='*'
		add_list rpcd.${uci_id}.write='*'
		commit otb-remote
		commit rpcd
	EOF

	# Create the user
	adduser -G root -s /bin/false -H -D -h /tmp "$luci_user"
	echo "$luci_user:$luci_password" | chpasswd

	# Restart rpcd
	/etc/init.d/rpcd restart
fi

otb_debug "Remote access $remote_access_id config written in uci"

[ -s /etc/dropbear/dropbear_ed25519_host_key ] || exit

pubkey=$(dropbearkey -y -f /etc/dropbear/dropbear_ed25519_host_key | grep ssh-ed25519)

otb_debug "Remote access $remote_access_id sending public key"

# shellcheck disable=SC2016
otb_device_post "remote_accesses/$remote_access_id/keys" \
	--data "$(jq -n -c --arg pubkey "$pubkey" '{public_key: $pubkey}')"
