#!/usr/bin/sh
#
# Hybrid Appliance eUSB/SATA-DOM maintenance tool
#
# Copyright (C) 2022 Musarubra US LLC, d.b.a. Skyhigh Security
#
#############################################################
# Main
#############################################################
LOG_FILE="/var/log/hyb-edisk.log"

[ -e "$LOG_FILE" ] || : > "$LOG_FILE"
chmod 0600 "$LOG_FILE" 2>/dev/null || true

# Signal handler for cleanup on interrupt
trap 'log_info "Interrupted. Performing cleanup..."; cleanup_on_error; echo "E-disk write failed: operation interrupted." >&2; exit 130' INT TERM

# Check for required commands
check_dependencies() {
    local missing=""
    local required_cmds="dmidecode mount umount partprobe parted mkfs.vfat losetup dd wipefs readlink grep sed awk date checkisomd5"
    
    for cmd in $required_cmds; do
        if ! command -v "$cmd" >/dev/null 2>&1; then
            missing="$missing $cmd"
        fi
    done
    
    if [ -n "$missing" ]; then
        error_exit "Missing required commands:$missing"
    fi
    
    log_info "All required dependencies found"
}

hyb_usage() {
    echo "usage: hyb-edisk <command> [option]" | tee -a "$LOG_FILE"
    echo "" | tee -a "$LOG_FILE"
    echo "    commands:" | tee -a "$LOG_FILE"
    echo "        check <file>        - check ISO image" | tee -a "$LOG_FILE"
    echo "        info                - show embedded drive info and status" | tee -a "$LOG_FILE"
    echo "        list                - show embedded drive info and status" | tee -a "$LOG_FILE"
    echo "        write <file>        - write image file to embedded drive" | tee -a "$LOG_FILE"
}

hyb_main() {
    local command="$1"
    local arg1="$2"

    if [ -z "$command" ]; then
        hyb_usage
        exit 1
    fi

    echo "***hyb-edisk log start***" >> "$LOG_FILE"
    date >> "$LOG_FILE"
    echo "*************************" >> "$LOG_FILE"

    if [ "$(id -u)" -ne 0 ]; then
        echo "error: hyb-edisk must be run as root" 1>&2 | tee -a "$LOG_FILE"
        exit 1
    fi
    
    # Check dependencies once at startup
    check_dependencies

    case "$command" in
        write)
            if [ -z "$arg1" ]; then
                hyb_usage
                exit 1
            fi
            hyb_write "$arg1"
            ;;
        check)
            if [ -z "$arg1" ]; then
                hyb_usage
                exit 1
            fi
            hyb_check "$arg1"
            ;;
        info|list)
            hyb_info
            ;;
        *)
            hyb_usage
            exit 1
            ;;
    esac
}

# --- Internal Script Variables ---
ISO_MOUNT_POINT="/tmp/hybappl_iso_mnt"
EDISK_ESP_MOUNT="/mnt/edisk_esp_final"
EFIBOOT_MOUNT_POINT="/tmp/efiboot_mnt"

error_exit() {
    echo "ERROR: $1" 2>&1 | tee -a "$LOG_FILE"
    cleanup_on_error
    exit 1
}

cleanup_on_error() {
    log_info "Performing cleanup..."
    [ -n "${EDISK_ESP_MOUNT:-}" ] && mountpoint -q "${EDISK_ESP_MOUNT}" 2>/dev/null && umount "${EDISK_ESP_MOUNT}" 2>/dev/null || true
    [ -n "${EFIBOOT_MOUNT_POINT:-}" ] && mountpoint -q "${EFIBOOT_MOUNT_POINT}" 2>/dev/null && umount "${EFIBOOT_MOUNT_POINT}" 2>/dev/null || true
    [ -n "${ISO_MOUNT_POINT:-}" ] && mountpoint -q "${ISO_MOUNT_POINT}" 2>/dev/null && umount "${ISO_MOUNT_POINT}" 2>/dev/null || true

    local loop_devs
    loop_devs=$(losetup -a 2>/dev/null | grep "${ISO_PATH:-iso_path_unset}\|${EFIBOOT_IMG_PATH:-efiboot_path_unset}" | awk -F: '{print $1}')
    for ld in $loop_devs; do
        losetup -d "$ld" 2>/dev/null || true
    done

    [ -n "${EDISK_ESP_MOUNT:-}" ] && [ -d "${EDISK_ESP_MOUNT}" ] && rmdir "${EDISK_ESP_MOUNT}" 2>/dev/null || true
    [ -n "${EFIBOOT_MOUNT_POINT:-}" ] && [ -d "${EFIBOOT_MOUNT_POINT}" ] && rmdir "${EFIBOOT_MOUNT_POINT}" 2>/dev/null || true
    [ -n "${ISO_MOUNT_POINT:-}" ] && [ -d "${ISO_MOUNT_POINT}" ] && rmdir "${ISO_MOUNT_POINT}" 2>/dev/null || true
    log_info "Cleanup complete."
}

