#!/bin/bash

set -euo pipefail

TEMP_CA="/home/zoox/.ssh/temp_ca"
TEMP_CA_PUB="${TEMP_CA}.pub"
PUBLIC_KEY="/home/zoox/.ssh/id_rsa.pub"
TEMP_TRUSTED_CAS_FILE="/etc/ssh/robot_pairing_ca.pub"
TRUSTED_CAS_FILE="/etc/ssh/trusted_user_ca.pub"
ROBOT_HOSTNAME="main-ai"

rm -rf "$TEMP_CA" "$TEMP_CA_PUB"

# Generate temporary CA
ssh-keygen -b 2048 -t ssh-rsa -N "" -f "$TEMP_CA" > /dev/null

# Generate identity for laptop, then discard CA private key
ssh-keygen -I zoox -s "$TEMP_CA" -t ssh-rsa -V +30d -n root,zoox "$PUBLIC_KEY" > /dev/null
rm "$TEMP_CA"

# Install temporary CA public key to robot
scp "$TEMP_CA_PUB" "root@${ROBOT_HOSTNAME}:$TEMP_TRUSTED_CAS_FILE"
rm "$TEMP_CA_PUB"
ssh root@${ROBOT_HOSTNAME} "cat $TEMP_TRUSTED_CAS_FILE >> $TRUSTED_CAS_FILE"

ssh root@${ROBOT_HOSTNAME} "service ssh restart"
