| 1 | #!/bin/bash |
| 2 | set -euo pipefail |
| 3 | |
| 4 | service=${1:?usage: tools/import-legacy-secrets.sh SERVICE ENV_NAME...|KEY=ENV_NAME...} |
| 5 | shift |
| 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; } |
| 8 | sources=() |
| 9 | keys=() |
| 10 | for 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") |
| 21 | done |
| 22 | (( ${#keys[@]} == 0 || ${#keys[@]} == ${#sources[@]} )) || { echo 'Use a target key for every source name' >&2; exit 1; } |
| 23 | options=() |
| 24 | for key in "${keys[@]}"; do |
| 25 | options+=(--key "$key") |
| 26 | done |
| 27 | : "${STUDIO_DEPLOY_HOST:?Set STUDIO_DEPLOY_HOST to the production target}" |
| 28 | |
| 29 | source_host=${STUDIO_MIGRATION_SOURCE:-zenith} |
| 30 | repo=$(cd "$(dirname "$0")/.." && pwd) |
| 31 | names=$(printf ' %s' "${sources[@]}") |
| 32 | if [[ -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") |
| 35 | else |
| 36 | source_remote=(ssh "$source_host") |
| 37 | fi |
| 38 | |
| 39 | "${source_remote[@]}" "python3 -$names <<'PY' |
| 40 | from pathlib import Path |
| 41 | import sys |
| 42 | |
| 43 | lines = Path('/mnt/storage1/apps/home-infra/.env').read_text().splitlines() |
| 44 | if len(set(sys.argv[1:])) != len(sys.argv[1:]): |
| 45 | raise SystemExit('Duplicate source secret name') |
| 46 | secrets = [] |
| 47 | for 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]) |
| 52 | for value in secrets: |
| 53 | print(value) |
| 54 | PY" | python3 "$repo/tools/deploy.py" secrets "$service" --file - "${options[@]}" |