log_info() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

log_console() {
    log_info "$1"
    echo "$1"
}

log_warn() {
    log_info "WARNING: $1"
    echo "warning: $1" >&2
}

log_err() {
    log_info "ERROR: $1"
    echo "error: $1" >&2
}

writeToNvme() {
    local EDISK_DEV="$1"
    local ISO_FILE="$2"

    if [ -z "$ISO_FILE" ] || [ ! -f "$ISO_FILE" ]; then
        error_exit "ISO image file not found or not readable: '$ISO_FILE'"
    fi

    local ISO_PATH
    ISO_PATH=$(readlink -f "$ISO_FILE" 2>/dev/null || echo "$ISO_FILE")
    
    if [ ! -r "$ISO_PATH" ]; then
        error_exit "Cannot read ISO file: $ISO_PATH"
    fi

    log_info "Starting e-disk deployment..."
    log_info "Deployment target device: ${EDISK_DEV}, ISO: ${ISO_PATH}"
    log_info "ISO file size: $(stat -f%z "$ISO_PATH" 2>/dev/null || stat -c%s "$ISO_PATH" 2>/dev/null) bytes"

    RAW_DISK_DEV="${EDISK_DEV}"
    if [[ "${RAW_DISK_DEV}" =~ nvme ]]; then
        ESP_PART="${RAW_DISK_DEV}p1"
    else
        ESP_PART="${RAW_DISK_DEV}1"
    fi

    # Validate device exists
    if [ ! -b "$RAW_DISK_DEV" ]; then
        error_exit "Device does not exist or is not a block device: $RAW_DISK_DEV"
    fi

    # 1. Mount ISO Image via Loopback
    if mountpoint -q "${ISO_MOUNT_POINT}" 2>/dev/null; then
        umount "${ISO_MOUNT_POINT}" 2>/dev/null || true
    fi
    mkdir -p "${ISO_MOUNT_POINT}" || error_exit "Failed to create ISO mount directory."
    mount -o loop,ro "${ISO_PATH}" "${ISO_MOUNT_POINT}" >> "$LOG_FILE" 2>&1 || error_exit "Failed to mount ISO image."

    # 2. Cleanup existing mounts & locks on target drive
    log_info "Unmounting existing partitions on ${RAW_DISK_DEV}..."
    swapoff "${RAW_DISK_DEV}"* 2>/dev/null || true
    umount -f "${ESP_PART}" 2>/dev/null || true
    umount -f "${RAW_DISK_DEV}"* 2>/dev/null || true

    partx -d "${RAW_DISK_DEV}" 2>/dev/null || true
    udevadm settle 2>/dev/null || true

    # 3. Wipe & Partition
    log_info "Wiping and partitioning ${RAW_DISK_DEV}..."
    wipefs -a -f "${RAW_DISK_DEV}" >> "$LOG_FILE" 2>&1 || true
    dd if=/dev/zero of="${RAW_DISK_DEV}" bs=1M count=10 status=none conv=fsync >> "$LOG_FILE" 2>&1 || error_exit "Failed to zero target drive."

    partx -d "${RAW_DISK_DEV}" 2>/dev/null || true
    partprobe "${RAW_DISK_DEV}" >> "$LOG_FILE" 2>&1 || true
    udevadm settle 2>/dev/null || true

    parted -s "${RAW_DISK_DEV}" mklabel gpt >> "$LOG_FILE" 2>&1 || error_exit "Failed to create GPT partition table."
    parted -s "${RAW_DISK_DEV}" mkpart primary fat32 1MiB 100% >> "$LOG_FILE" 2>&1 || error_exit "Failed to create primary partition."
    parted -s "${RAW_DISK_DEV}" set 1 esp on >> "$LOG_FILE" 2>&1 || error_exit "Failed to set ESP flag."

    partprobe "${RAW_DISK_DEV}" >> "$LOG_FILE" 2>&1 || true
    udevadm settle 2>/dev/null || true

    # Wait for partition to appear with timeout
    local retries=0
    local max_retries=30  # 30 seconds max
    log_info "Waiting for partition ${ESP_PART} to appear..."
    while [ ! -b "${ESP_PART}" ] && [ $retries -lt $max_retries ]; do
        retries=$((retries + 1))
        log_info "Waiting for partition... (attempt $retries/$max_retries)"
        sleep 1
    done

    if [ ! -b "${ESP_PART}" ]; then
        error_exit "Partition ${ESP_PART} did not appear after $max_retries seconds. Device enumeration may have failed."
    fi
    
    log_info "Partition ${ESP_PART} appeared successfully"

    # 4. Format FAT32 & Mount
    log_info "Formatting ${ESP_PART} as FAT32 with label MWG_EDISK..."
    mkfs.vfat -F 32 -n "MWG_EDISK" "${ESP_PART}" >> "$LOG_FILE" 2>&1 || error_exit "Failed to format ${ESP_PART} as FAT32."

    EDISK_ESP_MOUNT="/mnt/edisk_esp_$$"
    mkdir -p "${EDISK_ESP_MOUNT}" || error_exit "Failed to create mount point ${EDISK_ESP_MOUNT}."

    mount -t vfat "${ESP_PART}" "${EDISK_ESP_MOUNT}" >> "$LOG_FILE" 2>&1 || error_exit "Failed to mount ${ESP_PART}."

    # 5. Copy ISO contents to FAT32 safely
    log_info "Copying system payload files to target ESP..."
    cp -r "${ISO_MOUNT_POINT}"/* "${EDISK_ESP_MOUNT}"/ >> "$LOG_FILE" 2>&1 || true
    cp -r "${ISO_MOUNT_POINT}"/.* "${EDISK_ESP_MOUNT}"/ 2>/dev/null || true

    # Extract efiboot.img EFI bootloader contents
    EFIBOOT_IMG_PATH="${EDISK_ESP_MOUNT}/isolinux/efiboot.img"
    if [ ! -f "${EFIBOOT_IMG_PATH}" ]; then
        EFIBOOT_IMG_PATH="${ISO_MOUNT_POINT}/isolinux/efiboot.img"
    fi

    if [ -f "${EFIBOOT_IMG_PATH}" ]; then
        log_info "Extracting EFI boot image from ${EFIBOOT_IMG_PATH}..."
        EFIBOOT_LOOP_DEV=$(losetup -f --show "${EFIBOOT_IMG_PATH}") || true
        if [ -n "${EFIBOOT_LOOP_DEV}" ]; then
            EFIBOOT_MOUNT_POINT="/mnt/efiboot_img_$$"
            mkdir -p "${EFIBOOT_MOUNT_POINT}" || true
            if mount "${EFIBOOT_LOOP_DEV}" "${EFIBOOT_MOUNT_POINT}" >> "$LOG_FILE" 2>&1; then
                mkdir -p "${EDISK_ESP_MOUNT}/EFI"
                cp -r "${EFIBOOT_MOUNT_POINT}/EFI"/* "${EDISK_ESP_MOUNT}/EFI"/ >> "$LOG_FILE" 2>&1 || true
                umount "${EFIBOOT_MOUNT_POINT}" 2>/dev/null || true
            fi
            losetup -d "${EFIBOOT_LOOP_DEV}" 2>/dev/null || true
            rmdir "${EFIBOOT_MOUNT_POINT}" 2>/dev/null || true
        fi
    fi

    # 6. Update GRUB kernel line parameters (Includes explicit cdrom/edisk device mappings)
    log_info "Updating kernel parameters in GRUB configuration..."
    while IFS= read -r GRUB_CFG_PATH; do
        [ -z "$GRUB_CFG_PATH" ] && continue
        log_info "Processing GRUB config: ${GRUB_CFG_PATH}"

        # Create backup before modification
        if [ -f "$GRUB_CFG_PATH" ]; then
            cp "$GRUB_CFG_PATH" "${GRUB_CFG_PATH}.bak.$(date +%s)" >> "$LOG_FILE" 2>&1
            log_info "Backup created for ${GRUB_CFG_PATH}"
        else
            log_warn "GRUB config file not found: ${GRUB_CFG_PATH}"
            continue
        fi

        TMP_CFG=$(mktemp /tmp/grub.XXXXXX)
        if [ ! -w "$(dirname "$GRUB_CFG_PATH")" ]; then
            log_warn "Cannot write to directory of ${GRUB_CFG_PATH}, skipping"
            rm -f "$TMP_CFG"
            continue
        fi

        sed -r -e '/^\s*set root=\(hd[0-9]+,gpt[0-9]+\)/d' \
               -e '/^\s*search\s+/d' \
               -e "s@^\s*(linux|linuxefi)\s+.*\$@    \1 /isolinux/vmlinuz rootfstype=fat32 quiet hyb=wizard,stoponerror,reboot cdrom=${ESP_PART} edisk=${RAW_DISK_DEV}@" \
               "$GRUB_CFG_PATH" > "$TMP_CFG" 2>> "$LOG_FILE"

        if [ $? -ne 0 ]; then
            log_warn "sed failed for ${GRUB_CFG_PATH}"
            rm -f "$TMP_CFG"
            continue
        fi

        sed -i '/^menuentry /a \    search --no-floppy --set=root --file /isolinux/vmlinuz' "$TMP_CFG" 2>> "$LOG_FILE"

        if [ -s "$TMP_CFG" ]; then
            cp -f "$TMP_CFG" "$GRUB_CFG_PATH" >> "$LOG_FILE" 2>&1
            log_info "GRUB config updated successfully"
        else
            log_warn "Generated GRUB config is empty, skipping update"
        fi
        rm -f "$TMP_CFG"
    done < <(find "${EDISK_ESP_MOUNT}/EFI" -type f -name "grub.cfg" 2>/dev/null)

    # Synchronize slos/SkyhighSecurity grub.cfg to default /EFI/BOOT/grub.cfg
    if [ -f "${EDISK_ESP_MOUNT}/EFI/slos/grub.cfg" ]; then
        mkdir -p "${EDISK_ESP_MOUNT}/EFI/BOOT"
        cp -f "${EDISK_ESP_MOUNT}/EFI/slos/grub.cfg" "${EDISK_ESP_MOUNT}/EFI/BOOT/grub.cfg" >> "$LOG_FILE" 2>&1 || true
    elif [ -f "${EDISK_ESP_MOUNT}/EFI/SkyhighSecurity_Linux/grub.cfg" ]; then
        mkdir -p "${EDISK_ESP_MOUNT}/EFI/BOOT"
        cp -f "${EDISK_ESP_MOUNT}/EFI/SkyhighSecurity_Linux/grub.cfg" "${EDISK_ESP_MOUNT}/EFI/BOOT/grub.cfg" >> "$LOG_FILE" 2>&1 || true
    fi

    # 7. Unmount & Sync
    log_info "Unmounting ESP partition..."
    sync
    sleep 1
    umount "${EDISK_ESP_MOUNT}" >> "$LOG_FILE" 2>&1 || error_exit "Failed to unmount ${EDISK_ESP_MOUNT}."
    rmdir "${EDISK_ESP_MOUNT}" 2>/dev/null || true

    if mountpoint -q "${ISO_MOUNT_POINT}" 2>/dev/null; then
        umount "${ISO_MOUNT_POINT}" 2>/dev/null || true
        rmdir "${ISO_MOUNT_POINT}" 2>/dev/null || true
    fi

    log_info "Deployment complete."
}

hyb_verify_iso() {
    local image="$1"

    if ! command -v checkisomd5 >/dev/null 2>&1; then
        echo "iso verification: failed checkisomd5 is not available" | tee -a "$LOG_FILE" >&2
        return 1
    fi

    local verify_output="/tmp/hyb-edisk-check.$$"
    if checkisomd5 "$image" > "$verify_output" 2>&1; then
        cat "$verify_output" >> "$LOG_FILE"
        rm -f "$verify_output"
        echo "iso verification : pass" | tee -a "$LOG_FILE"
        return 0
    else
        cat "$verify_output" >> "$LOG_FILE"
        local reason
        reason=$(tr '\n' ' ' < "$verify_output" | sed 's/[[:space:]][[:space:]]*/ /g; s/^ //; s/ $//')
        rm -f "$verify_output"
        [ -n "$reason" ] || reason="checkisomd5 failed"
        echo "iso verification: failed $reason" | tee -a "$LOG_FILE" >&2
        return 1
    fi
}

