Files
CloudDeploy/prepdb.sh
2026-03-05 01:34:55 +01:00

78 lines
2.9 KiB
Bash

# sqlite db replace function
replace_in_sqlite_db() {
local DB_PATH="$1"
local OLD_STRING="$2"
local NEW_STRING="$3"
# Check if the database file exists
if [ ! -f "$DB_PATH" ]; then
echo "Error: Database file '$DB_PATH' does not exist."
exit 1
fi
# Check if jq is installed
if ! command -v jq &> /dev/null; then
echo "Error: 'jq' is not installed. Please install it first (e.g., 'sudo apt install jq')."
exit 1
fi
echo "Starting JSON-aware replacement of '$OLD_STRING' with '$NEW_STRING' in '$DB_PATH'..."
# Create a backup of the original database
local BACKUP_PATH="${DB_PATH}.bak"
cp "$DB_PATH" "$BACKUP_PATH"
# Dump the database to SQL
local DUMP_PATH="${DB_PATH}.sql"
sqlite3 "$DB_PATH" ".dump" > "$DUMP_PATH"
# Create a temporary file for the modified SQL dump
local MODIFIED_DUMP_PATH="${DB_PATH}.modified.sql"
# Process the SQL dump line by line
while IFS= read -r line; do
# Check if the line contains JSON data (simplistic check for quotes and brackets)
if [[ "$line" =~ [\"{][^"\{]*["\}][^"\{]*$OLD_STRING[^"\{]*[\}"] ]]; then
# Use jq to replace strings in JSON fields
echo "$line" | jq --arg old_str "$OLD_STRING" --arg new_str "$NEW_STRING" '
walk(if type == "string" then gsub($old_str; $new_str) else . end)
' > /dev/null 2>&1
# If jq fails (not valid JSON), fall back to sed
if [ $? -ne 0 ]; then
echo "$line" | sed "s|$OLD_STRING|$NEW_STRING|g"
else
echo "$line" | jq --arg old_str "$OLD_STRING" --arg new_str "$NEW_STRING" '
walk(if type == "string" then gsub($old_str; $new_str) else . end)
'
fi
else
# Use sed for non-JSON fields
echo "$line" | sed "s|$OLD_STRING|$NEW_STRING|g"
fi
done < "$DUMP_PATH" > "$MODIFIED_DUMP_PATH"
# Create a new database from the modified SQL dump
local NEW_DB_PATH="${DB_PATH}.new"
sqlite3 "$NEW_DB_PATH" < "$MODIFIED_DUMP_PATH"
# Replace the original database with the new one
mv "$NEW_DB_PATH" "$DB_PATH"
# Clean up temporary files
rm "$DUMP_PATH"
rm "$MODIFIED_DUMP_PATH"
echo "Replacement completed in '$DB_PATH'. Original database backed up to '$BACKUP_PATH'."
}
#set script directory
scriptdir="$(dirname "$(realpath "$0")")"
#example usage: replace_in_sqlite_db "database.sqlite" "Europe/Amsterdam" "UTC"
cp $scriptdir/stacks/npm/data/database-pre.sqlite $scriptdir/stacks/npm/data/database.sqlite
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "sdgserver.online" "?domain?"
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "192.168.2.132" "?localip?"
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "z5fGWz2i0q" "?adminpass?"
replace_in_sqlite_db "$scriptdir/stacks/npm/data/database.sqlite" "0.0.0.0/0" "?localip?"