# SPDX-FileCopyrightText: 2022 Luke Granger-Brown <depot@lukegb.com>
#
# SPDX-License-Identifier: Apache-2.0

{ pkgs, ... }@args: {
  cfg = import ./cfg args;

  provision-secret-id = pkgs.writeShellApplication {
    name = "provision-secret-id";
    runtimeInputs = with pkgs; [ vault ];
    text = ''
      set -euo pipefail

      export VAULT_ADDR=https://vault.int.lukegb.com/

      if [[ "$(id -u)" != 0 ]]; then
        echo Must be run as root >&2
        exit 1
      fi

      echo -n "Secret wrapping token: "
      read -r secret_id

      SECRET_ID="$(vault unwrap -field=secret_id "''${secret_id}")"
      RET="$?"
      if [[ "$RET" != 0 ]]; then
        exit $RET
      fi
      echo "$SECRET_ID" > /var/lib/vault-agent/secret-id

      systemctl restart vault-agent
      systemctl restart secretsmgr || true
    '';
  };
}