#!/usr/bin/env bash
# =============================================================================
# Meta              : NextCloud 备份执行脚本
# Version           : 2.0.0
# Author            : Bash Shell Senior Development Engineer
# License           : MIT
# Description       : 自动化执行NextCloud维护模式切换、数据库和文件备份、加密、上传及清理。
# =============================================================================

source "$(dirname "$0")/common.sh" || { echo "FATAL: common.sh not found." >&2; exit 1; }

#------------------------------------------------------------------------------
# 脚本配置区
#------------------------------------------------------------------------------
readonly APP_NAME="NextCloud"
readonly REMOTE_USER="root"
readonly REMOTE_HOST="s5"
readonly MAX_ENCRYPTED_REPLICAS=3

# > 远程配置
readonly REMOTE_WEB_CONTAINER="nextcloud_web"
readonly REMOTE_DB_CONTAINER="nextcloud-db"
readonly REMOTE_DATA_DIR="/data/nextcloud"
readonly DB_USER="nextcloud"
readonly DB_PASSWORD="boge14@Level5" # 建议使用更安全的方式管理密码
readonly DB_NAME="nextcloud"

# > 本地路径
readonly LOCAL_BACKUP_DIR="/data/s5_146-56-159-175/nextcloud"

# =============================================================================
# 核心函数
# =============================================================================
###
# 功能描述段: 切换Nextcloud维护模式 (on/off)
# @param mode <string> 模式, 'on' 或 'off'
# @return     <0> 成功 | >0 失败
###
toggle_maintenance_mode() {
  local mode="$1"
  log_message "INFO" "Setting maintenance mode to '${mode}'..."
  execute_remote_command "${REMOTE_USER}" "${REMOTE_HOST}" \
    "docker exec -u www-data ${REMOTE_WEB_CONTAINER} php occ maintenance:mode --${mode}"
}

# =============================================================================
# 主执行流程
# =============================================================================
main() {
  # > 设置陷阱，确保任何情况下都能尝试关闭维护模式
  trap 'log_message "ERROR" "${APP_NAME}中止的备份任务。试图禁用维护模式..."; toggle_maintenance_mode "off" || true; exit 1' ERR

  log_message "INFO" "${APP_NAME}的备份任务出现错误! 终止! "

  # > 步骤 1: 启用维护模式
  log_message "INFO" "[Step 1/8] 启用维护模式..."
  toggle_maintenance_mode "on"

  # > 步骤 2: 数据库备份
  log_message "INFO" "[Step 2/8] 执行远程数据库备份..."
  local db_backup_file="${REMOTE_DATA_DIR}/nextcloud-db_backup_$(date +%Y%m%d-%H%M%S).sql"
  local db_backup_cmd="docker exec ${REMOTE_DB_CONTAINER} mariadb-dump --single-transaction -h localhost -u ${DB_USER} -p'${DB_PASSWORD}' ${DB_NAME} > ${db_backup_file}"
  execute_remote_command "${REMOTE_USER}" "${REMOTE_HOST}" "${db_backup_cmd}"

  # > 步骤 3: rsync复制备份文件
  log_message "INFO" "[Step 3/8] Srsync复制远程备份文件..."
  mkdir -p "${LOCAL_BACKUP_DIR}"
  rsync -avz --progress -e "ssh -p ${REMOTE_SSH_PORT}" \
    "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DATA_DIR}/" \
    "${LOCAL_BACKUP_DIR}/"

  # > 步骤 4: 远程清理数据库备份
  log_message "INFO" "[Step 4/8] 远程清理数据库备份..."
  execute_remote_command "${REMOTE_USER}" "${REMOTE_HOST}" "rm -f ${REMOTE_DATA_DIR}/nextcloud-db_backup_*.sql"

  # > 步骤 5: 禁用维护模式
  log_message "INFO" "[Step 5/8] 禁用维护模式..."
  toggle_maintenance_mode "off"

  # > 步骤 6: 7zip加密
  local archive_file="${SCRIPT_RUN_DIR}/${APP_NAME}-backup-$(date +%Y%m%d-%H%M%S).7z"
  log_message "INFO" "[Step 6/8] 7zip加密本地目录..."
  encrypt_with_7zip "${LOCAL_BACKUP_DIR}" "${archive_file}"

  # > 步骤 7: rclone上传
  log_message "INFO" "[Step 7/8] 上传加密压缩包至冷存储 => ${RCLONE_REMOTE_REPO}..."
  rclone_copy "${archive_file}" "${RCLONE_REMOTE_REPO}"

  # > 步骤 8: 控制副本数并清理本地
  log_message "INFO" "[Step 8/8] 控制冷备份的副本数量 => ${MAX_ENCRYPTED_REPLICAS}..."
  rclone_control_replicas "${RCLONE_REMOTE_REPO}" "${APP_NAME}-backup-" "${MAX_ENCRYPTED_REPLICAS}"
  cleanup_local_encrypted_files "${SCRIPT_RUN_DIR}"
#  rm -rf "${LOCAL_BACKUP_DIR}"

  log_message "INFO" "====== ${APP_NAME} 备份任务已全部完成!  ======"
}

# =============================================================================
# 脚本入口点
# =============================================================================
# 函数调用关系图
# main
# ├─ toggle_maintenance_mode (2)
# │  └─ execute_remote_command
# ├─ execute_remote_command (2)
# ├─ encrypt_with_7zip
# ├─ rclone_copy
# ├─ rclone_control_replicas
# └─ cleanup_local_encrypted_files
# =============================================================================
main "$@"
