#!/bin/bash

# Copyright (C) 2026 Actiphy, Inc.
#   All rights reserved.
#
# THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Actiphy, Inc.
# The copyright notice above does not evidence any actual or intended
# publication of such source code.
#
# Created by Yoshinobu Ito
#
# Date: 11/27/26

# ==============================================================================
# Script Name : pre_freeze
# Description : Nutanix Guest Tools (NGT) pre-freeze script for Linux VMs.
#               Freezes databases (optional) and freezes local filesystems
#               before taking an application-consistent snapshot.
#
# Execution Flow:
#   1. Execute the optional DB freeze script if configured and executable.
#      (Skipped automatically if DB_FREEZE_SCRIPT is empty or missing.)
#   2. Discover physical local filesystems (ext4, xfs, btrfs) via /proc/mounts
#      (compatible with RHEL 8.x where 'findmnt --real' is unavailable).
#   3. Deduplicate block devices to avoid EBUSY errors on bind mounts, and
#      sort mount points so the root filesystem (/) is frozen last.
#   4. Freeze each filesystem in order and record frozen paths in /run.
#   5. If any step fails, roll back by unfreezing already frozen mounts and
#      unquiescing the database before exiting with status 1.
#
# Logging & Deadlock Avoidance:
#   - Logs progress and errors to Syslog via 'logger' (tag: nutanix-pre-freeze).
#   - Uses 'timeout 2' on logger calls to prevent blocking if Syslog stalls.
#   - Logs the freeze action for '/' immediately BEFORE executing 'fsfreeze -f /'
#     to prevent Syslog disk I/O from blocking once '/' is frozen.
#
# Deployment Requirements (Nutanix NGT):
#   - Path        : /usr/local/sbin/pre_freeze (without .sh extension)
#   - Permissions : chown root:root /usr/local/sbin/pre_freeze && chmod 700
#   - Timeout     : Must complete within 60 seconds.
# ==============================================================================

export LANG=C
ScVer="1.0.5"

set -e

LOG_TAG="nutanix-pre-freeze"
STATE_FILE="/run/nutanix_frozen_mounts.list"
DB_STATE_FILE="/run/nutanix_db_frozen.flag"

# Optional: Set paths to your custom DB freeze/thaw scripts.
# Leave empty or unset to skip DB handling.
DB_FREEZE_SCRIPT=""
DB_THAW_SCRIPT=""

log_info() {
    timeout 2 logger -t "$LOG_TAG" -p user.info "$1" 2>/dev/null || true
}

log_err() {
    timeout 2 logger -t "$LOG_TAG" -p user.err "$1" 2>/dev/null || true
}

log_info "Starting pre-freeze process."
log_info "Ver $ScVer START."

: > "$STATE_FILE"
rm -f "$DB_STATE_FILE"

# 1. Quiesce or stop the database BEFORE freezing filesystems (skip if not configured)
if [[ -n "$DB_FREEZE_SCRIPT" && -x "$DB_FREEZE_SCRIPT" ]]; then
    log_info "Executing DB freeze script: $DB_FREEZE_SCRIPT"
    if "$DB_FREEZE_SCRIPT" >/dev/null 2>&1; then
        touch "$DB_STATE_FILE"
        log_info "DB freeze script completed successfully."
    else
        log_err "DB freeze script failed: $DB_FREEZE_SCRIPT"
        exit 1
    fi
else
    log_info "DB freeze script not configured or not executable. Skipping DB freeze."
fi

# 2. Discover real block-backed local filesystems (compatible with RHEL 8.x)
#    Reads /proc/mounts, filters supported filesystem types, verifies real block
#    devices (SOURCE starting with /dev/), deduplicates bind mounts by device,
#    and moves root (/) to the very end of the list.
mapfile -t TARGET_MOUNTS < <(
    awk '
        $1 ~ /^\/dev\// && ($3 == "ext4" || $3 == "xfs" || $3 == "btrfs") {
            # Unescape octal spaces (\040) in mount point paths
            gsub(/\\040/, " ", $2)
            # Deduplicate by source device to prevent EBUSY on bind mounts
            if (!seen[$1]++) {
                if ($2 == "/") {
                    root = $2
                } else {
                    print $2
                }
            }
        }
        END {
            if (root != "") print root
        }
    ' /proc/mounts
)

if [[ ${#TARGET_MOUNTS[@]} -eq 0 ]]; then
    log_info "No target filesystems found to freeze."
fi

# 3. Freeze filesystems in order and record successfully frozen paths in /run (in-memory)
for mp in "${TARGET_MOUNTS[@]}"; do
    # Log BEFORE freezing '/' because Syslog disk writes will block once '/' is frozen
    log_info "Freezing filesystem: $mp"
    if fsfreeze -f "$mp" >/dev/null 2>&1; then
        echo "$mp" >> "$STATE_FILE"
    else
        # Rollback: Unfreeze already frozen mounts first (in reverse order)
        tac "$STATE_FILE" | while IFS= read -r frozen_mp; do
            fsfreeze -u "$frozen_mp" >/dev/null 2>&1 || true
        done
        rm -f "$STATE_FILE"

        log_err "Failed to freeze filesystem: $mp. Rolled back all frozen mounts."

        # Rollback: Resume or start the database if it was frozen
        if [[ -f "$DB_STATE_FILE" ]]; then
            if [[ -n "$DB_THAW_SCRIPT" && -x "$DB_THAW_SCRIPT" ]]; then
                log_info "Rolling back database freeze via: $DB_THAW_SCRIPT"
                "$DB_THAW_SCRIPT" >/dev/null 2>&1 || log_err "Failed to rollback database freeze."
            fi
            rm -f "$DB_STATE_FILE"
        fi
        exit 1
    fi
done

# Note: Avoid calling logger here because '/' is now frozen and disk I/O would block.
exit 0