hyb_check() {
    local image="$1"
    if [ ! -r "$image" ]; then
        err "file not found ($image)"
    fi
    if ! hyb_verify_iso "$image"; then
        exit 1
    fi
    exit 0
}

hyb_write() {
    local image="$1"
    local substring="nvme"

    if [ ! -r "$image" ]; then
        err "E-disk write failed: ISO file is missing or not readable ($image)"
    fi

    echo "E-disk write started." | tee -a "$LOG_FILE"
    log_info "Detecting embedded disk device..."
    local disk
    if ! disk=$(hyb_find_disk) || [ -z "$disk" ]; then
        err "E-disk write failed: embedded disk device was not found"
    fi

    local device="/dev/$disk"
    if [ ! -e "$device" ]; then
        log_info "Missing device node: $device"
        err "E-disk write failed: embedded disk device node was not found"
    fi

    log_info "Embedded disk detected."
    log_info "Target device: $device"

    log_info "Verifying ISO integrity..."
    if ! hyb_verify_iso "$image"; then
        err "E-disk write failed: ISO verification failed; the image may be corrupted"
    fi

    log_info "Writing image to embedded disk..."
    log_info "Writing to: $device"
    log_info "Starting write operation (this may take several minutes)..."
    
    if [[ "$device" =~ $substring ]]; then
        writeToNvme "$device" "$image"
    else
        dd if="$image" bs=1M of="$device" >> "$LOG_FILE" 2>&1 || \
            err "E-disk write failed while writing the ISO image to the embedded disk."
    fi

    echo "E-disk write completed." | tee -a "$LOG_FILE"
    exit 0
}

