#!/usr/bin/env sh
set -eux
dir=${0%/*}
key=$1
host=${key#*/}
host=${host%%/*}
hostkey=${key#*/*/}
mkdir -p "$dir/$host/credentials/${hostkey%/*}"
pass "$key" |
sudo unshare --mount sh -xc "
  mount --bind $dir/$host/root/credential.secret /var/lib/systemd/credential.secret &&
  mount --bind $dir/$host/root/machine-id /etc/machine-id &&
  systemd-creds encrypt --with-key=host --name '${hostkey##*/}' - - |
  install -m 400 -o $USER -g users /dev/stdin '$dir/$host/credentials/$hostkey.secret'
"