#!/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 : post_thaw
# Description : Nutanix Guest Tools (NGT) post-thaw script for Linux VMs.
#               Unfreezes local filesystems and resumes databases after a
#               snapshot completes (or after a pre_freeze failure).
#
# Execution Flow:
#   1. Read the list of frozen mount points recorded in /run during pre_freeze.
#   2. Unfreeze filesystems in reverse order (starting with root '/') so disk
#      I/O is restored immediately.
#   3. Execute the optional DB thaw script if the DB was frozen during
#      pre_freeze and the script is configured and executable.
#   4. Clean up temporary state files in /run and exit with status 0.
#
# Logging & Deadlock Avoidance:
#   - Logs progress and warnings to Syslog via 'logger' (tag: nutanix-post-thaw).
#   - Uses 'timeout 2' on logger calls to prevent blocking if Syslog stalls.
#   - Logs the unfreeze action for each mount point AFTER executing 'fsfreeze -u'
#     so Syslog writes do not block while '/' is still frozen.
#
# Deployment Requirements (Nutanix NGT):
#   - Path        : /usr/local/sbin/post_thaw (without .sh extension)
#   - Permissions : chown root:root /usr/local/sbin/post_thaw && chmod 700
#   - Timeout     : Must complete within 60 seconds.
# ==============================================================================

export LANG=C
ScVer="1.0.5"

LOG_TAG="nutanix-post-thaw"
STATE_FILE="/run/nutanix_frozen_mounts.list"
DB_STATE_FILE="/run/nutanix_db_frozen.flag"

# Optional: Set path to your custom DB thaw/start script.
# Leave empty or unset to skip DB handling.
DB_THAW_SCRIPT=""

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

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

# 1. Unfreeze filesystems first in reverse order (starting with /)
if [[ -f "$STATE_FILE" ]]; then
    tac "$STATE_FILE" | while IFS= read -r mp; do
        if fsfreeze -u "$mp" >/dev/null 2>&1; then
            # Log AFTER unfreezing so '/' disk I/O is available again
            log_info "Unfrozen filesystem: $mp"
        else
            log_warn "Failed to unfreeze filesystem (or already unfrozen): $mp"
        fi
    done
    rm -f "$STATE_FILE"
    log_info "Ver $ScVer START."
else
    log_info "Ver $ScVer START."
    log_info "No frozen mounts state file found. Skipping filesystem unfreeze."
fi

# 2. Resume or start the database AFTER filesystems are unfrozen (skip if not configured)
if [[ -f "$DB_STATE_FILE" ]]; then
    if [[ -n "$DB_THAW_SCRIPT" && -x "$DB_THAW_SCRIPT" ]]; then
        log_info "Executing database thaw script: $DB_THAW_SCRIPT"
        if "$DB_THAW_SCRIPT" >/dev/null 2>&1; then
            log_info "Database thaw completed successfully."
        else
            log_warn "Database thaw script returned an error: $DB_THAW_SCRIPT"
        fi
    else
        log_info "Database thaw script not configured or not executable. Skipping DB thaw."
    fi
    rm -f "$DB_STATE_FILE"
fi

log_info "Completed Nutanix post-thaw process."
exit 0
