1#!/bin/bash
2set -euo pipefail
3
4service=${1:?usage: tools/import-legacy-secrets.sh SERVICE ENV_NAME...|KEY=ENV_NAME...}
5shift
6(( $# > 0 )) || { echo 'Expected at least one environment variable name' >&2; exit 1; }
7[[ $service =~ ^[a-z][a-z0-9-]*$ ]] || { echo 'Invalid service name' >&2; exit 1; }
8sources=()
9keys=()
10for item in "$@"; do
11 if [[ $item == *=* ]]; then
12 key=${item%%=*}
13 source=${item#*=}
14 [[ $key =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || { echo 'Invalid secret key' >&2; exit 1; }
15 keys+=("$key")
16 else
17 source=$item
18 fi
19 [[ $source =~ ^[A-Z][A-Z0-9_]*$ ]] || { echo 'Invalid environment variable name' >&2; exit 1; }
20 sources+=("$source")
21done
22(( ${#keys[@]} == 0 || ${#keys[@]} == ${#sources[@]} )) || { echo 'Use a target key for every source name' >&2; exit 1; }
23options=()
24for key in "${keys[@]}"; do
25 options+=(--key "$key")
26done
27: "${STUDIO_DEPLOY_HOST:?Set STUDIO_DEPLOY_HOST to the production target}"
28
29source_host=${STUDIO_MIGRATION_SOURCE:-zenith}
30repo=$(cd "$(dirname "$0")/.." && pwd)
31names=$(printf ' %s' "${sources[@]}")
32if [[ -n ${STUDIO_LEGACY_HANDOFF:-} ]]; then
33 sh "$repo/tools/check-legacy-handoff.sh" "$STUDIO_LEGACY_HANDOFF" "$STUDIO_DEPLOY_HOST" "${STUDIO_DEPLOY_PORT:-22}"
34 source_remote=(ssh -p "${STUDIO_DEPLOY_PORT:-22}" "$STUDIO_DEPLOY_HOST")
35else
36 source_remote=(ssh "$source_host")
37fi
38
39"${source_remote[@]}" "python3 -$names <<'PY'
40from pathlib import Path
41import sys
42
43lines = Path('/mnt/storage1/apps/home-infra/.env').read_text().splitlines()
44if len(set(sys.argv[1:])) != len(sys.argv[1:]):
45 raise SystemExit('Duplicate source secret name')
46secrets = []
47for name in sys.argv[1:]:
48 values = [line.split('=', 1)[1] for line in lines if line.startswith(name + '=')]
49 if len(values) != 1 or not values[0]:
50 raise SystemExit('Expected one nonempty source secret: ' + name)
51 secrets.append(values[0])
52for value in secrets:
53 print(value)
54PY" | python3 "$repo/tools/deploy.py" secrets "$service" --file - "${options[@]}"