Add nextcloud app scripts

This commit is contained in:
2026-10-22 17:57:04 +03:00
parent b068a69d1f
commit f9a4ec65ff
2 changed files with 1158 additions and 0 deletions
+562
View File
@@ -0,0 +1,562 @@
#!/bin/bash
# =============================================================================
# Nextcloud Backup Script for TrueNAS App -> Docker Migration
# =============================================================================
# This script backs up a Nextcloud 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 Nextcloud app installed
# - Access to k3s/kubectl (usually via /usr/local/bin/k3s kubectl)
# - PostgreSQL client tools (pg_dump) or MariaDB/MySQL client tools
# - 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:-nextcloud}"
# Backup destination (TrueNAS dataset path)
BACKUP_DEST="${BACKUP_DEST:-/mnt/tank/backups/nextcloud}"
# Database details (auto-detected if not set)
DB_TYPE="${DB_TYPE:-postgresql}" # postgresql or mariadb
DB_HOST="${DB_HOST:-}"
DB_PORT="${DB_PORT:-}"
DB_NAME="${DB_NAME:-nextcloud}"
DB_USER="${DB_USER:-nextcloud}"
DB_PASS="${DB_PASS:-}"
# Nextcloud persistent volume claim names (auto-detected if not set)
PVC_DATA="${PVC_DATA:-}"
PVC_CONFIG="${PVC_CONFIG:-}"
PVC_APPS="${PVC_APPS:-}"
# Retention: keep last N backups
RETENTION_COUNT="${RETENTION_COUNT:-7}"
# Compression level (1-9, higher = smaller but slower)
COMPRESSION_LEVEL="${COMPRESSION_LEVEL:-6}"
# Put Nextcloud in maintenance mode during backup
MAINTENANCE_MODE="${MAINTENANCE_MODE:-true}"
# =============================================================================
# INTERNAL VARIABLES
# =============================================================================
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_DIR="${BACKUP_DEST}/nextcloud_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'
# =============================================================================
# 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
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 Nextcloud namespace..."
local ns=$(${KUBECTL_CMD} get pods --all-namespaces -l app=nextcloud -o jsonpath='{.items[0].metadata.namespace}' 2>/dev/null || true)
if [[ -n "${ns}" ]]; then
APP_NAMESPACE="${ns}"
info "Detected namespace: ${APP_NAMESPACE}"
else
for ns in nextcloud nextcloud-app apps-nextcloud; 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 Nextcloud 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 '(postgres|mariadb|mysql|database|nextcloud)' | head -1 | cut -d/ -f2 || true)
if [[ -n "${secret_name}" ]]; then
info "Found database secret: ${secret_name}"
if [[ "${DB_TYPE}" == "postgresql" ]]; then
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 "5432")}"
DB_NAME="${DB_NAME:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.database}' 2>/dev/null | base64 -d || echo "nextcloud")}"
DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "nextcloud")}"
DB_PASS="${DB_PASS:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.password}' 2>/dev/null | base64 -d || echo "")}"
if [[ -z "${DB_PASS}" ]]; then
DB_PASS=$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.postgres-password}' 2>/dev/null | base64 -d || true)
fi
else
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 "nextcloud")}"
DB_USER="${DB_USER:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.username}' 2>/dev/null | base64 -d || echo "nextcloud")}"
DB_PASS="${DB_PASS:-$(${KUBECTL_CMD} get secret "${secret_name}" -n "${APP_NAMESPACE}" -o jsonpath='{.data.password}' 2>/dev/null | base64 -d || echo "")}"
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
fi
# Try to detect from Nextcloud config.php if running
if [[ -z "${DB_HOST}" ]] || [[ -z "${DB_PASS}" ]]; then
info "Trying to detect from Nextcloud pod config..."
local nc_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nextcloud -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${nc_pod}" ]]; then
local config=$(${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- cat /var/www/html/config/config.php 2>/dev/null || true)
if [[ -n "${config}" ]]; then
if [[ "${config}" == *"pgsql"* ]] || [[ "${config}" == *"postgresql"* ]]; then
DB_TYPE="postgresql"
DB_PORT="${DB_PORT:-5432}"
else
DB_TYPE="mariadb"
DB_PORT="${DB_PORT:-3306}"
fi
DB_HOST="${DB_HOST:-$(echo "${config}" | grep -oP \"'dbhost'\s*=>\s*'\K[^']+\" | head -1 || true)}"
DB_USER="${DB_USER:-$(echo "${config}" | grep -oP \"'dbuser'\s*=>\s*'\K[^']+\" | head -1 || true)}"
DB_PASS="${DB_PASS:-$(echo "${config}" | grep -oP \"'dbpassword'\s*=>\s*'\K[^']+\" | head -1 || true)}"
DB_NAME="${DB_NAME:-$(echo "${config}" | grep -oP \"'dbname'\s*=>\s*'\K[^']+\" | head -1 || true)}"
fi
fi
fi
# Fallback: check for database pod in same namespace
if [[ -z "${DB_HOST}" ]]; then
if [[ "${DB_TYPE}" == "postgresql" ]]; then
local db_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -o name 2>/dev/null | grep -E '(postgres|postgresql)' | head -1 | cut -d/ -f2 || true)
else
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)
fi
if [[ -n "${db_pod}" ]]; then
DB_HOST="${db_pod}"
info "Detected database pod: ${DB_HOST}"
fi
fi
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, DB_TYPE environment variables."
else
info "Database: ${DB_TYPE} ${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
*data*|*nextcloud*)
PVC_DATA="${PVC_DATA:-${name}}"
;;
*config*)
PVC_CONFIG="${PVC_CONFIG:-${name}}"
;;
*app*|*custom*)
PVC_APPS="${PVC_APPS:-${name}}"
;;
esac
done
fi
PVC_DATA="${PVC_DATA:-nextcloud-data}"
PVC_CONFIG="${PVC_CONFIG:-nextcloud-config}"
PVC_APPS="${PVC_APPS:-nextcloud-apps}"
info "Using PVCs: data=${PVC_DATA}, config=${PVC_CONFIG}, apps=${PVC_APPS}"
}
# =============================================================================
# BACKUP FUNCTIONS
# =============================================================================
enable_maintenance_mode() {
if [[ "${MAINTENANCE_MODE}" != "true" ]]; then
return 0
fi
info "Enabling Nextcloud maintenance mode..."
local nc_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nextcloud -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${nc_pod}" ]]; then
${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- \
php occ maintenance:mode --on 2>>"${LOG_FILE}" || warn "Failed to enable maintenance mode"
success "Maintenance mode enabled"
else
warn "No Nextcloud pod found, skipping maintenance mode"
fi
}
disable_maintenance_mode() {
if [[ "${MAINTENANCE_MODE}" != "true" ]]; then
return 0
fi
info "Disabling Nextcloud maintenance mode..."
local nc_pod=$(${KUBECTL_CMD} get pods -n "${APP_NAMESPACE}" -l app=nextcloud -o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)
if [[ -n "${nc_pod}" ]]; then
${KUBECTL_CMD} exec -n "${APP_NAMESPACE}" "${nc_pod}" -- \
php occ maintenance:mode --off 2>>"${LOG_FILE}" || warn "Failed to disable maintenance mode"
success "Maintenance mode disabled"
fi
}
backup_database() {
info "Backing up ${DB_TYPE} database..."
local db_dump="${BACKUP_DIR}/database/nextcloud_${TIMESTAMP}.sql"
mkdir -p "${BACKUP_DIR}/database"
if [[ "${DB_TYPE}" == "postgresql" ]]; then
if ! command -v pg_dump >/dev/null 2>&1; then
die "pg_dump not found. Install postgresql-client."
fi
info "Using pg_dump for database dump"
export PGPASSWORD="${DB_PASS}"
if ! pg_dump -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \
--no-owner --no-privileges --clean --if-exists \
> "${db_dump}" 2>>"${LOG_FILE}"; then
die "PostgreSQL dump failed"
fi
unset PGPASSWORD
else
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"
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}"
if ! ${dump_cmd} "${conn_params[@]}" "${DB_NAME}" > "${db_dump}" 2>>"${LOG_FILE}"; then
die "MariaDB/MySQL dump failed"
fi
unset MYSQL_PWD
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})"
}
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}"
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
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}"
local pod_name="nextcloud-backup-${pvc_name}-${TIMESTAMP}"
local yaml_file="/tmp/${pod_name}.yaml"
cat > "${yaml_file}" <<EOF
apiVersion: v1
kind: Pod
metadata:
name: ${pod_name}
namespace: ${APP_NAMESPACE}
spec:
restartPolicy: Never
containers:
- name: backup
image: alpine:latest
command: ["/bin/sh", "-c", "sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: ${pvc_name}
EOF
info "Creating temporary pod to access PVC..."
${KUBECTL_CMD} apply -f "${yaml_file}" >>"${LOG_FILE}" 2>&1
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
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
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}"
${KUBECTL_CMD} get all,configmap,secret,pvc,ingress,serviceaccount,role,rolebinding,networkpolicy -n "${APP_NAMESPACE}" -o yaml > "${manifest_dir}/all-resources.yaml" 2>>"${LOG_FILE}" || true
for resource in deployment statefulset service configmap secret pvc ingress cronjob job; 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="nextcloud_backup_${TIMESTAMP}.tar.gz"
local archive_path="${BACKUP_DEST}/${archive_name}"
tar -czf "${archive_path}" -C "${BACKUP_DEST}" "nextcloud_backup_${TIMESTAMP}" 2>>"${LOG_FILE}"
local size=$(du -h "${archive_path}" | cut -f1)
success "Archive created: ${archive_path} (${size})"
sha256sum "${archive_path}" > "${archive_path}.sha256"
info "SHA256: $(cat "${archive_path}.sha256")"
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 nextcloud_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
Nextcloud Backup Restore Information
====================================
Backup Date: $(date)
Backup Timestamp: ${TIMESTAMP}
Source: TrueNAS App (namespace: ${APP_NAMESPACE})
Database: ${DB_TYPE} ${DB_NAME} on ${DB_HOST}:${DB_PORT} as ${DB_USER}
Backup Contents:
- database/nextcloud_${TIMESTAMP}.sql.gz - Full database dump
- data/ - Nextcloud data directory (user files)
- config/ - Nextcloud config directory (config.php)
- apps/ - Nextcloud custom apps (if separate PVC)
- manifests/ - Kubernetes resource definitions
To restore to Docker:
1. Copy the backup archive to your Docker host
2. Run the restore script: ./restore-nextcloud-docker.sh <backup_archive.tar.gz>
3. Follow the prompts
Database Connection for Docker:
- Host: <your-docker-db-host> (usually 'db' or 'postgres'/'mariadb' in docker-compose)
- Port: ${DB_PORT}
- Database: nextcloud
- User: nextcloud
- Password: <set in docker-compose .env>
Volume Mounts for Docker:
- ./nextcloud-data:/var/www/html
- data/ -> /var/www/html/data/
- config/ -> /var/www/html/config/
- apps/ -> /var/www/html/custom_apps/ (if used)
Important Nextcloud-specific notes:
1. Run 'occ maintenance:mode --off' after restore if needed
2. Run 'occ upgrade' after first startup if version changed
3. Check config.php for 'trusted_domains' - update for new hostname
4. If using Redis, configure in docker-compose
5. If using Cron, set up cron job in Docker
EOF
success "Restore info saved to ${BACKUP_DEST}/RESTORE_INFO_${TIMESTAMP}.txt"
}
# =============================================================================
# MAIN EXECUTION
# =============================================================================
main() {
info "======================================"
info "Nextcloud TrueNAS App Backup Started"
info "======================================"
info "Timestamp: ${TIMESTAMP}"
info "Backup destination: ${BACKUP_DEST}"
mkdir -p "${BACKUP_DIR}"
info "Backup directory: ${BACKUP_DIR}"
detect_kubectl
detect_namespace
detect_database
detect_pvcs
enable_maintenance_mode
backup_manifests
backup_database
backup_pvc "${PVC_DATA}" "data" "Data directory"
backup_pvc "${PVC_CONFIG}" "config" "Configuration"
backup_pvc "${PVC_APPS}" "apps" "Custom apps"
disable_maintenance_mode
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 Nextcloud instance"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
+596
View File
@@ -0,0 +1,596 @@
#!/bin/bash
# =============================================================================
# Nextcloud Restore Script for Docker Container
# =============================================================================
# This script restores a Nextcloud backup (from TrueNAS app) to a Docker container.
#
# Run this script ON the Docker host where you want to run Nextcloud.
#
# Requirements:
# - Docker and Docker Compose installed
# - Backup archive from backup-nextcloud-truenas.sh
# - Write access to Docker volumes/data directories
# =============================================================================
set -euo pipefail
# =============================================================================
# CONFIGURATION
# =============================================================================
BACKUP_ARCHIVE="${1:-}"
DOCKER_DIR="${DOCKER_DIR:-/opt/nextcloud}"
COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.yml}"
DB_CONTAINER="${DB_CONTAINER:-nextcloud-db}"
NEXTCLOUD_CONTAINER="${NEXTCLOUD_CONTAINER:-nextcloud}"
# Database credentials (should match docker-compose .env)
DB_TYPE="${DB_TYPE:-postgresql}" # postgresql or mariadb
DB_ROOT_PASS="${DB_ROOT_PASS:-}"
DB_NAME="${DB_NAME:-nextcloud}"
DB_USER="${DB_USER:-nextcloud}"
DB_PASS="${DB_PASS:-}"
# Nextcloud data directory (host path mounted to container)
NEXTCLOUD_DATA_DIR="${NEXTCLOUD_DATA_DIR:-${DOCKER_DIR}/nextcloud-data}"
# Redis (optional)
REDIS_ENABLED="${REDIS_ENABLED:-false}"
REDIS_CONTAINER="${REDIS_CONTAINER:-nextcloud-redis}"
# Skip database restore
SKIP_DB="${SKIP_DB:-false}"
# Skip files restore
SKIP_FILES="${SKIP_FILES:-false}"
# Force overwrite without confirmation
FORCE="${FORCE:-false}"
# =============================================================================
# INTERNAL VARIABLES
# =============================================================================
TEMP_DIR=""
EXTRACT_DIR=""
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 <backup_archive.tar.gz>"
fi
if [[ ! -f "${BACKUP_ARCHIVE}" ]]; then
die "Backup archive not found: ${BACKUP_ARCHIVE}"
fi
if ! tar -tzf "${BACKUP_ARCHIVE}" >/dev/null 2>&1; then
die "Invalid or corrupted backup archive"
fi
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 nextcloud-restore-XXXXXX)
info "Temporary directory: ${TEMP_DIR}"
tar -xzf "${BACKUP_ARCHIVE}" -C "${TEMP_DIR}"
EXTRACT_DIR=$(find "${TEMP_DIR}" -maxdepth 1 -type d -name "nextcloud_backup_*" | head -1)
if [[ -z "${EXTRACT_DIR}" ]] || [[ ! -d "${EXTRACT_DIR}" ]]; then
die "Could not find extracted backup directory"
fi
info "Extracted to: ${EXTRACT_DIR}"
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
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 ${DB_TYPE} database..."
local db_dump="${EXTRACT_DIR}/database/nextcloud_*.sql.gz"
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}"
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 15
else
die "Database container must be running to restore database"
fi
fi
info "Waiting for database to be ready..."
local retries=30
while [[ ${retries} -gt 0 ]]; do
if [[ "${DB_TYPE}" == "postgresql" ]]; then
if docker exec "${DB_CONTAINER}" pg_isready -h localhost -U "${DB_USER}" >/dev/null 2>&1; then
break
fi
else
if docker exec "${DB_CONTAINER}" mysqladmin ping -h localhost --silent 2>/dev/null; then
break
fi
fi
sleep 2
((retries--))
done
if [[ ${retries} -eq 0 ]]; then
die "Database not ready after 60 seconds"
fi
success "Database is ready"
if [[ "${DB_TYPE}" == "postgresql" ]]; then
info "Recreating database ${DB_NAME}..."
docker exec -i "${DB_CONTAINER}" psql -U postgres -c "
DROP DATABASE IF EXISTS \"${DB_NAME}\";
CREATE DATABASE \"${DB_NAME}\" WITH OWNER = \"${DB_USER}\" ENCODING = 'UTF8' LC_COLLATE = 'en_US.UTF-8' LC_CTYPE = 'en_US.UTF-8';
GRANT ALL PRIVILEGES ON DATABASE \"${DB_NAME}\" TO \"${DB_USER}\";
" 2>>/dev/null || die "Failed to recreate PostgreSQL database"
info "Restoring database data (this may take a while)..."
if ! zcat "${dump_file}" | docker exec -i "${DB_CONTAINER}" psql -U postgres -d "${DB_NAME}" 2>>/dev/null; then
die "PostgreSQL database restore failed"
fi
else
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 MariaDB/MySQL 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 "MariaDB/MySQL database restore failed"
fi
fi
success "Database restored successfully"
if [[ "${DB_TYPE}" == "postgresql" ]]; then
local table_count=$(docker exec "${DB_CONTAINER}" psql -U postgres -d "${DB_NAME}" -c "\dt" --tuples-only 2>/dev/null | wc -l)
else
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)
fi
info "Restored ${table_count} tables"
}
restore_files() {
if [[ "${SKIP_FILES}" == "true" ]]; then
info "Skipping files restore (SKIP_FILES=true)"
return 0
fi
info "Restoring Nextcloud files..."
mkdir -p "${NEXTCLOUD_DATA_DIR}/data"
mkdir -p "${NEXTCLOUD_DATA_DIR}/config"
mkdir -p "${NEXTCLOUD_DATA_DIR}/custom_apps"
if [[ -d "${EXTRACT_DIR}/data" ]]; then
info "Restoring data directory..."
rsync -av "${EXTRACT_DIR}/data/" "${NEXTCLOUD_DATA_DIR}/data/" 2>&1 | tail -5
local count=$(find "${NEXTCLOUD_DATA_DIR}/data" -type f | wc -l)
success "Data restored: ${count} files"
else
warn "No data directory in backup"
fi
if [[ -d "${EXTRACT_DIR}/config" ]]; then
info "Restoring configuration..."
rsync -av "${EXTRACT_DIR}/config/" "${NEXTCLOUD_DATA_DIR}/config/" 2>&1 | tail -5
success "Configuration restored"
else
warn "No config directory in backup"
fi
if [[ -d "${EXTRACT_DIR}/apps" ]]; then
info "Restoring custom apps..."
rsync -av "${EXTRACT_DIR}/apps/" "${NEXTCLOUD_DATA_DIR}/custom_apps/" 2>&1 | tail -5
local count=$(find "${NEXTCLOUD_DATA_DIR}/custom_apps" -type f | wc -l)
success "Custom apps restored: ${count} files"
else
info "No custom apps directory in backup (normal if not using separate PVC)"
fi
info "Fixing file permissions..."
# Nextcloud runs as www-data (uid 33) in most containers
docker run --rm -v "${NEXTCLOUD_DATA_DIR}:/data" alpine:latest \
sh -c "chown -R 33:33 /data && find /data -type d -exec chmod 750 {} \\; && find /data -type f -exec chmod 640 {} \\;" 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}"
if [[ "${DB_TYPE}" == "postgresql" ]]; then
cat > "${compose_path}" <<'EOF'
version: '3.8'
services:
db:
image: postgres:16
container_name: nextcloud-db
restart: unless-stopped
environment:
POSTGRES_PASSWORD: ${DB_ROOT_PASS}
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USER}
volumes:
- db-data:/var/lib/postgresql/data
networks:
- nextcloud-net
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${DB_USER} -d ${DB_NAME}"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
container_name: nextcloud-redis
restart: unless-stopped
networks:
- nextcloud-net
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
nextcloud:
image: nextcloud:latest
container_name: nextcloud
restart: unless-stopped
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
environment:
POSTGRES_HOST: db
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASS}
REDIS_HOST: redis
REDIS_HOST_PORT: 6379
NEXTCLOUD_TRUSTED_DOMAINS: ${NEXTCLOUD_TRUSTED_DOMAINS:-localhost}
NEXTCLOUD_ADMIN_USER: ${NEXTCLOUD_ADMIN_USER:-}
NEXTCLOUD_ADMIN_PASSWORD: ${NEXTCLOUD_ADMIN_PASSWORD:-}
PHP_MEMORY_LIMIT: 512M
PHP_UPLOAD_LIMIT: 10G
volumes:
- ${NEXTCLOUD_DATA_DIR}:/var/www/html
ports:
- "8080:80"
networks:
- nextcloud-net
volumes:
db-data:
networks:
nextcloud-net:
driver: bridge
EOF
else
cat > "${compose_path}" <<'EOF'
version: '3.8'
services:
db:
image: mariadb:10.11
container_name: nextcloud-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:
- nextcloud-net
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "localhost"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
container_name: nextcloud-redis
restart: unless-stopped
networks:
- nextcloud-net
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
nextcloud:
image: nextcloud:latest
container_name: nextcloud
restart: unless-stopped
depends_on:
db:
condition: service_healthy
redis:
condition: service_healthy
environment:
MYSQL_HOST: db
MYSQL_DATABASE: ${DB_NAME}
MYSQL_USER: ${DB_USER}
MYSQL_PASSWORD: ${DB_PASS}
REDIS_HOST: redis
REDIS_HOST_PORT: 6379
NEXTCLOUD_TRUSTED_DOMAINS: ${NEXTCLOUD_TRUSTED_DOMAINS:-localhost}
NEXTCLOUD_ADMIN_USER: ${NEXTCLOUD_ADMIN_USER:-}
NEXTCLOUD_ADMIN_PASSWORD: ${NEXTCLOUD_ADMIN_PASSWORD:-}
PHP_MEMORY_LIMIT: 512M
PHP_UPLOAD_LIMIT: 10G
volumes:
- ${NEXTCLOUD_DATA_DIR}:/var/www/html
ports:
- "8080:80"
networks:
- nextcloud-net
volumes:
db-data:
networks:
nextcloud-net:
driver: bridge
EOF
fi
success "Docker Compose template created at ${compose_path}"
local env_path="${DOCKER_DIR}/.env"
if [[ ! -f "${env_path}" ]] || [[ "${FORCE}" == "true" ]]; then
cat > "${env_path}" <<EOF
# Nextcloud Docker Environment Variables
# Copy this file to .env and fill in your values
# Database (must match what was used in backup or create new)
DB_TYPE=${DB_TYPE}
DB_ROOT_PASS=changeme_root_password
DB_NAME=nextcloud
DB_USER=nextcloud
DB_PASS=changeme_user_password
# Nextcloud data directory on host
NEXTCLOUD_DATA_DIR=${NEXTCLOUD_DATA_DIR}
# Trusted domains (comma-separated, no spaces)
# Example: NEXTCLOUD_TRUSTED_DOMAINS=localhost,nextcloud.example.com,192.168.1.100
NEXTCLOUD_TRUSTED_DOMAINS=localhost
# Optional: Admin credentials for initial setup (if fresh install)
# NEXTCLOUD_ADMIN_USER=admin
# NEXTCLOUD_ADMIN_PASSWORD=changeme_admin_password
# Optional: Redis (enabled by default in compose)
REDIS_ENABLED=true
EOF
info "Environment template created at ${env_path}"
warn "IMPORTANT: Edit ${env_path} and set secure passwords before starting!"
fi
}
show_next_steps() {
info "======================================"
success "Restore completed successfully!"
info "======================================"
echo
info "Next steps:"
echo
echo " 1. Review and edit the environment file:"
echo " ${DOCKER_DIR}/.env"
echo " - Set DB_ROOT_PASS and DB_PASS"
echo " - Set NEXTCLOUD_TRUSTED_DOMAINS to your domain/IP"
echo
echo " 2. Start the containers:"
echo " cd ${DOCKER_DIR}"
echo " docker-compose up -d"
echo
echo " 3. Access Nextcloud at:"
echo " http://<your-docker-host>:8080"
echo
echo " 4. Post-restore actions (run after containers are up):"
echo " docker-compose exec nextcloud php occ maintenance:mode --off"
echo " docker-compose exec nextcloud php occ upgrade"
echo " docker-compose exec nextcloud php occ db:add-missing-indices"
echo " docker-compose exec nextcloud php occ db:add-missing-primary-keys"
echo
info "Useful commands:"
echo " docker-compose logs -f nextcloud # View Nextcloud logs"
echo " docker-compose logs -f db # View database logs"
echo " docker-compose exec nextcloud php occ status"
echo " docker-compose restart nextcloud # Restart Nextcloud"
echo " docker-compose down # Stop everything"
echo
warn "Remember to:"
echo " - Set strong passwords in .env"
echo " - Configure NEXTCLOUD_TRUSTED_DOMAINS for your domain"
echo " - Set up reverse proxy (nginx/traefik) for HTTPS"
echo " - Configure cron: docker-compose exec -u www-data nextcloud php occ cron:run"
echo " - Set up regular backups for the Docker deployment"
}
# =============================================================================
# MAIN EXECUTION
# =============================================================================
main() {
info "======================================"
info "Nextcloud Docker Restore Started"
info "======================================"
if [[ "${BACKUP_ARCHIVE}" == "-h" ]] || [[ "${BACKUP_ARCHIVE}" == "--help" ]]; then
cat <<EOF
Usage: $0 <backup_archive.tar.gz> [options]
Options (via environment variables):
DOCKER_DIR Docker project directory (default: /opt/nextcloud)
COMPOSE_FILE Docker Compose filename (default: docker-compose.yml)
DB_CONTAINER Database container name (default: nextcloud-db)
NEXTCLOUD_CONTAINER Nextcloud container name (default: nextcloud)
DB_TYPE Database type: postgresql or mariadb (default: postgresql)
DB_ROOT_PASS Database root password (required)
DB_NAME Database name (default: nextcloud)
DB_USER Database user (default: nextcloud)
DB_PASS Database user password (required)
NEXTCLOUD_DATA_DIR Host data directory (default: \${DOCKER_DIR}/nextcloud-data)
REDIS_ENABLED Enable Redis (default: true)
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_TYPE=postgresql DB_ROOT_PASS=secret DB_PASS=secret $0 ./nextcloud_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 EXIT
main "$@"