#!/bin/sh
#
# Generate a CA cert to use for TLS authentication to vic-gateway
#
# Copyright 2018, Anki, Inc.

set -e
set -u

CERT_ROOT="/data/vic-gateway"
CERT_NAME="gateway"

# robot.pem is generated by mount-data
ROBOT_KEY="/data/etc/robot.pem"

mkdir -p ${CERT_ROOT}

# We use the current robot name as the common name in our cert. Clients will be
# responsible for resolving this correctly.

# Check for valid robot name, based on format:
# Vector-[A-Z][0-9][A-Z][0-9] (e.g. Vector-F1S3)
ROBOT_NAME=$(getprop "anki.robot.name" | tr ' ' '-')

if [[ ! $ROBOT_NAME =~ ^Vector-[A-Z][0-9][A-Z][0-9]$ ]]; then
    echo "error: '$ROBOT_NAME' is not a valid robot name"
    exit 1
fi

if [ ! -f ${ROBOT_KEY} ]; then
    echo "error: ${ROBOT_KEY} not found."
    exit 2
fi

if [ -f ${CERT_ROOT}/${CERT_NAME}.cert ]; then
    openssl x509 -in ${CERT_ROOT}/${CERT_NAME}.cert -noout
    if [[ $? == 0 ]]; then
        # valid cert already exists
        exit 0
    fi
    echo "Removing invalid cert: ${CERT_ROOT}/${CERT_NAME}.cert"
    rm -f ${CERT_ROOT}/${CERT_NAME}.cert
fi

CONF="/tmp/gateway-cert.$$.conf"
cp /etc/vic-gateway-cert.conf.in $CONF
echo "DNS.1       = $ROBOT_NAME" >> $CONF

openssl req \
    -config $CONF \
    -subj "/C=US/ST=California/L=SF/O=Anki/CN=$ROBOT_NAME" \
    -new -x509 \
    -days 36500 \
    -nodes \
    -key ${ROBOT_KEY} \
    -out ${CERT_ROOT}/${CERT_NAME}.cert

chmod 440 ${CERT_ROOT}/${CERT_NAME}.*

rm -f $CONF
