#!/bin/sh

# Create a random maintenance key (ecret. Readable only to root) and its
# hash readable to Ombutel.

hash_cmd=sha512sum
dir=/etc/ombutel
conf_file="$dir/ombutel.conf"
secret_file="$dir/ombutel-maint.conf"

hash_output() {
	$hash_cmd | cut -d' ' -f1
}

set -e

if [ ! -f "$secret_file" ]; then
	touch "$secret_file"
	chmod go= "$secret_file"
	head -c 512 /dev/urandom | hash_output >"$secret_file"
fi
secret=`cat $secret_file`
hash=`echo -n "$secret" | hash_output`
file_hash=`awk -F "[\"']" '/api_maintenance_key/{print $2}' "$conf_file"`
if [ "$file_hash" ]; then
	if [ "$file_hash" = "$hash" ]; then
		exit 0 # Nothing left to do
	fi
	sed -i "/api_maintenance_key/s/$file_hash/$hash/" "$conf_file"
else
	sed -i -e "/extends basic_config {/a\\\tconst api_maintenance_key = '$hash';" \
		"$conf_file"
fi

