utils/env-gen.sh

40 lines
993 B
Bash
Raw Normal View History

2024-07-27 04:15:43 +05:00
#!/bin/bash
if [ -z "$1" ]; then
2024-08-14 10:49:55 +05:00
echo "Use: $0 <var_name> [value]"
2024-07-27 04:15:43 +05:00
exit 1
fi
VARIABLE_NAME=$1
ENV_FILE="/data/secrets/$SERVER_DOMAIN/$SERVER_DOMAIN.env"
2024-08-14 10:49:55 +05:00
# Password gen: 20chars,0-9,a-z
2024-07-27 04:15:43 +05:00
generate_random_password() {
#tr -dc 'a-z0-9' </dev/urandom | head -c 20
pwgen -s 20 1
}
2024-08-14 10:49:55 +05:00
# If the second parameter is specified, use it as the value of the variable
2024-07-27 04:15:43 +05:00
if [ -n "$2" ]; then
VALUE=$2
else
VALUE=$(generate_random_password)
fi
2024-08-14 10:49:55 +05:00
# Creating .env file if it doesn't exist
2024-07-27 04:15:43 +05:00
if [ ! -f "$ENV_FILE" ]; then
2024-08-14 10:49:55 +05:00
# Creating directories if they don't exist
2024-07-27 04:15:43 +05:00
mkdir -p "$(dirname "$ENV_FILE")"
touch "$ENV_FILE"
fi
2024-08-14 10:49:55 +05:00
# Update or add a variable to the .env file
2024-07-27 04:15:43 +05:00
if grep -q "^$VARIABLE_NAME=" "$ENV_FILE"; then
2024-08-14 10:49:55 +05:00
# The variable exists, update its value
2024-07-27 04:15:43 +05:00
sed -i "s/^$VARIABLE_NAME=.*/$VARIABLE_NAME=$VALUE/" "$ENV_FILE"
else
2024-08-14 10:49:55 +05:00
# The variable does not exist, add it to the file
2024-07-27 04:15:43 +05:00
echo "$VARIABLE_NAME=$VALUE" >> "$ENV_FILE"
fi
2024-08-14 10:49:55 +05:00
echo "Variable $VARIABLE_NAME successfully updated/added to $ENV_FILE"