#!/usr/bin/env bash

source "${SNAP}/init"

if ! [[ -d "${CERTS_DIR}" ]]; then
    logger "Creating dir ${CERTS_DIR}"
    mkdir "${CERTS_DIR}"
    chmod 0700 "${CERTS_DIR}"
fi

if ! [[ -d "${SSL_DIR}" ]]; then
    logger "Creating local cert dir ${SSL_DIR}"
    mkdir "${SSL_DIR}"
fi

logger "Creating connection from ${SNAP_NAME} (uuid: ${UUID})"

KEY=`gpg --armor --export "${UUID}"`

if [ -z "${KEY}" ]; then
    gpg_start_agent
    logger "Create GPG-key"
    gpg --batch --no-tty --gen-key <<< "
    %echo Generating a basic OpenPGP key
    Key-Type: default
    Subkey-Type: default
    Name-Real: ${SNAP_NAME}
    Name-Email: ${UUID}@${SNAP_NAME}.gpg
    Name-comment: Generated from ${SNAP_NAME} for certs-slot
    Expire-Date: 0
    %no-protection
    %commit
    %echo done"
    gpg_close_agent
fi

KEY=`gpg --armor --export "${UUID}"`
if [ $? -ne 0 ]; then
    echo "Failed to create GPG-key"
    logger "Failed to create GPG-key for ${UUID}"
    exit 1
fi

snapctl set :certs snapname="${SNAP_NAME}"
snapctl set :certs uuid="${UUID}"
snapctl set :certs pkey="${KEY}"

logger "${SNAP_NAME}:certs (uuid: ${UUID}) prepared"