dots/.bin/save-passwddb

76 lines
2.0 KiB
Bash
Executable File

#!/usr/bin/env bash
# Save (encrypted) password database to cloud storage
#
# Usage:
# save-passwddb - Save databases to cloud
# save-passwddb init - Restore databases from cloud (with single backup archive)
RCLONE_REMOTE="proton"
SOURCE_DIR="$HOME/doc"
TARGET_DIR="$RCLONE_REMOTE:doc"
BACKUP_DIR="$HOME/doc/bak"
function save_databases() {
if [ 0 -lt "$(ls $SOURCE_DIR/*.kdbx 2>/dev/null | wc -w)" ]; then
echo "[save] Saving KeePassXC databases and database keys"
rclone copy "$SOURCE_DIR" "$TARGET_DIR" \
--include "/*.{kdbx,kdbx.key}" \
--progress
echo "[save] Done"
else
echo "[save] No password database found, restore with:"
echo ""
echo " $0 init"
exit 1
fi
}
function backup_existing() {
mkdir -p "$BACKUP_DIR"
local timestamp=$(date +%Y%m%d-%H%M%S)
local backup_file="$BACKUP_DIR/passwddb_backup_${timestamp}.tar.gz"
echo "[backup] Creating backup archive: ${backup_file}"
tar -czf "$backup_file" -C "$SOURCE_DIR" $(find "$SOURCE_DIR" -maxdepth 1 -type f \( -name "*.kdbx" -o -name "*.kdbx.key" \) -printf "%f ")
echo "[backup] Backup complete"
}
function restore_databases() {
echo "[init] Checking for existing files..."
local existing_files=$(find "$SOURCE_DIR" -maxdepth 1 -type f \( -name "*.kdbx" -o -name "*.kdbx.key" \) -print)
if [ -n "$existing_files" ]; then
echo "[init] Found existing database files:"
echo "$existing_files" | while read -r file; do
echo " - $file"
done
read -p "[init] Create backup archive of existing files? [y/N] " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
backup_existing
fi
fi
echo "[init] Restoring KeePassXC databases and database keys"
mkdir -p "$SOURCE_DIR"
rclone copy "$TARGET_DIR" "$SOURCE_DIR" \
--include "*.{kdbx,kdbx.key}" \
--progress
echo "[init] Done"
}
case "$1" in
""|save)
save_databases
;;
init)
restore_databases
;;
*)
echo "Usage: $0 [init|save]"
exit 1
;;
esac