hyb_info() {
    local substring="nvme"
    
    log_info "Detecting embedded disk device..."
    local disk
    if ! disk=$(hyb_find_disk) || [ -z "$disk" ]; then
        err "no embedded disk device found"
    fi

    local device="/dev/$disk"
    if [ ! -e "$device" ]; then
        log_info "Missing device node: $device"
        err "no embedded disk device node found"
    fi

    log_info "Reading embedded disk information..."
    log_info "Reading info from: $device"

    local mount_point
    mount_point=$(mktemp -d)
    if [ -z "$mount_point" ]; then
        err "Failed to create a temporary mount point."
    fi

    cleanup_info_mount() {
        if [ -n "$mount_point" ] && mountpoint -q "$mount_point" 2>/dev/null; then
            umount "$mount_point" >/dev/null 2>&1 || true
        fi
        if [ -n "$mount_point" ] && [ -d "$mount_point" ]; then
            rmdir "$mount_point" >/dev/null 2>&1 || true
        fi
    }
    trap cleanup_info_mount EXIT

    if [[ "$device" =~ $substring ]]; then
        local nvme_part="${device}p1"
        local mount_dev="$device"
        if [ -b "$nvme_part" ]; then
            mount_dev="$nvme_part"
        fi
        log_info "Attempting to mount NVMe device: $mount_dev"
        if ! mount -t vfat -o ro "$mount_dev" "$mount_point" >/dev/null 2>&1; then
            if ! mount -t iso9660 -o ro "$mount_dev" "$mount_point" >/dev/null 2>&1; then
                cleanup_info_mount
                log_info "Failed to mount NVMe device: $mount_dev"
                echo "Unable to read ISO information from embedded disk." | tee -a "$LOG_FILE"
                return 0
            fi
        fi
    else
        log_info "Attempting to mount block device: $device"
        if ! mount -t iso9660 -o ro "$device" "$mount_point" >/dev/null 2>&1; then
            cleanup_info_mount
            log_info "Failed to mount block device: $device"
            echo "Unable to read ISO information from embedded disk." | tee -a "$LOG_FILE"
            return 0
        fi
    fi

    local file_found=""
    for file in "$mount_point"/system-*.x86_64.img; do
        if [ -e "$file" ]; then
            file_found="$file"
            break
        fi
    done

    if [ -n "$file_found" ]; then
        local version
        version=$(basename "$file_found" .x86_64.img | cut -d- -f2-)
        echo "ISO found on embedded disk: $version" | tee -a "$LOG_FILE"
    elif [ -f "$mount_point/ID" ]; then
        local version
        version=$(sed -n '2p' "$mount_point/ID")
        echo "ISO found on embedded disk: $version" | tee -a "$LOG_FILE"
    else
        echo "No ISO image found on embedded disk." | tee -a "$LOG_FILE"
    fi

    cleanup_info_mount
}

