From b068a69d1f7bab9eb9e4d01afa2d2f6254a6ea7e Mon Sep 17 00:00:00 2001 From: Tero Date: Thu, 22 Oct 2026 17:41:16 +0300 Subject: [PATCH] first commit --- .env.example | 45 ++++ QUICKSTART.md | 90 +++++++ README.md | 332 +++++++++++++++++++++++++ backup-piwigo-truenas.sh | 518 +++++++++++++++++++++++++++++++++++++++ restore-piwigo-docker.sh | 500 +++++++++++++++++++++++++++++++++++++ 5 files changed, 1485 insertions(+) create mode 100644 .env.example create mode 100644 QUICKSTART.md create mode 100644 README.md create mode 100644 backup-piwigo-truenas.sh create mode 100644 restore-piwigo-docker.sh diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b5b2d0d --- /dev/null +++ b/.env.example @@ -0,0 +1,45 @@ +# Piwigo Docker Migration - Environment Configuration +# Copy this file to .env and fill in your values +# NEVER commit .env to version control! + +# ============================================================================= +# DATABASE CREDENTIALS (Required) +# ============================================================================= +# These must match what you used during restore or what exists in the backup +DB_ROOT_PASS=changeme_strong_root_password_here +DB_NAME=piwigo +DB_USER=piwigo +DB_PASS=changeme_strong_user_password_here + +# ============================================================================= +# PIWIGO DATA DIRECTORY +# ============================================================================= +# Host directory where Piwigo files will be stored (uploads, config, galleries) +PIWIGO_DATA_DIR=/opt/piwigo/piwigo-data + +# ============================================================================= +# OPTIONAL: INITIAL ADMIN USER (Only used on fresh database install) +# ============================================================================= +# If restoring from backup, these are ignored (existing users preserved) +# PIWIGO_ADMIN_USER=admin +# PIWIGO_ADMIN_PASS=changeme_admin_password +# PIWIGO_ADMIN_EMAIL=admin@example.com + +# ============================================================================= +# OPTIONAL: PHP SETTINGS (Adjust for large uploads) +# ============================================================================= +# PHP_MEMORY_LIMIT=256M +# PHP_MAX_EXECUTION_TIME=300 +# PHP_UPLOAD_MAX_FILESIZE=100M +# PHP_POST_MAX_SIZE=100M + +# ============================================================================= +# OPTIONAL: CONTAINER NAMES (Override if needed) +# ============================================================================= +# DB_CONTAINER=piwigo-db +# PIWIGO_CONTAINER=piwigo + +# ============================================================================= +# OPTIONAL: NETWORK/PORT SETTINGS +# ============================================================================= +# PIWIGO_PORT=8080 # Host port for Piwigo web UI \ No newline at end of file diff --git a/QUICKSTART.md b/QUICKSTART.md new file mode 100644 index 0000000..7999d4d --- /dev/null +++ b/QUICKSTART.md @@ -0,0 +1,90 @@ +# Quick Start: TrueNAS Piwigo → Docker + +## One-Line Commands + +### On TrueNAS (Backup) +```bash +ssh root@truenas "APP_NAMESPACE=piwigo BACKUP_DEST=/mnt/tank/backups/piwigo bash -s" < backup-piwigo-truenas.sh +``` + +### On Docker Host (Restore + Start) +```bash +# 1. Copy backup from TrueNAS to Docker host +scp root@truenas:/mnt/tank/backups/piwigo/piwigo_backup_*.tar.gz* /opt/piwigo/ + +# 2. Run restore (set your passwords) +cd /opt/piwigo +DB_ROOT_PASS=your_root_pass DB_PASS=your_user_pass ./restore-piwigo-docker.sh piwigo_backup_*.tar.gz + +# 3. Edit .env with same passwords +nano .env + +# 4. Start! +docker-compose up -d +``` + +## Minimum Required Commands + +```bash +# TRUENAS: Run backup +ssh root@truenas +/tmp/backup-piwigo-truenas.sh + +# DOCKER HOST: Restore and start +scp root@truenas:/mnt/tank/backups/piwigo/piwigo_backup_*.tar.gz* . +DB_ROOT_PASS=xxx DB_PASS=yyy ./restore-piwigo-docker.sh piwigo_backup_*.tar.gz +cp .env.example .env +# Edit .env with: DB_ROOT_PASS=xxx DB_PASS=yyy +docker-compose up -d +``` + +## Verify It Works + +```bash +# Check containers running +docker-compose ps + +# View Piwigo logs +docker-compose logs -f piwigo + +# Test web access +curl -I http://localhost:8080 +``` + +## Common Customizations + +| Need | Command | +|------|---------| +| Custom backup location | `BACKUP_DEST=/mnt/pool/backups ./backup-piwigo-truenas.sh` | +| Different namespace | `APP_NAMESPACE=my-piwigo ./backup-piwigo-truenas.sh` | +| Only restore files | `SKIP_DB=true ./restore-piwigo-docker.sh backup.tar.gz` | +| Only restore database | `SKIP_FILES=true ./restore-piwigo-docker.sh backup.tar.gz` | +| Custom data dir | `PIWIGO_DATA_DIR=/data/piwigo ./restore-piwigo-docker.sh backup.tar.gz` | +| Non-interactive | `FORCE=true ./restore-piwigo-docker.sh backup.tar.gz` | + +## File Locations After Migration + +``` +/opt/piwigo/ +├── docker-compose.yml # Generated +├── .env # YOUR PASSWORDS HERE +├── piwigo-data/ +│ ├── upload/ # Photos +│ ├── local/config/ # Config +│ └── galleries/ # Gallery structure +└── (db-data in Docker volume) +``` + +## Rollback Plan + +If something goes wrong: + +```bash +# Stop Docker Piwigo +docker-compose down + +# TrueNAS app is untouched - just restart it in TrueNAS UI +# Or if you modified TrueNAS data, restore from backup: +# (backup script keeps last 7 by default) +ls /mnt/tank/backups/piwigo/piwigo_backup_*.tar.gz +``` \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..1fafca0 --- /dev/null +++ b/README.md @@ -0,0 +1,332 @@ +# TrueNAS Piwigo App → Docker Migration + +This repository contains scripts to backup a Piwigo instance running as a TrueNAS App (Kubernetes/k3s) and restore it to a Docker container. + +## Scripts + +| Script | Purpose | Run On | +|--------|---------|--------| +| `backup-piwigo-truenas.sh` | Backup Piwigo from TrueNAS App | TrueNAS host | +| `restore-piwigo-docker.sh` | Restore Piwigo to Docker | Docker host | + +--- + +## Prerequisites + +### On TrueNAS Host +- TrueNAS with Piwigo app installed +- SSH access to TrueNAS (or use TrueNAS Shell) +- `k3s kubectl` available (usually at `/usr/local/bin/k3s kubectl`) +- `mariadb-dump` or `mysqldump` installed +- Write access to backup destination dataset + +### On Docker Host +- Docker Engine installed +- Docker Compose (v2 plugin or standalone) +- Write access to Docker data directory + +--- + +## Quick Start + +### 1. Backup on TrueNAS + +```bash +# SSH into TrueNAS +ssh root@truenas.local + +# Copy the backup script to TrueNAS +scp backup-piwigo-truenas.sh root@truenas.local:/tmp/ + +# Run the backup script +# You can set environment variables to customize behavior +APP_NAMESPACE=piwigo \ +BACKUP_DEST=/mnt/tank/backups/piwigo \ +/tmp/backup-piwigo-truenas.sh +``` + +**Environment Variables for Backup:** +| Variable | Default | Description | +|----------|---------|-------------| +| `APP_NAMESPACE` | `piwigo` | Kubernetes namespace of Piwigo app | +| `BACKUP_DEST` | `/mnt/tank/backups/piwigo` | Destination dataset path | +| `DB_HOST` | auto-detect | Database host | +| `DB_PORT` | `3306` | Database port | +| `DB_NAME` | `piwigo` | Database name | +| `DB_USER` | `piwigo` | Database user | +| `DB_PASS` | auto-detect | Database password | +| `PVC_UPLOADS` | auto-detect | Uploads PVC name | +| `PVC_CONFIG` | auto-detect | Config PVC name | +| `PVC_GALLERIES` | auto-detect | Galleries PVC name | +| `RETENTION_COUNT` | `7` | Number of backups to keep | +| `COMPRESSION_LEVEL` | `6` | gzip compression (1-9) | + +### 2. Transfer Backup to Docker Host + +```bash +# From your workstation, pull the backup from TrueNAS +scp root@truenas.local:/mnt/tank/backups/piwigo/piwigo_backup_*.tar.gz* . + +# Copy to Docker host +scp piwigo_backup_*.tar.gz* user@docker-host:/opt/piwigo/ +``` + +### 3. Restore on Docker Host + +```bash +# SSH into Docker host +ssh user@docker-host + +# Make scripts executable +chmod +x restore-piwigo-docker.sh + +# Run restore (set required passwords) +DB_ROOT_PASS=your_root_password \ +DB_PASS=your_piwigo_password \ +./restore-piwigo-docker.sh /opt/piwigo/piwigo_backup_20240115_120000.tar.gz +``` + +**Environment Variables for Restore:** +| Variable | Default | Description | +|----------|---------|-------------| +| `DOCKER_DIR` | `/opt/piwigo` | Docker project directory | +| `COMPOSE_FILE` | `docker-compose.yml` | Compose filename | +| `DB_CONTAINER` | `piwigo-db` | Database container name | +| `PIWIGO_CONTAINER` | `piwigo` | Piwigo container name | +| `DB_ROOT_PASS` | **required** | MariaDB root password | +| `DB_NAME` | `piwigo` | Database name | +| `DB_USER` | `piwigo` | Database user | +| `DB_PASS` | **required** | Database user password | +| `PIWIGO_DATA_DIR` | `${DOCKER_DIR}/piwigo-data` | Host data directory | +| `SKIP_DB` | `false` | Skip database restore | +| `SKIP_FILES` | `false` | Skip files restore | +| `FORCE` | `false` | Skip confirmations | + +### 4. Start Piwigo + +```bash +cd /opt/piwigo + +# Edit .env with your passwords (IMPORTANT!) +nano .env + +# Start containers +docker-compose up -d + +# Check logs +docker-compose logs -f piwigo +``` + +### 5. Access Piwigo + +Open your browser to `http://:8080` + +- If database was restored: Your existing Piwigo with all photos/users +- If fresh database: Piwigo installer will appear + +--- + +## Detailed Workflow + +### Backup Process (TrueNAS) + +The backup script performs these steps: + +1. **Detection**: Finds Kubernetes namespace, database credentials, and PVCs +2. **Manifests**: Exports all K8s resources (deployments, services, PVCs, secrets, etc.) +3. **Database**: Dumps MariaDB/MySQL database with `mariadb-dump`/`mysqldump` +4. **Files**: Creates temporary pods to copy data from PVCs: + - `uploads/` → Piwigo upload directory + - `config/` → Piwigo local/config directory + - `galleries/` → Piwigo galleries (if separate PVC) +5. **Archive**: Creates compressed `.tar.gz` with checksum +6. **Cleanup**: Removes old backups per retention policy +7. **Info**: Generates `RESTORE_INFO_.txt` with restore instructions + +### Restore Process (Docker) + +The restore script performs these steps: + +1. **Validation**: Verifies backup archive integrity (checksum) +2. **Extraction**: Unpacks backup to temporary directory +3. **Docker Compose**: Generates `docker-compose.yml` and `.env` template +4. **Database**: Recreates database and restores from SQL dump +5. **Files**: Syncs uploads, config, and galleries to host directory +6. **Permissions**: Fixes file ownership for www-data (UID 33) +7. **Guidance**: Shows next steps to start containers + +--- + +## Docker Compose Structure + +The generated `docker-compose.yml` creates: + +``` +piwigo/ +├── docker-compose.yml +├── .env # Your passwords (EDIT THIS!) +├── piwigo-data/ # Host-mounted Piwigo data +│ ├── upload/ # Photos and derivatives +│ ├── local/config/ # Piwigo configuration +│ └── galleries/ # Gallery structure (if used) +└── db-data/ # Database volume (Docker managed) +``` + +--- + +## Common Scenarios + +### Migration with Same Database Credentials + +If you want to keep the same database passwords: + +```bash +# On TrueNAS, note the DB_PASS from backup output or secret +# On Docker host, use same passwords: +DB_ROOT_PASS=same_as_truenas \ +DB_PASS=same_as_truenas \ +./restore-piwigo-docker.sh backup.tar.gz +``` + +### Fresh Database, Restore Only Files + +```bash +SKIP_DB=true \ +./restore-piwigo-docker.sh backup.tar.gz +``` + +### Restore Only Database + +```bash +SKIP_FILES=true \ +./restore-piwigo-docker.sh backup.tar.gz +``` + +### Custom Data Directory + +```bash +PIWIGO_DATA_DIR=/data/piwigo \ +./restore-piwigo-docker.sh backup.tar.gz +``` + +--- + +## Troubleshooting + +### Backup Fails: "Database dump failed" + +1. Check database credentials are correct +2. Ensure `mariadb-dump` or `mysqldump` is installed on TrueNAS +3. Verify database is accessible from TrueNAS host: + ```bash + mariadb -h -u -p -e "SELECT 1" + ``` + +### Backup Fails: "PVC not found" + +1. Check PVC names in TrueNAS: `k3s kubectl get pvc -n piwigo` +2. Set `PVC_UPLOADS`, `PVC_CONFIG`, `PVC_GALLERIES` explicitly + +### Restore Fails: "Database not ready" + +1. Check database container logs: `docker-compose logs db` +2. Ensure `DB_ROOT_PASS` in `.env` matches what you passed to restore script +3. Increase startup wait time in script if needed + +### Piwigo Shows "Database Connection Failed" + +1. Verify `.env` has correct `DB_HOST=db` (service name) +2. Check `DB_NAME`, `DB_USER`, `DB_PASS` match restore values +3. Ensure database container is healthy: `docker-compose ps` + +### Permission Errors on Files + +```bash +# Fix permissions manually +docker run --rm -v /opt/piwigo/piwigo-data:/data alpine:latest \ + sh -c "chown -R 33:33 /data && chmod -R 755 /data" +``` + +### Large Backup Times Out + +For very large galleries, increase Docker Compose healthcheck timeouts or run restore in steps: +```bash +# Restore DB first +SKIP_FILES=true ./restore-piwigo-docker.sh backup.tar.gz +# Then files +SKIP_DB=true ./restore-piwigo-docker.sh backup.tar.gz +``` + +--- + +## Security Notes + +1. **Never commit `.env` to version control** - contains passwords +2. **Use strong passwords** for `DB_ROOT_PASS` and `DB_PASS` +3. **Restrict backup access** - backup archives contain all photos and database +4. **Use HTTPS in production** - put Piwigo behind a reverse proxy (Traefik, Nginx Proxy Manager, Caddy) +5. **Regular backups** - Set up automated backups for the Docker deployment + +--- + +## Advanced: Reverse Proxy (HTTPS) + +Example with Traefik (add to `docker-compose.yml`): + +```yaml +services: + piwigo: + # ... existing config ... + labels: + - "traefik.enable=true" + - "traefik.http.routers.piwigo.rule=Host(\`photos.example.com\`)" + - "traefik.http.routers.piwigo.tls.certresolver=letsencrypt" + - "traefik.http.services.piwigo.loadbalancer.server.port=80" + networks: + - piwigo-net + - traefik-net # external network + +networks: + traefik-net: + external: true +``` + +--- + +## File Structure After Restore + +``` +/opt/piwigo/ +├── docker-compose.yml +├── .env # ← EDIT THIS FIRST +├── piwigo_backup_*.tar.gz # Backup archive (can delete after verify) +├── piwigo_backup_*.sha256 # Checksum +├── RESTORE_INFO_*.txt # Restore documentation +└── piwigo-data/ + ├── upload/ + │ ├── 2024/01/15/... + │ └── ... + ├── local/config/ + │ ├── config.inc.php + │ └── ... + └── galleries/ + └── ... +``` + +--- + +## Support + +If you encounter issues: + +1. Check the log output from both scripts +2. Verify all prerequisites are met +3. Ensure network connectivity between containers +4. Check TrueNAS app logs: `k3s kubectl logs -n piwigo -l app=piwigo` +5. Check Docker logs: `docker-compose logs piwigo` + +--- + +## License + +MIT License - Feel free to use and modify for your needs. \ No newline at end of file diff --git a/backup-piwigo-truenas.sh b/backup-piwigo-truenas.sh new file mode 100644 index 0000000..836af22 --- /dev/null +++ b/backup-piwigo-truenas.sh @@ -0,0 +1,518 @@ +#!/bin/bash +# ============================================================================= +# Piwigo Backup Script for TrueNAS App -> Docker Migration +# ============================================================================= +# This script backs up a Piwigo instance running as a TrueNAS App (k3s/Kubernetes) +# to a TrueNAS dataset/share, ready for restoration to a Docker container. +# +# Run this script ON the TrueNAS host (via SSH or TrueNAS Shell). +# +# Requirements: +# - TrueNAS with Piwigo app installed +# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl) +# - MariaDB/MySQL client tools (mariadb-dump/mysqldump) +# - Write access to backup destination dataset +# ============================================================================= + +set -euo pipefail + +# ============================================================================= +# CONFIGURATION - Adjust these values for your environment +# ============================================================================= + +# TrueNAS App namespace (usually the app name) +APP_NAMESPACE="${APP_NAMESPACE:-piwigo}" + +# Backup destination (TrueNAS dataset path) +BACKUP_DEST="${BACKUP_DEST:/mnt/tank/backups/piwigo}" + +# Database details (auto-detected if not set) +DB_HOST="${DB_HOST:-}" +DB_PORT="${DB_PORT:-3306}" +DB_NAME="${DB_NAME:-piwigo}" +DB_USER="${DB_USER:-piwigo}" +DB_PASS="${DB_PASS:-}" + +# Piwigo persistent volume claim names (auto-detected if not set) +PVC_UPLOADS="${PVC_UPLOADS:-}" +PVC_CONFIG="${PVC_CONFIG:-}" +PVC_GALLERIES="${PVC_GALLERIES:-}" + +# Retention: keep last N backups +RETENTION_COUNT="${RETENTION_COUNT:-7}" + +# Compression level (1-9, higher = smaller but slower) +COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}" + +# ============================================================================= +# INTERNAL VARIABLES +# ============================================================================= + +TIMESTAMP=$(date +"%Y%m%d_%H%M%S") +BACKUP_DIR="${BACKUP_DEST}/piwigo_backup_${TIMESTAMP}" +KUBECTL_CMD="${KUBECTL_CMD:-/usr/local/bin/k3s kubectl}" +LOG_FILE="${BACKUP_DIR}/backup.log" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# ============================================================================= +# HELPER FUNCTIONS +# ============================================================================= + +log() { + local level="$1" + shift + local msg="$*" + local timestamp=$(date +"%Y-%m-%d %H:%M:%S") + echo -e "${timestamp} [${level}] ${msg}" | tee -a "${LOG_FILE}" +} + +info() { log "INFO" "${BLUE}$*${NC}"; } +warn() { log "WARN" "${YELLOW}$*${NC}"; } +error() { log "ERROR" "${RED}$*${NC}"; } +success() { log "SUCCESS" "${GREEN}$*${NC}"; } + +die() { + error "$*" + exit 1 +} + +run_cmd() { + info "Running: $*" + if ! "$@" 2>&1 | tee -a "${LOG_FILE}"; then + die "Command failed: $*" + fi +} + +# ============================================================================= +# DETECTION FUNCTIONS +# ============================================================================= + +detect_kubectl() { + if [[ ! -x "${KUBECTL_CMD}" ]]; then + # Try common locations + for cmd in /usr/local/bin/k3s /usr/bin/k3s /usr/local/bin/kubectl /usr/bin/kubectl; do + if [[ -x "${cmd}" ]]; then + if [[ "${cmd}" == *k3s ]]; then + KUBECTL_CMD="${cmd} kubectl" + else + KUBECTL_CMD="${cmd}" + fi + info "Found kubectl at: ${KUBECTL_CMD}" + return 0 + fi + done + die "kubectl not found. Please install k3s or kubectl." + fi + info "Using kubectl: ${KUBECTL_CMD}" +} + +detect_namespace() { + if [[ -z "${APP_NAMESPACE}" ]]; then + info "Auto-detecting Piwigo namespace..." + local ns=$(${KUBECTL_CMD} get pods --all-namespaces -l app=piwigo -o jsonpath='{.items[0].metadata.namespace}' 2>/dev/null || true) + if [[ -n "${ns}" ]]; then + APP_NAMESPACE="${ns}" + info "Detected namespace: ${APP_NAMESPACE}" + else + # Try common namespaces + for ns in piwigo piwigo-app apps-piwigo; do + if ${KUBECTL_CMD} get namespace "${ns}" >/dev/null 2>&1; then + APP_NAMESPACE="${ns}" + info "Found namespace: ${APP_NAMESPACE}" + return 0 + fi + done + die "Could not detect Piwigo namespace. Set APP_NAMESPACE manually." + fi + fi +} + +detect_database() { + info "Detecting database configuration..." + + # Try to get database credentials from Kubernetes secrets + local secret_name=$(${KUBECTL_CMD} get secrets -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(mariadb|mysql|database|piwigo)' | head -1 | cut -d/ -f2 || true) + + if [[ -n "${secret_name}" ]]; then + info "Found database secret: ${secret_name}" + DB_HOST="${DB_HOST:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.host}' 2>/dev/null | base64 -d || echo "")}" + DB_PORT="${DB_PORT:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.port}' 2>/dev/null | base64 -d || echo "3306")}" + DB_NAME="${DB_NAME:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.database}' 2>/dev/null | base64 -d || echo "piwigo")}" + DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "piwigo")}" + DB_PASS="${DB_PASS:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.password}' 2>/dev/null | base64 -d || echo "")}" + + # Also check for mariadb-root-password or similar + if [[ -z "${DB_PASS}" ]]; then + DB_PASS=$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.mariadb-root-password}' 2>/dev/null | base64 -d || true) + fi + if [[ -z "${DB_PASS}" ]]; then + DB_PASS=$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.mysql-root-password}' 2>/dev/null | base64 -d || true) + fi + fi + + # Try to detect from Piwigo config if running + if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then + info "Trying to detect from Piwigo pod config..." + local piwigo_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=piwigo -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true) + if [[ -n "${piwigo_pod}" ]]; then + # Try to read config from the pod + local config=$(${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${piwigo_pod}" -- cat /var/www/html/local/config/config.inc.php 2>/dev/null || true) + if [[ -n "${config}" ]]; then + DB_HOST="${DB_HOST:-$(echo "${config}" | grep -oP \"'db_host'\s*=>\s*'\K[^']+\" || true)}" + DB_USER="${DB_USER:-$(echo "${config}" | grep -oP \"'db_user'\s*=>\s*'\K[^']+\" || true)}" + DB_PASS="${DB_PASS:-$(echo "${config}" | grep -oP \"'db_password'\s*=>\s*'\K[^']+\" || true)}" + DB_NAME="${DB_NAME:-$(echo "${config}" | grep -oP \"'db_name'\s*=>\s*'\K[^']+\" || true)}" + fi + fi + fi + + # Fallback: check for MariaDB/MySQL pod in same namespace + if [[ -z "${DB_HOST}" ]]; then + local db_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(mariadb|mysql)' | head -1 | cut -d/ -f2 || true) + if [[ -n "${db_pod}" ]]; then + DB_HOST="${db_pod}" + info "Detected database pod: ${DB_HOST}" + fi + fi + + # Final validation + if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then + warn "Could not fully auto-detect database credentials." + warn "Please set DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS environment variables." + warn "Or ensure the database secret is labeled correctly in Kubernetes." + else + info "Database: ${DB_USER}@${DB_HOST}:${DB_PORT}/${DB_NAME}" + fi +} + +detect_pvcs() { + info "Detecting persistent volume claims..." + + local pvcs=$(${KUBECTL_CMD} get pvc -n "${APP_NAMESPACE}" -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.volumeName}{"\n"}{end}' 2>/dev/null || true) + + if [[ -n "${pvcs}" ]]; then + echo "${pvcs}" | while read -r name volume; do + info "Found PVC: ${name} -> ${volume}" + case "${name}" in + *upload*|*gallery*|*image*|*photo*) + PVC_UPLOADS="${PVC_UPLOADS:-${name}}" + ;; + *config*|*data*) + PVC_CONFIG="${PVC_CONFIG:-${name}}" + ;; + *gallery*) + PVC_GALLERIES="${PVC_GALLERIES:-${name}}" + ;; + esac + done + fi + + # If not detected, try common names + PVC_UPLOADS="${PVC_UPLOADS:-piwigo-uploads}" + PVC_CONFIG="${PVC_CONFIG:-piwigo-config}" + PVC_GALLERIES="${PVC_GALLERIES:-piwigo-galleries}" + + info "Using PVCs: uploads=${PVC_UPLOADS}, config=${PVC_CONFIG}, galleries=${PVC_GALLERIES}" +} + +# ============================================================================= +# BACKUP FUNCTIONS +# ============================================================================= + +backup_database() { + info "Backing up database..." + + local db_dump="${BACKUP_DIR}/database/piwigo_${TIMESTAMP}.sql" + + mkdir -p "${BACKUP_DIR}/database" + + # Check if we have mariadb-dump or mysqldump + local dump_cmd="" + if command -v mariadb-dump >/dev/null 2>&1; then + dump_cmd="mariadb-dump" + elif command -v mysqldump >/dev/null 2>&1; then + dump_cmd="mysqldump" + else + die "Neither mariadb-dump nor mysqldump found. Install mariadb-client or mysql-client." + fi + + info "Using ${dump_cmd} for database dump" + + # Build connection parameters + local conn_params=( + "-h" "${DB_HOST}" + "-P" "${DB_PORT}" + "-u" "${DB_USER}" + "--single-transaction" + "--routines" + "--triggers" + "--events" + "--hex-blob" + "--complete-insert" + "--extended-insert" + "--quick" + "--lock-tables=false" + ) + + # Use password from environment or prompt + if [[ -n "${DB_PASS}" ]]; then + export MYSQL_PWD="${DB_PASS}" + fi + + info "Dumping database ${DB_NAME} from ${DB_HOST}:${DB_PORT}..." + if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then + die "Database dump failed. Check credentials and connectivity." + fi + + unset MYSQL_PWD + + # Compress the dump + info "Compressing database dump..." + gzip -${COMPRESSION_LEVEL} "${db_dump}" + db_dump="${db_dump}.gz" + + local size=$(du -h "${db_dump}" | cut -f1) + success "Database backup complete: ${db_dump} (${size})" + + # Also create a schema-only dump for reference + ${dump_cmd} "${conn_params[@]}" --no-data "${DB_NAME}" | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/piwigo_schema_${TIMESTAMP}.sql.gz" +} + +backup_pvc() { + local pvc_name="$1" + local dest_subdir="$2" + local description="$3" + + info "Backing up ${description} (PVC: ${pvc_name})..." + + local dest_dir="${BACKUP_DIR}/${dest_subdir}" + mkdir -p "${dest_dir}" + + # Check if PVC exists + if ! ${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" >/dev/null 2>&1; then + warn "PVC ${pvc_name} not found in namespace ${APP_NAMESPACE}, skipping..." + return 0 + fi + + # Get the volume name + local volume_name=$(${KUBECTL_CMD} get pvc "${pvc_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.spec.volumeName}' 2>/dev/null || true) + + if [[ -z "${volume_name}" ]]; then + warn "PVC ${pvc_name} is not bound to a volume, skipping..." + return 0 + fi + + info "PVC ${pvc_name} bound to volume ${volume_name}" + + # Create a temporary pod to access the volume + local pod_name="piwigo-backup-${pvc_name}-${TIMESTAMP}" + local yaml_file="/tmp/${pod_name}.yaml" + + cat > "${yaml_file}" <>"${LOG_FILE}" 2>&1 + + # Wait for pod to be ready + local retries=30 + while [[ ${retries} -gt 0 ]]; do + local phase=$(${KUBECTL_CMD} get pod "${pod_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.status.phase}' 2>/dev/null || echo "Unknown") + if [[ "${phase}" == "Running" ]]; then + break + fi + sleep 2 + ((retries--)) + done + + if [[ ${retries} -eq 0 ]]; then + warn "Timeout waiting for backup pod, cleaning up..." + ${KUBECTL_CMD} delete pod "${pod_name}" -n "${APP_NAMESPACE}" --ignore-not-found=true >>"${LOG_FILE}" 2>&1 + rm -f "${yaml_file}" + return 1 + fi + + # Copy data from pod + info "Copying data from PVC..." + if ! ${KUBECTL_CMD} cp "${APP_NAMESPACE}/${pod_name}:/data/." "${dest_dir}/" >>"${LOG_FILE}" 2>&1; then + warn "Failed to copy data from PVC ${pvc_name}" + else + local count=$(find "${dest_dir}" -type f | wc -l) + local size=$(du -sh "${dest_dir}" | cut -f1) + success "${description} backup complete: ${count} files, ${size}" + fi + + # Cleanup + info "Cleaning up temporary pod..." + ${KUBECTL_CMD} delete pod "${pod_name}" -n "${APP_NAMESPACE}" --ignore-not-found=true >>"${LOG_FILE}" 2>&1 + rm -f "${yaml_file}" +} + +backup_manifests() { + info "Backing up Kubernetes manifests..." + + local manifest_dir="${BACKUP_DIR}/manifests" + mkdir -p "${manifest_dir}" + + # Export all resources in the namespace + ${KUBECTL_CMD} get all,configmap,secret,pvc,ingress,serviceaccount,role,rolebinding -n "${APP_NAMESPACE}" -o yaml > "${manifest_dir}/all-resources.yaml" 2>>"${LOG_FILE}" || true + + # Also export individually for easier reading + for resource in deployment statefulset service configmap secret pvc ingress; do + ${KUBECTL_CMD} get "${resource}" -n "${APP_NAMESPACE}" -o yaml > "${manifest_dir}/${resource}s.yaml" 2>>"${LOG_FILE}" || true + done + + success "Manifests backed up to ${manifest_dir}" +} + +create_archive() { + info "Creating compressed archive..." + + local archive_name="piwigo_backup_${TIMESTAMP}.tar.gz" + local archive_path="${BACKUP_DEST}/${archive_name}" + + # Create tar.gz of the backup directory + tar -czf "${archive_path}" -C "${BACKUP_DEST}" "piwigo_backup_${TIMESTAMP}" 2>>"${LOG_FILE}" + + local size=$(du -h "${archive_path}" | cut -f1) + success "Archive created: ${archive_path} (${size})" + + # Create checksum + sha256sum "${archive_path}" > "${archive_path}.sha256" + info "SHA256: $(cat "${archive_path}.sha256")" + + # Clean up uncompressed directory to save space + info "Cleaning up uncompressed backup directory..." + rm -rf "${BACKUP_DIR}" + + echo "${archive_path}" +} + +cleanup_old_backups() { + info "Cleaning up old backups (keeping last ${RETENTION_COUNT})..." + + cd "${BACKUP_DEST}" + ls -1t piwigo_backup_*.tar.gz 2>/dev/null | tail -n +$((RETENTION_COUNT + 1)) | while read -r file; do + info "Removing old backup: ${file}" + rm -f "${file}" "${file}.sha256" + done + + success "Cleanup complete" +} + +generate_restore_info() { + info "Generating restore information..." + + cat > "${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" < +3. Follow the prompts + +Database Connection for Docker: +- Host: (usually 'db' or 'mariadb' in docker-compose) +- Port: 3306 +- Database: piwigo +- User: piwigo +- Password: + +Volume Mounts for Docker: +- ./piwigo-data:/var/www/html + - uploads/ -> /var/www/html/upload/ + - config/ -> /var/www/html/local/config/ + - galleries/ -> /var/www/html/galleries/ (if used) + +EOF + + success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" +} + +# ============================================================================= +# MAIN EXECUTION +# ============================================================================= + +main() { + info "======================================" + info "Piwigo TrueNAS App Backup Started" + info "======================================" + info "Timestamp: ${TIMESTAMP}" + info "Backup destination: ${BACKUP_DEST}" + + # Create backup directory + mkdir -p "${BACKUP_DIR}" + info "Backup directory: ${BACKUP_DIR}" + + # Detection phase + detect_kubectl + detect_namespace + detect_database + detect_pvcs + + # Backup phase + backup_manifests + backup_database + backup_pvc "${PVC_UPLOADS}" "uploads" "Uploads" + backup_pvc "${PVC_CONFIG}" "config" "Configuration" + backup_pvc "${PVC_GALLERIES}" "galleries" "Galleries" + + # Archive and cleanup + local archive=$(create_archive) + cleanup_old_backups + generate_restore_info + + info "======================================" + success "Backup completed successfully!" + info "======================================" + info "Archive: ${archive}" + info "Checksum: ${archive}.sha256" + info "Restore info: ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt" + info "" + info "Next steps:" + info "1. Copy ${archive} to your Docker host" + info "2. Run the restore script on the Docker host" + info "3. Verify the restored Piwigo instance" +} + +# Run main if not sourced +if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then + main "$@" +fi \ No newline at end of file diff --git a/restore-piwigo-docker.sh b/restore-piwigo-docker.sh new file mode 100644 index 0000000..e30bdca --- /dev/null +++ b/restore-piwigo-docker.sh @@ -0,0 +1,500 @@ +#!/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 "$@" \ No newline at end of file