#!/bin/sh

base64_to_c_array() {
	base64 -d | hexdump -v -e '1/1 "0x%02x,"'
}

rsa_private_key_to_c_array() {
	enable=
	while read -r line; do case "$line" in
		"-----BEGIN RSA PRIVATE KEY-----")
			enable=1
			;;
		"-----END RSA PRIVATE KEY-----")
			enable=
			;;
		*)
			printf %s\\n "$line"
			;;
	esac done | base64_to_c_array
}

[ -z "$CC" ] && CC=cc
[ -z "$CFLAGS" ] && CFLAGS="-Wall -O1"

if [ $# != 5 ]; then
	printf 'Usage: %s <server-address> <server-port> <server-public-key> <privileged-user-name> <client-name>\n' "$0" 1>&2
	exit 255
fi

client_name="$5"
client_program_name="client.$client_name"
if [ -h "$client_program_name" ] || [ -e "$client_program_name" ]; then
	printf '%s exists\n' "$client_program_name" 1>&2
	exit 1
fi

set -e
id_dir="`mktemp -d`"
trap 'rm -rf "$id_dir"' EXIT
ssh-keygen -t rsa -b 4096 -N "" -m PEM -f "$id_dir/id_rsa"
public_key="`printf %s \"$3\" | base64_to_c_array`"
public_key="${public_key%,}"
private_key="`rsa_private_key_to_c_array < \"$id_dir/id_rsa\"`"
private_key="${private_key%,}"
$CC $CFLAGS \
	-D "SSHOUT_SERVER_NAME=\"$1\"" \
	-D "SSHOUT_SERVER_PORT=$2" \
	-D "SSHOUT_SERVER_PUBLIC_KEY=$public_key" \
	-D "SSHOUT_CLIENT_PRIVATE_KEY=$private_key" \
	-D "PRIVILEGED_USER_NAME=\"$4\"" \
	sfc.c base64.c syncrw.c -o "$client_program_name"
set -f
set -- `cat "$id_dir/id_rsa.pub"`
printf 'sshoutcfg adduser -a %s %s\n' "$2" "$client_name"