err() {
    echo "error: $*" 1>&2 | tee -a "$LOG_FILE"
    exit 1
}

warn() {
    echo "warning: $*" 1>&2 | tee -a "$LOG_FILE"
}

debug() {
    if [ -n "$DEBUG" ]; then
        echo "debug: $*" 1>&2 | tee -a "$LOG_FILE"
    fi
}

run() {
    local status
    debug "$*"
    LIBC_FATAL_STDERR_=1 MALLOC_CHECK_=3 "$@"
    status=$?
    if [ $status -ne 0 ]; then
        err "$* failed with $status"
    fi
}

hyb_check_size() {
    local device=$1
    local min=$2
    local max=$3
    local size
    
    if [ ! -f "/sys/block/$device/size" ]; then
        debug "hyb_check_size: /sys/block/$device/size not found"
        return 1
    fi
    
    size=$(( $(cat "/sys/block/$device/size" 2>/dev/null || echo "0") / 2048 ))

    if [ "$size" -lt "$min" ]; then
        debug "hyb_check_size: $device too small (size: $size MB, min: $min MB, max: $max MB)"
        return 1
    elif [ -n "$max" ] && [ "$size" -ge "$max" ]; then
        debug "hyb_check_size: $device too big (size: $size MB, min: $min MB, max: $max MB)"
        return 1
    else
        debug "hyb_check_size: $device within limits (size: $size MB, min: $min MB, max: $max MB)"
        return 0
    fi
}

