Last active
September 29, 2020 23:11
-
-
Save cdanis/6558c24c73840fce5639f8d85f298285 to your computer and use it in GitHub Desktop.
backup-r38-db.sh
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Copyright © 2020 Chris Danis | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
# | |
# Usage: r38-backup-db [instance: prod or staging, default prod] | |
set -euf | |
[ "$(whoami)" = "r38" ] || exec sudo -u r38 "$(readlink -f "$0")" "$@" | |
INSTANCE="${1:-prod}" | |
BASEDIR="/srv/r38/${INSTANCE}/backups" | |
mkdir -p "$BASEDIR/tmp" "$BASEDIR/by-hash" "$BASEDIR/by-time" | |
cd "$BASEDIR" | |
TIMESTAMP="$(date -Isecond | cut -d+ -f1)" # eg 2020-06-13T04:22:00 | |
DATE="${TIMESTAMP%%T*}" # eg 2020-06-13 | |
TMPFILE="$(mktemp tmp/backup.XXXXXX."${TIMESTAMP}".db)" | |
trap 'rm -f $TMPFILE' EXIT | |
[ -r "../draft.db" ] && sqlite3 ../draft.db ".backup ${TMPFILE}" | |
HASH="$(sha256sum "$TMPFILE")" | |
HASH="${HASH%% *}" | |
HASH_DIR="by-hash/${HASH:0:2}/${HASH:2:2}" # abcdef1234 --> ab/cd/abcdef1234 | |
mkdir -p "$HASH_DIR" | |
HASH_FILE="${HASH_DIR}/${HASH}" | |
if [ ! -f "${HASH_FILE}.gz" ]; then | |
mv "$TMPFILE" "$HASH_FILE" | |
gzip --best "$HASH_FILE" | |
fi | |
mkdir -p "by-time/${DATE}" | |
ln -s "../../$HASH_FILE.gz" "by-time/${DATE}/${TIMESTAMP}.gz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment