#!/bin/bash # ============================================================================= # Piwigo Restore Script for Docker Container # ============================================================================= # This script restores a Piwigo backup (from TrueNAS app) to a Docker container. # # Run this script ON the Docker host where you want to run Piwigo. # # Requirements: # - Docker and Docker Compose installed # - Backup archive from backup-piwigo-truenas.sh # - Write access to Docker volumes/data directories # ============================================================================= set -euo pipefail # ============================================================================= # CONFIGURATION # ============================================================================= # Backup archive path (passed as first argument or set here) BACKUP_ARCHIVE="${1:-}" # Docker project directory DOCKER_DIR="${DOCKER_DIR:-/opt/piwigo}" # Docker Compose file COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.yml}" # Database container name (from docker-compose) DB_CONTAINER="${DB_CONTAINER:-piwigo-db}" # Piwigo container name PIWIGO_CONTAINER="${PIWIGO_CONTAINER:-piwigo}" # Database credentials (should match docker-compose .env) DB_ROOT_PASS="${DB_ROOT_PASS:-}" DB_NAME="${DB_NAME:-piwigo}" DB_USER="${DB_USER:-piwigo}" DB_PASS="${DB_PASS:-}" # Piwigo data directory (host path mounted to container) PIWIGO_DATA_DIR="${PIWIGO_DATA_DIR:-${DOCKER_DIR}/piwigo-data}" # Skip database restore (only restore files) SKIP_DB="${SKIP_DB:-false}" # Skip files restore (only restore database) SKIP_FILES="${SKIP_FILES:-false}" # Force overwrite without confirmation FORCE="${FORCE:-false}" # ============================================================================= # INTERNAL VARIABLES # ============================================================================= TEMP_DIR="" EXTRACT_DIR="" # Colors RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' BLUE='\033[0;34m' NC='\033[0m' # ============================================================================= # HELPER FUNCTIONS # ============================================================================= log() { local level="$1" shift local msg="$*" local timestamp=$(date +"%Y-%m-%d %H:%M:%S") echo -e "${timestamp} [${level}] ${msg}" } info() { log "INFO" "${BLUE}$*${NC}"; } warn() { log "WARN" "${YELLOW}$*${NC}"; } error() { log "ERROR" "${RED}$*${NC}"; } success() { log "SUCCESS" "${GREEN}$*${NC}"; } die() { error "$*" cleanup exit 1 } confirm() { local prompt="$1" if [[ "${FORCE}" == "true" ]]; then return 0 fi read -rp "${prompt} [y/N]: " response case "${response}" in [yY][eE][sS]|[yY]) return 0 ;; *) return 1 ;; esac } cleanup() { if [[ -n "${TEMP_DIR}" ]] && [[ -d "${TEMP_DIR}" ]]; then info "Cleaning up temporary directory..." rm -rf "${TEMP_DIR}" fi } # ============================================================================= # VALIDATION FUNCTIONS # ============================================================================= validate_backup() { info "Validating backup archive..." if [[ -z "${BACKUP_ARCHIVE}" ]]; then die "Usage: $0 " fi if [[ ! -f "${BACKUP_ARCHIVE}" ]]; then die "Backup archive not found: ${BACKUP_ARCHIVE}" fi # Check if it's a valid tar.gz if ! tar -tzf "${BACKUP_ARCHIVE}" >/dev/null 2>&1; then die "Invalid or corrupted backup archive" fi # Verify checksum if exists if [[ -f "${BACKUP_ARCHIVE}.sha256" ]]; then info "Verifying checksum..." if ! sha256sum -c "${BACKUP_ARCHIVE}.sha256" >/dev/null 2>&1; then die "Checksum verification failed! Archive may be corrupted." fi success "Checksum verified" else warn "No checksum file found, skipping verification" fi success "Backup archive validated" } extract_backup() { info "Extracting backup archive..." TEMP_DIR=$(mktemp -d -t piwigo-restore-XXXXXX) info "Temporary directory: ${TEMP_DIR}" tar -xzf "${BACKUP_ARCHIVE}" -C "${TEMP_DIR}" # Find the extracted directory (should be piwigo_backup_*) EXTRACT_DIR=$(find "${TEMP_DIR}" -maxdepth 1 -type d -name "piwigo_backup_*" | head -1) if [[ -z "${EXTRACT_DIR}" ]] || [[ ! -d "${EXTRACT_DIR}" ]]; then die "Could not find extracted backup directory" fi info "Extracted to: ${EXTRACT_DIR}" # List contents info "Backup contents:" find "${EXTRACT_DIR}" -type f | head -30 | while read -r file; do local rel="${file#${EXTRACT_DIR}/}" local size=$(du -h "${file}" | cut -f1) echo " ${rel} (${size})" done } validate_docker() { info "Validating Docker environment..." if ! command -v docker >/dev/null 2>&1; then die "Docker not found. Please install Docker." fi if ! command -v docker-compose >/dev/null 2>&1 && ! docker compose version >/dev/null 2>&1; then die "Docker Compose not found. Please install Docker Compose." fi # Check if docker-compose file exists if [[ ! -f "${DOCKER_DIR}/${COMPOSE_FILE}" ]]; then warn "Docker Compose file not found at ${DOCKER_DIR}/${COMPOSE_FILE}" warn "You may need to create it first or specify correct path with COMPOSE_FILE" fi success "Docker environment validated" } # ============================================================================= # RESTORE FUNCTIONS # ============================================================================= restore_database() { if [[ "${SKIP_DB}" == "true" ]]; then info "Skipping database restore (SKIP_DB=true)" return 0 fi info "Restoring database..." local db_dump="${EXTRACT_DIR}/database/piwigo_*.sql.gz" # Find the actual dump file local dump_file=$(ls ${db_dump} 2>/dev/null | head -1 || true) if [[ -z "${dump_file}" ]] || [[ ! -f "${dump_file}" ]]; then die "Database dump not found in backup: ${db_dump}" fi info "Using database dump: ${dump_file}" # Check if database container is running if ! docker ps --format '{{.Names}}' | grep -q "^${DB_CONTAINER}$"; then warn "Database container '${DB_CONTAINER}' is not running." if confirm "Start it now?"; then cd "${DOCKER_DIR}" docker-compose up -d "${DB_CONTAINER}" info "Waiting for database to be ready..." sleep 10 else die "Database container must be running to restore database" fi fi # Wait for database to be ready info "Waiting for database to be ready..." local retries=30 while [[ ${retries} -gt 0 ]]; do if docker exec "${DB_CONTAINER}" mysqladmin ping -h localhost --silent 2>/dev/null; then break fi sleep 2 ((retries--)) done if [[ ${retries} -eq 0 ]]; then die "Database not ready after 60 seconds" fi success "Database is ready" # Drop and recreate database (clean restore) info "Recreating database ${DB_NAME}..." docker exec -i "${DB_CONTAINER}" mysql -u root -p"${DB_ROOT_PASS}" -e " DROP DATABASE IF EXISTS \`${DB_NAME}\`; CREATE DATABASE \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; GRANT ALL PRIVILEGES ON \`${DB_NAME}\`.* TO '${DB_USER}'@'%'; FLUSH PRIVILEGES; " 2>>/dev/null || die "Failed to recreate database" # Restore database info "Restoring database data (this may take a while)..." if ! zcat "${dump_file}" | docker exec -i "${DB_CONTAINER}" mysql -u root -p"${DB_ROOT_PASS}" "${DB_NAME}" 2>>/dev/null; then die "Database restore failed" fi success "Database restored successfully" # Verify restore local table_count=$(docker exec "${DB_CONTAINER}" mysql -u root -p"${DB_ROOT_PASS}" "${DB_NAME}" -e "SHOW TABLES;" --silent 2>/dev/null | wc -l) info "Restored ${table_count} tables" } restore_files() { if [[ "${SKIP_FILES}" == "true" ]]; then info "Skipping files restore (SKIP_FILES=true)" return 0 fi info "Restoring Piwigo files..." # Create data directory structure mkdir -p "${PIWIGO_DATA_DIR}/upload" mkdir -p "${PIWIGO_DATA_DIR}/local/config" mkdir -p "${PIWIGO_DATA_DIR}/galleries" # Restore uploads if [[ -d "${EXTRACT_DIR}/uploads" ]]; then info "Restoring uploads..." rsync -av "${EXTRACT_DIR}/uploads/" "${PIWIGO_DATA_DIR}/upload/" 2>&1 | tail -5 local count=$(find "${PIWIGO_DATA_DIR}/upload" -type f | wc -l) success "Uploads restored: ${count} files" else warn "No uploads directory in backup" fi # Restore config if [[ -d "${EXTRACT_DIR}/config" ]]; then info "Restoring configuration..." rsync -av "${EXTRACT_DIR}/config/" "${PIWIGO_DATA_DIR}/local/config/" 2>&1 | tail -5 success "Configuration restored" else warn "No config directory in backup" fi # Restore galleries (if exists) if [[ -d "${EXTRACT_DIR}/galleries" ]]; then info "Restoring galleries..." rsync -av "${EXTRACT_DIR}/galleries/" "${PIWIGO_DATA_DIR}/galleries/" 2>&1 | tail -5 local count=$(find "${PIWIGO_DATA_DIR}/galleries" -type f | wc -l) success "Galleries restored: ${count} files" else info "No galleries directory in backup (this is normal if not using separate gallery storage)" fi # Fix permissions info "Fixing file permissions..." # Piwigo runs as www-data (uid 33) in most containers docker run --rm -v "${PIWIGO_DATA_DIR}:/data" alpine:latest \ sh -c "chown -R 33:33 /data && find /data -type d -exec chmod 755 {} \\; && find /data -type f -exec chmod 644 {} \\;" 2>&1 | tail -3 success "Permissions fixed" } generate_docker_compose() { info "Generating Docker Compose template..." local compose_path="${DOCKER_DIR}/${COMPOSE_FILE}" if [[ -f "${compose_path}" ]] && [[ "${FORCE}" != "true" ]]; then warn "Docker Compose file already exists at ${compose_path}" if ! confirm "Overwrite?"; then info "Skipping Docker Compose generation" return 0 fi fi mkdir -p "${DOCKER_DIR}" cat > "${compose_path}" <<'EOF' version: '3.8' services: db: image: mariadb:10.11 container_name: piwigo-db restart: unless-stopped environment: MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASS} MYSQL_DATABASE: ${DB_NAME} MYSQL_USER: ${DB_USER} MYSQL_PASSWORD: ${DB_PASS} volumes: - db-data:/var/lib/mysql networks: - piwigo-net healthcheck: test: ["CMD", "mysqladmin", "ping", "-h", "localhost"] interval: 10s timeout: 5s retries: 5 piwigo: image: piwigo/piwigo:latest container_name: piwigo restart: unless-stopped depends_on: db: condition: service_healthy environment: # Database configuration DB_HOST: db DB_PORT: 3306 DB_NAME: ${DB_NAME} DB_USER: ${DB_USER} DB_PASS: ${DB_PASS} # Optional: PHP settings PHP_MEMORY_LIMIT: 256M PHP_MAX_EXECUTION_TIME: 300 PHP_UPLOAD_MAX_FILESIZE: 100M PHP_POST_MAX_SIZE: 100M volumes: - ${PIWIGO_DATA_DIR}:/var/www/html ports: - "8080:80" networks: - piwigo-net volumes: db-data: networks: piwigo-net: driver: bridge EOF success "Docker Compose template created at ${compose_path}" # Create .env template local env_path="${DOCKER_DIR}/.env" if [[ ! -f "${env_path}" ]] || [[ "${FORCE}" == "true" ]]; then cat > "${env_path}" <:8080" echo echo " 4. If this is a fresh database (not restored), you'll see the Piwigo installer." echo " If database was restored, you should see your existing Piwigo instance." echo echo " 5. Verify everything works:" echo " - Check that photos appear" echo " - Test upload a new photo" echo " - Verify admin panel access" echo info "Useful commands:" echo " docker-compose logs -f piwigo # View Piwigo logs" echo " docker-compose logs -f db # View database logs" echo " docker-compose restart piwigo # Restart Piwigo" echo " docker-compose down # Stop everything" echo warn "Remember to:" echo " - Set strong passwords in .env" echo " - Configure reverse proxy (nginx/traefik) for HTTPS" echo " - Set up regular backups for the Docker deployment" } # ============================================================================= # MAIN EXECUTION # ============================================================================= main() { info "======================================" info "Piwigo Docker Restore Started" info "======================================" # Handle help if [[ "${BACKUP_ARCHIVE}" == "-h" ]] || [[ "${BACKUP_ARCHIVE}" == "--help" ]]; then cat < [options] Options (via environment variables): DOCKER_DIR Docker project directory (default: /opt/piwigo) COMPOSE_FILE Docker Compose filename (default: docker-compose.yml) DB_CONTAINER Database container name (default: piwigo-db) PIWIGO_CONTAINER Piwigo container name (default: piwigo) DB_ROOT_PASS Database root password (required) DB_NAME Database name (default: piwigo) DB_USER Database user (default: piwigo) DB_PASS Database user password (required) PIWIGO_DATA_DIR Host data directory (default: \${DOCKER_DIR}/piwigo-data) SKIP_DB Skip database restore (true/false, default: false) SKIP_FILES Skip files restore (true/false, default: false) FORCE Force overwrite without confirmation (true/false, default: false) Example: DB_ROOT_PASS=secret DB_PASS=secret $0 ./piwigo_backup_20240115_120000.tar.gz EOF exit 0 fi validate_backup extract_backup validate_docker generate_docker_compose restore_database restore_files cleanup show_next_steps } # Trap cleanup on exit trap cleanup EXIT # Run main main "$@"