#!/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 " 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}" <: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 < [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 "$@"