Files
truenas-app-to-docker/backup-piwigo-truenas.sh
T

589 lines
22 KiB
Bash

#!/bin/bash
# =============================================================================
# Piwigo Backup Script for TrueNAS 27+ App -> Docker Migration
# =============================================================================
# This script backs up a Piwigo instance running as a TrueNAS App
# to a TrueNAS dataset/share, ready for restoration to a Docker container.
#
# TrueNAS 27 (Electric Eel) stores app data directly in datasets accessible
# from the host filesystem. No kubectl/k3s required.
#
# Run this script ON the TrueNAS host (via SSH or TrueNAS Shell).
#
# Requirements:
# - TrueNAS 27+ with Piwigo app installed
# - MariaDB/MySQL client tools (mariadb-dump/mysqldump) for database dump
# - Write access to backup destination dataset
# - Read access to Piwigo app datasets (configured in app settings)
# =============================================================================
set -euo pipefail
# =============================================================================
# CONFIGURATION - Adjust these values for your environment
# =============================================================================
# Backup destination (TrueNAS dataset path)
BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/piwigo}"
# ---- Database Configuration ----
# If the database is running as a separate container/app, provide connection details
# If using the built-in MariaDB from the Piwigo app chart, it might be accessible via localhost
DB_HOST="${DB_HOST:-localhost}"
DB_PORT="${DB_PORT:-3306}"
DB_NAME="${DB_NAME:-piwigo}"
DB_USER="${DB_USER:-piwigo}"
DB_PASS="${DB_PASS:-}" # Required! Get from app config or secret
# Database container name (optional - auto-detected if not set)
DB_CONTAINER="${DB_CONTAINER:-}"
# Database password env var name in container (optional - auto-detected if not set)
# Common names: MYSQL_PASSWORD, MYSQL_ROOT_PASSWORD, MARIADB_PASSWORD, MARIADB_ROOT_PASSWORD
DB_PASSWORD_ENV="${DB_PASSWORD_ENV:-}"
# ---- Piwigo Data Paths (Host filesystem paths) ----
# These are the dataset paths you configured in the Piwigo app settings
# Example: /mnt/tank/apps/piwigo/uploads
# Example: /mnt/tank/apps/piwigo/config
# Example: /mnt/tank/apps/piwigo/galleries
PIWIGO_UPLOADS_PATH="${PIWIGO_UPLOADS_PATH:-}"
PIWIGO_CONFIG_PATH="${PIWIGO_CONFIG_PATH:-}"
PIWIGO_GALLERIES_PATH="${PIWIGO_GALLERIES_PATH:-}"
# Alternative: Single base path if all data is under one dataset
# PIWIGO_BASE_PATH="${PIWIGO_BASE_PATH:-/mnt/tank/apps/piwigo}"
# 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}"
mkdir -p "${BACKUP_DIR}"
LOG_FILE="${BACKUP_DIR}/backup.log"
# Debug: show config values
echo "DEBUG: BACKUP_DEST='${BACKUP_DEST}'" >&2
echo "DEBUG: BACKUP_DIR='${BACKUP_DIR}'" >&2
# 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
}
# =============================================================================
# VALIDATION FUNCTIONS
# =============================================================================
validate_paths() {
info "Validating data paths..."
local has_paths=false
# Check individual paths
if [[ -n "${PIWIGO_UPLOADS_PATH}" ]] && [[ -d "${PIWIGO_UPLOADS_PATH}" ]]; then
info "Found uploads path: ${PIWIGO_UPLOADS_PATH}"
has_paths=true
elif [[ -n "${PIWIGO_UPLOADS_PATH}" ]]; then
warn "Uploads path does not exist: ${PIWIGO_UPLOADS_PATH}"
fi
if [[ -n "${PIWIGO_CONFIG_PATH}" ]] && [[ -d "${PIWIGO_CONFIG_PATH}" ]]; then
info "Found config path: ${PIWIGO_CONFIG_PATH}"
has_paths=true
elif [[ -n "${PIWIGO_CONFIG_PATH}" ]]; then
warn "Config path does not exist: ${PIWIGO_CONFIG_PATH}"
fi
if [[ -n "${PIWIGO_GALLERIES_PATH}" ]] && [[ -d "${PIWIGO_GALLERIES_PATH}" ]]; then
info "Found galleries path: ${PIWIGO_GALLERIES_PATH}"
has_paths=true
elif [[ -n "${PIWIGO_GALLERIES_PATH}" ]]; then
warn "Galleries path does not exist: ${PIWIGO_GALLERIES_PATH}"
fi
# If no individual paths set, try to auto-detect from common locations
if [[ "${has_paths}" == "false" ]]; then
info "No explicit paths set, trying to auto-detect..."
detect_paths
fi
if [[ "${has_paths}" == "false" ]]; then
die "No valid Piwigo data paths found. Please set PIWIGO_UPLOADS_PATH, PIWIGO_CONFIG_PATH, PIWIGO_GALLERIES_PATH environment variables to the dataset paths configured in your Piwigo app."
fi
}
detect_paths() {
# Common TrueNAS app dataset locations
local common_bases=(
"/mnt/tank/apps/piwigo"
"/mnt/pool/apps/piwigo"
"/mnt/data/apps/piwigo"
"/mnt/storage/apps/piwigo"
"/mnt/apps/piwigo"
)
for base in "${common_bases[@]}"; do
if [[ -d "${base}" ]]; then
info "Found potential base path: ${base}"
if [[ -d "${base}/uploads" ]] && [[ -z "${PIWIGO_UPLOADS_PATH}" ]]; then
PIWIGO_UPLOADS_PATH="${base}/uploads"
info "Auto-detected uploads: ${PIWIGO_UPLOADS_PATH}"
fi
if [[ -d "${base}/config" ]] && [[ -z "${PIWIGO_CONFIG_PATH}" ]]; then
PIWIGO_CONFIG_PATH="${base}/config"
info "Auto-detected config: ${PIWIGO_CONFIG_PATH}"
fi
if [[ -d "${base}/galleries" ]] && [[ -z "${PIWIGO_GALLERIES_PATH}" ]]; then
PIWIGO_GALLERIES_PATH="${base}/galleries"
info "Auto-detected galleries: ${PIWIGO_GALLERIES_PATH}"
fi
# Also check for 'data' as uploads
if [[ -d "${base}/data" ]] && [[ -z "${PIWIGO_UPLOADS_PATH}" ]]; then
PIWIGO_UPLOADS_PATH="${base}/data"
info "Auto-detected uploads (as data): ${PIWIGO_UPLOADS_PATH}"
fi
# If we found at least one, break
if [[ -n "${PIWIGO_UPLOADS_PATH}" ]] || [[ -n "${PIWIGO_CONFIG_PATH}" ]] || [[ -n "${PIWIGO_GALLERIES_PATH}" ]]; then
return 0
fi
fi
done
}
validate_database() {
info "Validating database connection..."
if [[ -z "${DB_PASS}" ]]; then
warn "DB_PASS not set. Trying to find it from common locations..."
find_db_password
fi
if [[ -z "${DB_PASS}" ]]; then
die "Database password (DB_PASS) is required. Please set it or ensure it can be auto-detected."
fi
# Test connection - try host tools first, then docker exec
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"
fi
if [[ -n "${dump_cmd}" ]]; then
# Host tools available
export MYSQL_PWD="${DB_PASS}"
if ! ${dump_cmd} -h "${DB_HOST}" -P "${DB_PORT}" -u "${DB_USER}" -e "SELECT 1" >/dev/null 2>&1; then
unset MYSQL_PWD
die "Cannot connect to database at ${DB_HOST}:${DB_PORT} as ${DB_USER}. Check credentials and ensure database is accessible from host."
fi
unset MYSQL_PWD
else
# No host tools, try docker exec
info "Host database tools not found, trying docker exec..."
if ! command -v docker >/dev/null 2>&1; then
die "Neither mariadb-dump/mysqldump nor docker found. Cannot dump database."
fi
local db_container="${DB_CONTAINER}"
if [[ -z "${db_container}" ]]; then
# Prefer TrueNAS 27+ style container names (ix-*)
db_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mariadb' | head -1 || true)
if [[ -z "${db_container}" ]]; then
db_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mysql' | head -1 || true)
fi
if [[ -z "${db_container}" ]]; then
db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|piwigo.*db)' | head -1 || true)
fi
fi
if [[ -z "${db_container}" ]]; then
die "No MariaDB/MySQL container found. Cannot dump database."
fi
info "Using database container: ${db_container}"
if ! docker exec "${db_container}" mariadb -u "${DB_USER}" -p"${DB_PASS}" -e "SELECT 1" >/dev/null 2>&1; then
die "Cannot connect to database in container ${db_container}. Check credentials."
fi
fi
success "Database connection validated"
}
find_db_password() {
# Try to find password from common locations
local possible_files=(
"/mnt/tank/apps/piwigo/.env"
"/mnt/pool/apps/piwigo/.env"
"/mnt/data/apps/piwigo/.env"
"/mnt/storage/apps/piwigo/.env"
"/mnt/apps/piwigo/.env"
"/etc/piwigo/db_password"
"/root/.piwigo_db_password"
"${PIWIGO_CONFIG_PATH}/.env"
"${PIWIGO_CONFIG_PATH}/db_password"
)
for file in "${possible_files[@]}"; do
if [[ -n "${file}" ]] && [[ -f "${file}" ]]; then
# Try to extract password from file
local pass=$(grep -iE '(password|passwd)' "${file}" 2>/dev/null | head -1 | sed -E 's/.*[=:]\s*//' | sed -E 's/["\'\'']//g' | xargs)
if [[ -n "${pass}" ]]; then
DB_PASS="${pass}"
info "Found database password in ${file}"
return 0
fi
fi
done
# Check if there's a MariaDB container running that we can get password from
if command -v docker >/dev/null 2>&1; then
local mariadb_container="${DB_CONTAINER}"
if [[ -z "${mariadb_container}" ]]; then
# Prefer TrueNAS 27+ style container names (ix-*)
mariadb_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mariadb' | head -1 || true)
if [[ -z "${mariadb_container}" ]]; then
mariadb_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mysql' | head -1 || true)
fi
if [[ -z "${mariadb_container}" ]]; then
mariadb_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|piwigo.*db)' | head -1 || true)
fi
fi
if [[ -n "${mariadb_container}" ]]; then
info "Found potential MariaDB container: ${mariadb_container}"
# Try to get password from container env - check multiple possible env var names
local password_env_vars=(
"MYSQL_PASSWORD"
"MYSQL_ROOT_PASSWORD"
"MARIADB_PASSWORD"
"MARIADB_ROOT_PASSWORD"
"MYSQL_ROOT_PASSWORD_FILE"
"MARIADB_ROOT_PASSWORD_FILE"
)
# If user specified a specific env var name, check that first
if [[ -n "${DB_PASSWORD_ENV}" ]]; then
password_env_vars=("${DB_PASSWORD_ENV}" "${password_env_vars[@]}")
fi
for env_var in "${password_env_vars[@]}"; do
local pass=$(docker inspect "${mariadb_container}" 2>/dev/null | grep -iE "\"${env_var}\"" | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
if [[ -n "${pass}" ]]; then
DB_PASS="${pass}"
info "Found database password from container env var: ${env_var}"
return 0
fi
done
# Also check for _FILE variants (Docker secrets)
for env_var in MYSQL_PASSWORD_FILE MYSQL_ROOT_PASSWORD_FILE MARIADB_PASSWORD_FILE MARIADB_ROOT_PASSWORD_FILE; do
local file_path=$(docker inspect "${mariadb_container}" 2>/dev/null | grep -iE "\"${env_var}\"" | head -1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
if [[ -n "${file_path}" ]] && [[ -f "${file_path}" ]]; then
local pass=$(cat "${file_path}" 2>/dev/null | xargs)
if [[ -n "${pass}" ]]; then
DB_PASS="${pass}"
info "Found database password from container secret file: ${env_var}"
return 0
fi
fi
done
fi
fi
}
# =============================================================================
# BACKUP FUNCTIONS
# =============================================================================
backup_database() {
info "Backing up database..."
local db_dump="${BACKUP_DIR}/database/piwigo_${TIMESTAMP}.sql"
mkdir -p "${BACKUP_DIR}/database"
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"
fi
if [[ -n "${dump_cmd}" ]]; then
# Use host tools
info "Using ${dump_cmd} for database dump"
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"
)
export MYSQL_PWD="${DB_PASS}"
info "Dumping database ${DB_NAME} from ${DB_HOST}:${DB_PORT}..."
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
unset MYSQL_PWD
die "Database dump failed. Check credentials and connectivity."
fi
unset MYSQL_PWD
else
# Use docker exec
if ! command -v docker >/dev/null 2>&1; then
die "Neither mariadb-dump/mysqldump nor docker found. Cannot dump database."
fi
local db_container="${DB_CONTAINER}"
if [[ -z "${db_container}" ]]; then
# Prefer TrueNAS 27+ style container names (ix-*)
db_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mariadb' | head -1 || true)
if [[ -z "${db_container}" ]]; then
db_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mysql' | head -1 || true)
fi
if [[ -z "${db_container}" ]]; then
db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|piwigo.*db)' | head -1 || true)
fi
fi
if [[ -z "${db_container}" ]]; then
die "No MariaDB/MySQL container found. Cannot dump database."
fi
info "Using docker exec on container: ${db_container}"
info "Dumping database ${DB_NAME}..."
if ! docker exec "${db_container}" mariadb-dump -u "${DB_USER}" -p"${DB_PASS}" \
--single-transaction --routines --triggers --events --hex-blob \
--complete-insert --extended-insert --quick --lock-tables=false \
"${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
die "Database dump failed via docker exec."
fi
fi
# 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
if [[ -n "${dump_cmd}" ]]; then
export MYSQL_PWD="${DB_PASS}"
${dump_cmd} "${conn_params[@]}" --no-data "${DB_NAME}" | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/piwigo_schema_${TIMESTAMP}.sql.gz"
unset MYSQL_PWD
else
local db_container="${DB_CONTAINER}"
if [[ -z "${db_container}" ]]; then
# Prefer TrueNAS 27+ style container names (ix-*)
db_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mariadb' | head -1 || true)
if [[ -z "${db_container}" ]]; then
db_container=$(docker ps --format '{{.Names}}' | grep -iE '^ix-.*mysql' | head -1 || true)
fi
if [[ -z "${db_container}" ]]; then
db_container=$(docker ps --format '{{.Names}}' | grep -iE '(mariadb|mysql|piwigo.*db)' | head -1 || true)
fi
fi
if [[ -n "${db_container}" ]]; then
docker exec "${db_container}" mariadb-dump -u "${DB_USER}" -p"${DB_PASS}" \
--no-data --single-transaction --routines --triggers --events \
"${DB_NAME}" | gzip -${COMPRESSION_LEVEL} > "${BACKUP_DIR}/database/piwigo_schema_${TIMESTAMP}.sql.gz"
fi
fi
}
backup_directory() {
local src_path="$1"
local dest_subdir="$2"
local description="$3"
info "Backing up ${description}..."
local dest_dir="${BACKUP_DIR}/${dest_subdir}"
mkdir -p "${dest_dir}"
if [[ ! -d "${src_path}" ]]; then
warn "Source path does not exist: ${src_path}"
return 0
fi
info "Copying from ${src_path} to ${dest_dir}..."
if ! rsync -av "${src_path}/" "${dest_dir}/" 2>&1 | tee -a "${LOG_FILE}"; then
warn "Failed to copy data from ${src_path}"
return 1
fi
local count=$(find "${dest_dir}" -type f | wc -l)
local size=$(du -sh "${dest_dir}" | cut -f1)
success "${description} backup complete: ${count} files, ${size}"
}
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" <<EOF
Piwigo Backup Restore Information
=================================
Backup Date: $(date)
Backup Timestamp: ${TIMESTAMP}
Source: TrueNAS 27+ App (direct dataset access)
Database: ${DB_NAME} on ${DB_HOST}:${DB_PORT} as ${DB_USER}
Backup Contents:
- database/piwigo_${TIMESTAMP}.sql.gz - Full database dump
- database/piwigo_schema_${TIMESTAMP}.sql.gz - Schema only
- uploads/ - Piwigo uploads directory
- config/ - Piwigo configuration (local/config/)
- galleries/ - Piwigo galleries (if separate path)
To restore to Docker:
1. Copy the backup archive to your Docker host
2. Run the restore script: ./restore-piwigo-docker.sh <backup_archive.tar.gz>
3. Follow the prompts
Database Connection for Docker:
- Host: <your-docker-db-host> (usually 'db' or 'mariadb' in docker-compose)
- Port: 3306
- Database: piwigo
- User: piwigo
- Password: <set in docker-compose .env>
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)
Source Paths Used:
- Uploads: ${PIWIGO_UPLOADS_PATH:-<not set>}
- Config: ${PIWIGO_CONFIG_PATH:-<not set>}
- Galleries: ${PIWIGO_GALLERIES_PATH:-<not set>}
EOF
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
}
# =============================================================================
# MAIN EXECUTION
# =============================================================================
main() {
info "======================================"
info "Piwigo TrueNAS 27+ App Backup Started"
info "======================================"
info "Timestamp: ${TIMESTAMP}"
info "Backup destination: ${BACKUP_DEST}"
info "Backup directory: ${BACKUP_DIR}"
# Validate prerequisites
validate_paths
validate_database
# Backup phase
backup_database
backup_directory "${PIWIGO_UPLOADS_PATH}" "uploads" "Uploads"
backup_directory "${PIWIGO_CONFIG_PATH}" "config" "Configuration"
backup_directory "${PIWIGO_GALLERIES_PATH}" "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