|
1 | 1 | #!/bin/bash |
2 | 2 |
|
3 | | -# Check if .env file exists and if AUTH_SECRET is already set |
4 | | -if [ -f .env ] && grep -q "^AUTH_SECRET=" .env; then |
5 | | - echo "AUTH_SECRET already exists in .env file. Skipping generation." |
6 | | -else |
7 | | - echo "Generating AUTH_SECRET..." |
8 | | - AUTH_SECRET=$(node -e "console.log('AUTH_SECRET=' + require('crypto').randomBytes(32).toString('base64'))") |
9 | | - echo $AUTH_SECRET |
10 | | - echo $AUTH_SECRET >> .env |
11 | | -fi |
12 | | - |
13 | | -# Check if DATABASE_URL is already set |
14 | | -if [ -f .env ] && grep -q "^DATABASE_URL=" .env; then |
15 | | - echo "DATABASE_URL already exists in .env file. Skipping." |
16 | | -else |
17 | | - echo "DATABASE_URL='postgresql://echo_user:echo_password@localhost:5469/echo_control_v2?schema=public'" >> .env |
18 | | -fi |
19 | | - |
20 | | -echo "Setup complete! You can now run 'pnpm dev' to start the development server." |
| 3 | +set -euo pipefail |
| 4 | + |
| 5 | +ENV_FILE=".env" |
| 6 | +DATABASE_URL_VALUE='"postgresql://echo_user:echo_password@localhost:5469/echo_control_v2?schema=public"' |
| 7 | + |
| 8 | +ensure_env_file() { |
| 9 | + if [ -f "$ENV_FILE" ]; then |
| 10 | + return |
| 11 | + fi |
| 12 | + |
| 13 | + if [ -f ".env.example" ]; then |
| 14 | + cp ".env.example" "$ENV_FILE" |
| 15 | + echo "Created $ENV_FILE from .env.example." |
| 16 | + else |
| 17 | + touch "$ENV_FILE" |
| 18 | + echo "Created empty $ENV_FILE." |
| 19 | + fi |
| 20 | +} |
| 21 | + |
| 22 | +env_value() { |
| 23 | + local key="$1" |
| 24 | + grep -E "^${key}=" "$ENV_FILE" | tail -n 1 | cut -d= -f2- | tr -d "\"'" |
| 25 | +} |
| 26 | + |
| 27 | +set_env_value() { |
| 28 | + local key="$1" |
| 29 | + local value="$2" |
| 30 | + local current |
| 31 | + |
| 32 | + current="$(env_value "$key" || true)" |
| 33 | + if [ -n "$current" ]; then |
| 34 | + echo "$key already exists in $ENV_FILE. Skipping." |
| 35 | + return |
| 36 | + fi |
| 37 | + |
| 38 | + if grep -qE "^${key}=" "$ENV_FILE"; then |
| 39 | + local temp_file |
| 40 | + temp_file="$(mktemp)" |
| 41 | + awk -v key="$key" -v replacement="${key}=${value}" ' |
| 42 | + BEGIN { replaced = 0 } |
| 43 | + $0 ~ "^" key "=" && replaced == 0 { |
| 44 | + print replacement |
| 45 | + replaced = 1 |
| 46 | + next |
| 47 | + } |
| 48 | + { print } |
| 49 | + ' "$ENV_FILE" > "$temp_file" |
| 50 | + mv "$temp_file" "$ENV_FILE" |
| 51 | + else |
| 52 | + printf "%s=%s\n" "$key" "$value" >> "$ENV_FILE" |
| 53 | + fi |
| 54 | + |
| 55 | + echo "Set $key in $ENV_FILE." |
| 56 | +} |
| 57 | + |
| 58 | +ensure_env_file |
| 59 | + |
| 60 | +AUTH_SECRET_VALUE="\"$(node -e "process.stdout.write(require('crypto').randomBytes(32).toString('base64'))")\"" |
| 61 | + |
| 62 | +set_env_value "AUTH_SECRET" "$AUTH_SECRET_VALUE" |
| 63 | +set_env_value "DATABASE_URL" "$DATABASE_URL_VALUE" |
| 64 | + |
| 65 | +echo "Setup complete. You can now run 'pnpm dev' to start the development server." |
0 commit comments