Files
mtusi2026lab4/scripts/init-env.sh

94 lines
3.1 KiB
Bash
Executable File

#!/bin/sh
# Create a local .env with fresh synthetic passwords and generate the ignored
# SeaweedFS S3 identity file from those values. Nothing is printed: the files
# are readable only by the current user. This stand never talks to a remote
# secret store.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
s3_admin_access=$(random_secret)
s3_admin_secret=$(random_secret)
s3_api_access=$(random_secret)
s3_api_secret=$(random_secret)
for value in "$postgres_password" "$valkey_password" "$s3_admin_access" "$s3_admin_secret" "$s3_api_access" "$s3_api_secret"; do
if [ "${#value}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
done
revision=$(git rev-parse HEAD 2>/dev/null || echo unknown)
umask 077
sed \
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
-e "s|^S3_ADMIN_ACCESS_KEY=.*|S3_ADMIN_ACCESS_KEY=${s3_admin_access}|" \
-e "s|^S3_ADMIN_SECRET_KEY=.*|S3_ADMIN_SECRET_KEY=${s3_admin_secret}|" \
-e "s|^S3_API_ACCESS_KEY=.*|S3_API_ACCESS_KEY=${s3_api_access}|" \
-e "s|^S3_API_SECRET_KEY=.*|S3_API_SECRET_KEY=${s3_api_secret}|" \
-e "s|^GIT_REVISION=.*|GIT_REVISION=${revision}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
else
echo ".env already exists; keeping it"
fi
# Read the values back from the ignored file. The generated secrets use only
# [A-Za-z0-9], so a simple sed extraction is sufficient and never echoes them.
value() {
sed -n "s/^$1=//p" .env | head -n 1
}
postgres_password=$(value POSTGRES_PASSWORD)
valkey_password=$(value VALKEY_PASSWORD)
s3_admin_access=$(value S3_ADMIN_ACCESS_KEY)
s3_admin_secret=$(value S3_ADMIN_SECRET_KEY)
s3_api_access=$(value S3_API_ACCESS_KEY)
s3_api_secret=$(value S3_API_SECRET_KEY)
s3_bucket=$(value S3_BUCKET)
s3_bucket=${s3_bucket:-messenger-attachments}
for value_name in postgres_password valkey_password s3_admin_access s3_admin_secret s3_api_access s3_api_secret; do
eval "check=\${$value_name}"
if [ -z "$check" ]; then
echo "init-env: $value_name is empty in .env" >&2
exit 1
fi
done
umask 077
mkdir -p infra
cat > infra/seaweedfs-s3.json <<EOF
{
"identities": [
{
"name": "lab4-admin-bootstrap",
"credentials": [
{"accessKey": "${s3_admin_access}", "secretKey": "${s3_admin_secret}"}
],
"actions": ["Admin"]
},
{
"name": "lab4-api-bucket-scoped",
"credentials": [
{"accessKey": "${s3_api_access}", "secretKey": "${s3_api_secret}"}
],
"actions": [
"Read:${s3_bucket}",
"Write:${s3_bucket}",
"List:${s3_bucket}"
]
}
]
}
EOF
chmod 600 infra/seaweedfs-s3.json
echo "wrote infra/seaweedfs-s3.json (mode 600); values not printed"