#!/usr/bin/env bash
set -eux
set -o pipefail
#dir=${0%/*}
gpg=$1
name=${2-}
base=${gpg%.gpg}

umask 177
SECRET=$(mktemp /dev/shm/credential.secret.XXXXXXX)
trap 'chmod 600 $SECRET; shred --remove=unlink $SECRET' EXIT
gpg --yes --output "$SECRET" --decrypt "credential.secret.gpg"

gpg --decrypt "$gpg" |
sudo unshare --mount sh -xc "
  mount --bind '$SECRET' /var/lib/systemd/credential.secret &&
  chmod 400 /var/lib/systemd/credential.secret &&
  mount --bind machine-id.clear /etc/machine-id &&
  systemd-creds encrypt --with-key=host ${name:+--name "$name"} - - |
  install -m 400 -o '$USER' -g users /dev/stdin '$base.cred'
"