summaryrefslogtreecommitdiff
path: root/secrets/create-local.sh
blob: ffebd9cf52d871015b25cc1f230d5751784ffb24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/bin/bash

set -euo pipefail

if [[ "$#" -gt 0 && ("$1" == "-h" || "$1" == "--help") ]]; then
    cat <<EOF
create-local: Create a new localized secret store

Creates a new age private key for a localized secret store and initializes
a directory with metadata for automatic store discovery.

If the store key already exists but the directory lacks metadata, this command
will add the metadata file (useful for migrating existing stores).

Usage:
  create-local <store-name> <directory>
  create-local -h|--help

Arguments:
  store-name    Name of the local store to create
  directory     Directory to initialize with store metadata

The command will:
1. Check if the directory already has a .szecret metadata file
2. If the store key doesn't exist, generate a new age private key
3. Write the store name to <directory>/.szecret

Note: This command will refuse to overwrite existing metadata.
EOF
    exit 0
fi

this_dir="$(cd "$(dirname "$0")" && pwd)"
source "${this_dir}/common.sh"

if [[ "$#" -lt 2 ]]; then
    >&2 echo "ERROR: Need local store name and directory"
    exit 1
fi

local_store_name="$1"
target_dir="$2"
metadata_file="${target_dir}/.szecret"
local_key_name="$(local_key_name "${local_store_name}")"
local_key_file="$(file_for "${local_key_name}")"

key_exists=false
metadata_exists=false

[[ -r "${local_key_file}" ]] && key_exists=true
[[ -e "${metadata_file}" ]] && metadata_exists=true

# Check if metadata already exists
if [[ "${metadata_exists}" == "true" ]]; then
    >&2 echo "ERROR: Directory already has .szecret metadata"
    exit 1
fi

# Ensure target directory exists
mkdir -p "${target_dir}"

ensure_age

if [[ "${key_exists}" == "false" ]]; then
    # New store: create key first
    age-keygen 2>/dev/null | "${this_dir}/put.sh" "${local_key_name}"
fi

# Get public key and write metadata
local_pubkey="$(get_local_public_key "${local_store_name}")"
write_local_metadata "${metadata_file}" "${local_store_name}" "${local_pubkey}"

if [[ "${key_exists}" == "true" ]]; then
    >&2 echo "Added metadata for existing store '${local_store_name}'"
fi