|
| 1 | +#!/bin/bash |
| 2 | +# Database restore script for Kelas Rumah Berbagi |
| 3 | +# Restores SQLite database from backup |
| 4 | +# |
| 5 | +# Usage: ./scripts/restore-db.sh [backup_file] |
| 6 | +# If no backup file specified, uses the most recent backup |
| 7 | + |
| 8 | +set -euo pipefail |
| 9 | + |
| 10 | +# Configuration |
| 11 | +DB_PATH="/data/kelas/db/prod.db" |
| 12 | +BACKUP_DIR="/var/backups/kelas-db" |
| 13 | + |
| 14 | +# Get backup file (from argument or most recent) |
| 15 | +if [ $# -ge 1 ]; then |
| 16 | + BACKUP_FILE="$1" |
| 17 | +else |
| 18 | + BACKUP_FILE=$(ls -t "${BACKUP_DIR}"/prod_*.db 2>/dev/null | head -1) |
| 19 | + if [ -z "${BACKUP_FILE}" ]; then |
| 20 | + echo "ERROR: No backup files found in ${BACKUP_DIR}" |
| 21 | + exit 1 |
| 22 | + fi |
| 23 | + echo "Using most recent backup: ${BACKUP_FILE}" |
| 24 | +fi |
| 25 | + |
| 26 | +# Verify backup file exists |
| 27 | +if [ ! -f "${BACKUP_FILE}" ]; then |
| 28 | + echo "ERROR: Backup file not found: ${BACKUP_FILE}" |
| 29 | + exit 1 |
| 30 | +fi |
| 31 | + |
| 32 | +# Confirm restore |
| 33 | +echo "WARNING: This will replace the current database!" |
| 34 | +echo " Source: ${BACKUP_FILE}" |
| 35 | +echo " Target: ${DB_PATH}" |
| 36 | +read -p "Are you sure you want to continue? (yes/no): " CONFIRM |
| 37 | + |
| 38 | +if [ "${CONFIRM}" != "yes" ]; then |
| 39 | + echo "Restore cancelled" |
| 40 | + exit 0 |
| 41 | +fi |
| 42 | + |
| 43 | +# Stop the application container to prevent writes during restore |
| 44 | +echo "Stopping application container..." |
| 45 | +if docker ps --format '{{.Names}}' | grep -q "kelas-web"; then |
| 46 | + docker stop kelas-web || true |
| 47 | +fi |
| 48 | + |
| 49 | +# Create backup of current database before restore |
| 50 | +if [ -f "${DB_PATH}" ]; then |
| 51 | + TIMESTAMP=$(date +%Y%m%d_%H%M%S) |
| 52 | + PRERESTORE_BACKUP="${BACKUP_DIR}/prod_prerestore_${TIMESTAMP}.db" |
| 53 | + echo "Backing up current database to ${PRERESTORE_BACKUP}..." |
| 54 | + cp "${DB_PATH}" "${PRERESTORE_BACKUP}" |
| 55 | +fi |
| 56 | + |
| 57 | +# Restore the backup |
| 58 | +echo "Restoring database..." |
| 59 | +cp "${BACKUP_FILE}" "${DB_PATH}" |
| 60 | + |
| 61 | +# Restart the application |
| 62 | +echo "Starting application container..." |
| 63 | +docker start kelas-web || true |
| 64 | + |
| 65 | +# Verify restore |
| 66 | +if [ -f "${DB_PATH}" ]; then |
| 67 | + RESTORED_SIZE=$(du -h "${DB_PATH}" | cut -f1) |
| 68 | + echo "Database restored successfully (${RESTORED_SIZE})" |
| 69 | +else |
| 70 | + echo "ERROR: Restore failed - database file not found" |
| 71 | + exit 1 |
| 72 | +fi |
| 73 | + |
| 74 | +echo "Restore completed" |
0 commit comments