#!/bin/bash

# Path where secrets are stored
SECRETS_PATH=.secrets

# Generated secrets
SECRETS=(
	app_key
	mysql_root_password
)

# API key secrets
API_KEYS=(
	tmdb_key
	discord_bot_key
	plex_token
	tvdb_key
	tvdb_pin
	vpn_auth
)

# Store new API keys if available
NEW_API_KEYS=()

# Indicate if existing secrets should be regenerated
OVERWRITE=0

# Generate secrets and files -----------------------------------------------------------------------

# Create secrets folder
if [ -d $SECRETS_PATH ]; then
	read -p "Regenerate existing secrets (Y|n)? " -n 1 -r
	echo
	if [[ $REPLY =~ ^[Yy]$ ]]; then
		OVERWRITE=1
	fi
else
	mkdir -p $SECRETS_PATH
fi

# Generate random secrets
for key in ${SECRETS[@]}; do
	if [ $OVERWRITE -eq 1 ] || [ ! -f "$SECRETS_PATH/$key" ] || [[ -z $(grep '[^[:space:]]' "$SECRETS_PATH/$key") ]]; then
		openssl rand -base64 20 > "$SECRETS_PATH/$key"
	fi
done

# Create API key files if they don't ekist
for key in ${API_KEYS[@]}; do
	if [ ! -f "$SECRETS_PATH/$key" ] || [[ -z $(grep '[^[:space:]]' "$SECRETS_PATH/$key") ]]; then
		touch "$SECRETS_PATH/$key"
		NEW_API_KEYS+=($key)
	fi
done

# --------------------------------------------------------------------------------------------------

# Display newly-added/empty API key files
if [ ${#NEW_API_KEYS[*]} -gt 0 ]; then
	echo "New API keys available:"
	for key in ${NEW_API_KEYS[@]}; do
		echo "  $SECRETS_PATH/$key"
	done
fi

echo "Done."