hyb_find_disk() {
    local product
    product=$(dmidecode -s system-product-name)
    local minimum="10000"
    local maximum="64000"
    local selector=""

    case $product in
        Appliance\ D1|Appliance\ D2)
            selector='/usb1/1-8/'
            ;;
        Appliance\ D3*)
            selector='/ata1/host0/'
            ;;
        Appliance\ F[1-2])
            selector='/nvme0n1'
            maximum="115000"
            ;;
        *)
            err "Not a valid Hybrid Appliance platform ($product). Execution halted."
            ;;
    esac

    log_info "Detecting embedded disk for platform: $product"
    debug "hyb_find_disk: minimum=$minimum MB maximum=$maximum MB selector=$selector"

    local disk=""
    for disk in sda sdb sdc sdd sde sdf sdg sdh nvme0n1; do
        if [ ! -e "/sys/block/$disk" ]; then
            debug "hyb_find_disk: $disk does not exist"
            continue
        fi

        # Skip removable media (optical drives, USB keys with removable flag)
        if [ -f "/sys/block/$disk/removable" ]; then
            local removable
            removable=$(cat "/sys/block/$disk/removable" 2>/dev/null)
            if [ "$removable" = "1" ]; then
                debug "hyb_find_disk: $disk is removable media, skipping"
                continue
            fi
        fi

        local path
        path="$(readlink "/sys/block/$disk" 2>/dev/null)"
        if [ -z "$path" ]; then
            debug "hyb_find_disk: $disk readlink failed"
            continue
        fi
        
        if ! echo "$path" | grep -q "$selector"; then
            debug "hyb_find_disk: $disk does not match selector $selector (path: $path)"
            continue
        fi

        if hyb_check_size "$disk" "$minimum" "$maximum"; then
            log_info "Found embedded disk: /dev/$disk"
            debug "hyb_find_disk: found $disk"
            echo "$disk"
            return 0
        fi
    done

    debug "hyb_find_disk: no disk found"
    echo ""
    return 1
}

hyb_main "$@"
