#!/bin/bash
set -e

CPU_SERIAL=$(awk '/Serial/ {print $3}' /proc/cpuinfo)

# Fallback if CPU_SERIAL is empty
if [[ -z "$CPU_SERIAL" ]]; then
  CPU_SERIAL="999999999999"
fi

KEK=$(echo -n "$CPU_SERIAL" | \
      openssl dgst -sha256 -hmac "server-provided-salt" | \
      awk '{print $2}')

# Decrypt into tmpfs
mkdir -p /run/iot
openssl enc -d -aes-256-gcm -pbkdf2 \
  -pass pass:$KEK \
  -in /etc/iot/keys/device.key.enc \
  -out /run/iot/device.key

# Load into kernel keyring (root-only key)
keyctl padd user iot-client-key @s < /run/iot/device.key

# Securely erase plaintext
shred -u /run/iot/device.key