#!/usr/bin/env bash
# Copyright (c) 2024–2025, LongQT-sea

# mkmaciso – the ultimate tool for creating macOS installer ISO and DMG images

set -e

# Official Apple download URLs
LION_URL="https://updates.cdn-apple.com/2021/macos/041-7683-20210614-E610947E-C7CE-46EB-8860-D26D71F0D3EA/InstallMacOSX.dmg"
MOUNTAIN_LION_URL="https://updates.cdn-apple.com/2021/macos/031-0627-20210614-90D11F33-1A65-42DD-BBEA-E1D9F43A6B3F/InstallMacOSX.dmg"
YOSEMITE_URL="http://updates-http.cdn-apple.com/2019/cert/061-41343-20191023-02465f92-3ab5-4c92-bfe2-b725447a070d/InstallMacOSX.dmg"
EL_CAPITAN_URL="http://updates-http.cdn-apple.com/2019/cert/061-41424-20191024-218af9ec-cf50-4516-9011-228c78eda3d2/InstallMacOSX.dmg"
SIERRA_URL="http://updates-http.cdn-apple.com/2019/cert/061-39476-20191023-48f365f4-0015-4c41-9f44-39d3d2aca067/InstallOS.dmg"

CATALINA_BASE_URL="https://swcdn.apple.com/content/downloads/26/37/001-68446/r1dbqtmf3mtpikjnd04cq31p4jk91dceh8/"
MOJAVE_BASE_URL="https://swcdn.apple.com/content/downloads/17/32/061-26589-A_8GJTCGY9PC/25fhcu905eta7wau7aoafu8rvdm7k1j4el/"
HIGH_SIERRA_BASE_URL="https://swcdn.apple.com/content/downloads/06/50/041-91758-A_M8T44LH2AW/b5r4og05fhbgatve4agwy4kgkzv07mdid9/"

# Default parameters
VERSION="${1:-}"
IMAGE_FORMAT="${2:-}"
OUTPUT_PATH="${3:-}"
RETRIES_COUNT=10
FINAL_OUTPUT_PATH=""
DISK_ID=""

CPU_ARCH=$(uname -m)
KERNEL_VERSION=$(uname -r | cut -d'.' -f1)

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'

[ "$(uname -s)" != "Darwin" ] && echo "${RED}Error: macOS only${NC}" && exit 1
[ "$KERNEL_VERSION" -lt 13 ] && echo "${RED}Requires Mavericks (10.9) or newer${NC}" && exit 1

# Helper functions
log_info() { echo -e "${GREEN}$(date +'%H:%M:%S') [INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}$(date +'%H:%M:%S') [WARN]${NC} $1"; }
log_error() { echo -e "${RED}$(date +'%H:%M:%S') [ERROR]${NC} $1"; }

check_sudo_access() {
    sudo -v || { log_error "This script requires administrator privileges"; exit 1; }
    while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null &
}

check_disk_space() {
    local required_gb=40 threshold_gb=15
    local available=$(df -g . | awk 'NR==2 {print $4}')
    
    if [ "$available" -lt "$threshold_gb" ]; then
        log_error "CRITICAL: Only ${available} GB available"
        exit 1
    elif [ "$available" -lt "$required_gb" ]; then
        log_warn "Low disk space - ${available} GB available"
        echo -ne "${YELLOW}[WARN]${NC} Continue? (Y/n - auto-yes in 10 seconds): "
        read -t 10 answer || answer="y"
        [[ "$answer" =~ ^[Nn] ]] && exit 1
    fi
}

detach_disk() {
    local disk="$1"
    [ -z "$disk" ] && return 0
    
    for attempt in $(seq 1 "$RETRIES_COUNT"); do
        log_info "Detach attempt $attempt of $RETRIES_COUNT..."
        if sync && sleep 5 && hdiutil detach -quiet "$disk" || hdiutil detach -quiet "$disk" -force; then
            log_info "Disk detached successfully"
            return 0
        fi
        [ "$attempt" -lt "$RETRIES_COUNT" ] && log_warn "Detach failed, retrying..."
    done
    log_error "Failed to detach $disk after $RETRIES_COUNT attempts"
    return 1
}

cleanup() {
    if [ -n "$WORK_DIR" ] && [ -d "$WORK_DIR" ] && [ "$WORK_DIR" != "/" ] && [ "$WORK_DIR" != "$HOME" ]; then
        for mnt in "$WORK_DIR"/*_mnt; do
            [ -d "$mnt" ] && detach_disk "$mnt" 2>/dev/null || true
        done
        [ -n "${DISK_ID:-}" ] && detach_disk "$DISK_ID"
        log_info "Cleaning up temporary files..."
        sudo rm -rf "$WORK_DIR"
    fi
}

trap cleanup EXIT

get_version_number() {
    local codename="$1"
    case "$codename" in
        "lion") echo "10.7" ;; "mountainlion") echo "10.8" ;; "mavericks") echo "10.9" ;;
        "yosemite") echo "10.10" ;; "elcapitan") echo "10.11" ;; "sierra") echo "10.12" ;;
        "highsierra") echo "10.13" ;; "mojave") echo "10.14" ;; "catalina") echo "10.15" ;;
        "bigsur") echo "11" ;; "monterey") echo "12" ;; "ventura") echo "13" ;;
        "sonoma") echo "14" ;; "sequoia") echo "15" ;; "tahoe") echo "26" ;;
        *) echo "" ;;
    esac
}

get_codename() {
    local version="$1"
    case "$version" in
        "10.7") echo "Lion" ;; "10.8") echo "Mountain_Lion" ;; "10.9") echo "Mavericks" ;;
        "10.10") echo "Yosemite" ;; "10.11") echo "El_Capitan" ;; "10.12") echo "Sierra" ;;
        "10.13") echo "High_Sierra" ;; "10.14") echo "Mojave" ;; "10.15") echo "Catalina" ;;
        "11") echo "Big_Sur" ;; "12") echo "Monterey" ;; "13") echo "Ventura" ;;
        "14") echo "Sonoma" ;; "15") echo "Sequoia" ;; "26") echo "Tahoe" ;;
        *) echo "" ;;
    esac
}

get_installer_app_name() {
    local v="$1"
    case "$v" in
        "10.7") echo "Install Mac OS X Lion" ;;
        "10.8") echo "Install OS X Mountain Lion" ;;
        "10.9") echo "Install OS X Mavericks" ;;
        "10.10") echo "Install OS X Yosemite" ;;
        "10.11") echo "Install OS X El Capitan" ;;
        "10.12") echo "Install macOS Sierra" ;;
        "10.13") echo "Install macOS High Sierra" ;;
        "10.14") echo "Install macOS Mojave" ;;
        "10.15") echo "Install macOS Catalina" ;;
        "11") echo "Install macOS Big Sur" ;;
        "12") echo "Install macOS Monterey" ;;
        "13") echo "Install macOS Ventura" ;;
        "14") echo "Install macOS Sonoma" ;;
        "15") echo "Install macOS Sequoia" ;;
        "26") echo "Install macOS Tahoe" ;;
        *) echo "" ;;
    esac
}

# Get DMG size based on version
get_dmg_size() {
    local v="$1"
    case "$v" in
        10.9) echo "1400m" ;;
        10.10|10.11|10.12|10.13|10.14) echo "7g" ;;
        10.15) echo "9g" ;;
        11|12|13) echo "15g" ;;
        14|15) echo "18g" ;;
        *) echo "20g" ;;
    esac
}

# ==========================
# Interactive Menu Functions
# ==========================

declare -a MACOS_VERSIONS=(
    "10.7|Lion|2011" "10.8|Mountain Lion|2012" "10.9|Mavericks|2013"
    "10.10|Yosemite|2014" "10.11|El Capitan|2015" "10.12|Sierra|2016"
    "10.13|High Sierra|2017" "10.14|Mojave|2018" "10.15|Catalina|2019"
    "11|Big Sur|2020" "12|Monterey|2021" "13|Ventura|2022"
    "14|Sonoma|2023" "15|Sequoia|2024" "26|Tahoe|2025"
)

print_header() {
    clear
    echo -e "${BOLD}${CYAN}"
    echo "╔══════════════════════════════════════════════════════════════════════════════╗"
    echo "║ mkmaciso – the ultimate tool for creating macOS installer ISO and DMG images ║"
    echo "╠══════════════════════════════════════════════════════════════════════════════╣"
    echo "║                               Interactive mode                               ║"
    echo "╚══════════════════════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_separator() { echo -e "${CYAN}──────────────────────────────────────────────────────────────────────${NC}"; }

show_version_menu() {
    print_header
    echo -e "${BOLD}Step 1/3: Select macOS Version${NC}"
    print_separator
    echo ""
    echo -e "  ${BOLD}#   Version    Name              Year${NC}    ${BOLD}#   Version    Name              Year${NC}"
    print_separator
    
    local total=${#MACOS_VERSIONS[@]}
    local half=$(( (total + 1) / 2 ))
    
    for ((i=0; i<half; i++)); do
        IFS='|' read -r ver name year <<< "${MACOS_VERSIONS[$i]}"
        printf "  ${CYAN}%2d${NC})  %-8s  %-16s  %s" "$((i+2))" "$ver" "$name" "$year"
        local right_idx=$((i + half))
        if [ $right_idx -lt $total ]; then
            IFS='|' read -r ver name year <<< "${MACOS_VERSIONS[$right_idx]}"
            printf "    ${CYAN}%2d${NC})  %-8s  %-16s  %s" "$((right_idx+2))" "$ver" "$name" "$year"
        fi
        echo ""
    done
    echo ""
    print_separator
    echo -e "  ${YELLOW}Default: 16 (Tahoe - latest)${NC}"
    echo -n "  Enter your choice [2-$((total+1))] or press Enter for default: "
}

show_format_menu() {
    print_header
    echo -e "${BOLD}Step 2/3: Select Image Format${NC}"
    print_separator
    echo -e "  Selected macOS: $2 ($1)"
    print_separator
    echo -e "  ${CYAN}1${NC})  ${BOLD}ISO${NC}  - For virtual machines"
    echo -e "  ${CYAN}2${NC})  ${BOLD}DMG${NC}  - For USB drives"
    print_separator
    echo -e "  ${YELLOW}Default: [1] ISO${NC}"
    echo -n "  Enter your choice [1-2] or press Enter for default: "
}

show_output_menu() {
    print_header
    echo -e "${BOLD}Step 3/3: Select Output Location${NC}"
    print_separator
    echo -e "  Selected macOS: $2 ($1)"
    echo -e "  Selected Format: $(echo "$3" | tr '[:lower:]' '[:upper:]')"
    print_separator
    echo -e "  ${CYAN}1${NC})  Current Directory: $(pwd)"
    echo -e "  ${CYAN}2${NC})  Desktop: $HOME/Desktop"
    echo -e "  ${CYAN}3${NC})  Downloads: $HOME/Downloads"
    echo -e "  ${CYAN}4${NC})  Home: $HOME"
    echo -e "  ${CYAN}5${NC})  Custom Path"
    print_separator
    echo -e "  ${YELLOW}Default: [1] Current Directory${NC}"
    echo -n "  Enter your choice [1-5] or press Enter for default: "
}

run_interactive_menu() {
    local selected_version="" selected_name="" selected_format="" output_dir=""
    
    # Step 1: Select version
    while true; do
        show_version_menu
        read -r choice
        [ -z "$choice" ] && choice=16
        if [[ "$choice" =~ ^[0-9]+$ ]] && [ "$choice" -ge 2 ] && [ "$choice" -le $((${#MACOS_VERSIONS[@]} + 1)) ]; then
            IFS='|' read -r selected_version selected_name _ <<< "${MACOS_VERSIONS[$((choice - 2))]}"
            break
        fi
        echo -e "\n  ${RED}Invalid choice${NC}"; sleep 2
    done
    
    # Step 2: Select format
    while true; do
        show_format_menu "$selected_version" "$selected_name"
        read -r choice
        [ -z "$choice" ] && choice=1
        case "$choice" in
            1) selected_format="iso"; break ;;
            2) selected_format="dmg"; break ;;
            *) echo -e "\n  ${RED}Invalid choice${NC}"; sleep 2 ;;
        esac
    done
    
    # Step 3: Select output
    while true; do
        show_output_menu "$selected_version" "$selected_name" "$selected_format"
        read -r choice
        [ -z "$choice" ] && choice=1
        case "$choice" in
            1) output_dir="$(pwd)"; break ;;
            2) output_dir="$HOME/Desktop"; break ;;
            3) output_dir="$HOME/Downloads"; break ;;
            4) output_dir="$HOME"; break ;;
            5)
                echo -n "  Enter custom path: "
                read -r custom_path
                custom_path="${custom_path/#\~/$HOME}"
                if [ -d "$custom_path" ]; then
                    output_dir="$custom_path"; break
                else
                    echo -n "  Create it? [y/N]: "
                    read -r create_dir
                    [[ "$create_dir" =~ ^[Yy] ]] && mkdir -p "$custom_path" && output_dir="$custom_path" && break
                fi
                ;;
            *) echo -e "\n  ${RED}Invalid choice${NC}"; sleep 2 ;;
        esac
    done
    
    VERSION="$selected_version"
    IMAGE_FORMAT="$selected_format"
    OUTPUT_PATH="${output_dir}/macOS_${selected_name// /_}.${selected_format}"
    clear
}

# ==========================
# Download Functions
# ==========================

download_legacy_macos() {
    local version_num="$1"
    local download_url=""
    
    case "$version_num" in
        "10.7") download_url="$LION_URL" ;;
        "10.8") download_url="$MOUNTAIN_LION_URL" ;;
        "10.9") download_mavericks; return $? ;;
        "10.10") download_url="$YOSEMITE_URL" ;;
        "10.11") download_url="$EL_CAPITAN_URL" ;;
        "10.12") download_url="$SIERRA_URL" ;;
        *) log_error "Unsupported legacy version: $version_num"; return 1 ;;
    esac
    
    log_info "Downloading macOS $(get_codename $version_num)..."
    curl --retry 5 --max-time 1800 --connect-timeout 10 --progress-bar -L "$download_url" -o "$WORK_DIR/InstallMacOSX.dmg"
}

download_mavericks() {
    local board_serial_number="C0243070168G3M91F"
    local board_id="Mac-3CBD00234E554E41"
    local rom="003EE1E6AC14"
    
    hex_to_bin() { printf "%s" "$1" | xxd -r -p; }
    
    local server_id=$(curl -fs -c - http://osrecovery.apple.com/ | tail -1 | awk '{print $NF}')
    local client_id=$(dd if=/dev/urandom bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \n' | tr '[:lower:]' '[:upper:]')
    
    {
        hex_to_bin "$client_id"
        hex_to_bin "$(echo $server_id | awk -F'~' '{print $2}')"
        hex_to_bin "$rom"
        printf "%s" "${board_serial_number}${board_id}" | iconv -t utf-8 | openssl dgst -sha256 -binary
        printf '\xCC\xCC\xCC\xCC\xCC\xCC\xCC\xCC\xCC\xCC'
    } > "$WORK_DIR/key_info"
    
    local key=$(openssl dgst -sha256 -binary < "$WORK_DIR/key_info" | od -An -tx1 | tr -d ' \n' | tr '[:lower:]' '[:upper:]')
    rm "$WORK_DIR/key_info"
    
    local installation_payload=$(curl -fs 'http://osrecovery.apple.com/InstallationPayload/OSInstaller' -X POST \
        -H 'Content-Type: text/plain' --cookie "session=$server_id" \
        -d "cid=$client_id
sn=$board_serial_number
bid=$board_id
k=$key")
    
    local mavericks_url=$(echo "$installation_payload" | grep AU | awk -F': ' '{print $2}')
    local token=$(echo "$installation_payload" | grep AT | awk -F': ' '{print $2}')
    
    log_info "Downloading macOS Mavericks..."
    curl --retry 5 --max-time 1800 --connect-timeout 10 --progress-bar -L "$mavericks_url" \
        -H "Cookie: AssetToken=$token" -o "$WORK_DIR/InstallESD.dmg"
}

install_legacy_app() {
    local version_num="$1"
    local dmg_file="$2"
    
    log_info "Installing macOS $(get_codename $version_num) installer..."
    
    if [[ "$version_num" =~ ^(10\.7|10\.8|10\.10|10\.11|10\.12)$ ]]; then
        hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/downloaded_dmg_mnt" "$dmg_file"
        
        if [ "$CPU_ARCH" == "arm64" ]; then
            log_info "Apple silicon detected, using manual installation..."
            pkgutil --expand "$WORK_DIR/downloaded_dmg_mnt"/*.pkg "$WORK_DIR/pkg_extracted"
            local inner_pkg=$(ls -d "$WORK_DIR/pkg_extracted"/*.pkg 2>/dev/null | head -1)
            cd /Applications && sudo cpio -idm < "$inner_pkg/Payload" && cd - > /dev/null
            local app_path="/Applications/$(get_installer_app_name $version_num).app"
            sudo ditto "$inner_pkg/InstallESD.dmg" "$app_path/Contents/SharedSupport/InstallESD.dmg"
            sudo chown root:wheel "$app_path/Contents/SharedSupport/InstallESD.dmg"
        else
            sudo installer -pkg "$WORK_DIR/downloaded_dmg_mnt"/*.pkg -target /
        fi
        sync && detach_disk "$WORK_DIR/downloaded_dmg_mnt"
        
    elif [ "$version_num" == "10.9" ]; then
        if [ -f "$WORK_DIR/InstallESD.dmg" ]; then
            hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" "$WORK_DIR/InstallESD.dmg"
            hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/BaseSystem_mnt" "$WORK_DIR/InstallESD_mnt/BaseSystem.dmg"
            
            sudo cp -a "$WORK_DIR/BaseSystem_mnt/Install OS X Mavericks.app" "/Applications/"
            sudo mkdir "/Applications/Install OS X Mavericks.app/Contents/SharedSupport"
            sudo cp -a "$WORK_DIR/InstallESD.dmg" "/Applications/Install OS X Mavericks.app/Contents/SharedSupport/InstallESD.dmg"
            sudo cp -a "$WORK_DIR/InstallESD_mnt/Packages/OSInstall.mpkg" "/Applications/Install OS X Mavericks.app/Contents/SharedSupport/"
            sudo chown -R root:wheel "/Applications/Install OS X Mavericks.app/Contents/SharedSupport/"
            
            sync && detach_disk "$WORK_DIR/BaseSystem_mnt"
            sync && detach_disk "$WORK_DIR/InstallESD_mnt"
        fi
    fi
    log_info "Installed $(get_installer_app_name $version_num) to /Applications"
}

direct_download_10_13_10_15() {
    local version_num="$1"
    local base_url=""
    
    case "$version_num" in
        "10.13") base_url="$HIGH_SIERRA_BASE_URL" ;;
        "10.14") base_url="$MOJAVE_BASE_URL" ;;
        "10.15") base_url="$CATALINA_BASE_URL" ;;
        *) return 1 ;;
    esac
    
    log_info "Downloading macOS $(get_codename $version_num) using direct URLs..."
    
    local files=("BaseSystem.dmg" "BaseSystem.chunklist" "InstallInfo.plist" 
                 "InstallESDDmg.pkg" "AppleDiagnostics.dmg" "AppleDiagnostics.chunklist")
    
    for filename in "${files[@]}"; do
        log_info "Downloading ${filename}..."
        curl --retry 5 --max-time 1800 --connect-timeout 10 --progress-bar \
            -L "${base_url}${filename}" -o "$WORK_DIR/${filename}" || return 1
    done
    
    log_info "Building installer app..."
    hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/BaseSystem_mnt" "$WORK_DIR/BaseSystem.dmg"
    
    local installer_app="$WORK_DIR/BaseSystem_mnt/$(get_installer_app_name $version_num).app"
    sudo cp -Rp "$installer_app" "/Applications/"
    
    local shared_support="/Applications/$(get_installer_app_name $version_num).app/Contents/SharedSupport"
    sudo mkdir -p "$shared_support"
    
    mv "$WORK_DIR/InstallESDDmg.pkg" "$WORK_DIR/InstallESD.dmg"
    sed -e "s/InstallESDDmg\.pkg/InstallESD.dmg/" \
        -e "s/pkg\.InstallESDDmg/dmg.InstallESD/" \
        -e "/InstallESD\.dmg/{n;N;N;N;d;}" \
        "$WORK_DIR/InstallInfo.plist" > "$WORK_DIR/InstallInfo_fixed.plist"
    
    sudo cp -Rp "$WORK_DIR/BaseSystem.dmg" "$WORK_DIR/BaseSystem.chunklist" \
                "$WORK_DIR/InstallESD.dmg" "$WORK_DIR/AppleDiagnostics.dmg" \
                "$WORK_DIR/AppleDiagnostics.chunklist" "$shared_support/"
    sudo cp -Rp "$WORK_DIR/InstallInfo_fixed.plist" "$shared_support/InstallInfo.plist"
    sudo chown -R root:wheel "$shared_support"
    
    if [ "$CPU_ARCH" == "arm64" ]; then
        sudo codesign -s - -f "/Applications/$(get_installer_app_name $version_num).app/Contents/Resources/createinstallmedia"
        sudo xattr -r -d com.apple.quarantine "/Applications/$(get_installer_app_name $version_num).app"
    fi
    
    sync && sleep 10 && detach_disk "$WORK_DIR/BaseSystem_mnt"
    log_info "Successfully installed $(get_installer_app_name $version_num)"
}

download_modern_macos() {
    local version_num="$1"
    local version_name=$(get_codename $version_num | tr '_' ' ')
    
    if [[ "$version_num" =~ ^10\.1[345]$ ]]; then
        if [ "$CPU_ARCH" == "arm64" ]; then
            log_warn "Apple silicon: softwareupdate cannot download older macOS versions"
            direct_download_10_13_10_15 "$version_num"
            return $?
        fi
        if [ "$KERNEL_VERSION" -lt 20 ]; then
            direct_download_10_13_10_15 "$version_num"
            return $?
        fi
    fi
    
    if [ "$CPU_ARCH" = "x86_64" ] && [ "$KERNEL_VERSION" -lt 20 ]; then
        log_error "Intel Macs require macOS 11+ for softwareupdate"
        return 1
    fi
    
    log_info "Fetching available installers..."
    softwareupdate --list-full-installers 2>/dev/null | grep "* Title:" > $WORK_DIR/installers.txt
    
    local selected_version_number=$(grep -i "$version_name" $WORK_DIR/installers.txt | head -1 | sed -n 's/.*Version: \([^,]*\).*/\1/p')
    
    if [ -z "$selected_version_number" ]; then
        log_error "macOS $version_name not available for download"
        return 1
    fi
    
    log_info "Downloading macOS $version_name $selected_version_number..."
    
    for attempt in $(seq 1 4); do
        log_info "Download attempt $attempt of 4..."
        softwareupdate --fetch-full-installer --full-installer-version "$selected_version_number" && return 0
        [ $attempt -lt 4 ] && sleep 5
    done
    log_error "Download failed"
    return 1
}

# ========================================
# COMBINED: Image Creation Functions
# ========================================

# Extract version number from mounted volume
get_exact_version() {
    local mount_path="$1"
    defaults read "$mount_path/System/Library/CoreServices/SystemVersion" ProductVersion
}

# Set final output path with version number
set_final_output_path() {
    local base_path="$1"
    local exact_version="$2"
    local ext="$3"
    
    if [ "$ext" == "dmg" ]; then
        FINAL_OUTPUT_PATH="${base_path%.dmg}_${exact_version}.dmg.img"
    else
        FINAL_OUTPUT_PATH="${base_path%.iso}_${exact_version}.iso"
    fi
}

# Convert to final format (ISO or DMG)
finalize_image() {
    local source="$1"
    local volume_name="$2"
    local format="$3"
    
    if [ "$format" == "iso" ]; then
        log_info "Converting to ISO format..."
        sudo hdiutil makehybrid -quiet -ov -hfs -udf -default-volume-name "$volume_name" "$source" -o "$FINAL_OUTPUT_PATH"
    else
        log_info "Optimizing DMG file size..."
        sudo hdiutil resize -size min "$source"
        mv -f "$source" "$FINAL_OUTPUT_PATH"
    fi
}

# Create image for 10.7-10.8 (both ISO and DMG)
create_image_10_7_10_8() {
    local installer_path="$1"
    local output_file="$2"
    local volume_name="$3"
    local version_num="$4"
    
    log_info "Creating macOS $(get_codename $version_num) $(echo $IMAGE_FORMAT | tr '[:lower:]' '[:upper:]') image..."
    
    hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" \
        "$installer_path/Contents/SharedSupport/InstallESD.dmg"
    
    local exact_version=$(get_exact_version "$WORK_DIR/InstallESD_mnt")
    set_final_output_path "$output_file" "$exact_version" "$IMAGE_FORMAT"
    
    if [ "$IMAGE_FORMAT" == "dmg" ]; then
        sudo hdiutil create -quiet -layout GPTSPUD -format UDRW -ov \
            -volname "$volume_name" -srcdir "$WORK_DIR/InstallESD_mnt" "${FINAL_OUTPUT_PATH%.img}"

        mv -f "${FINAL_OUTPUT_PATH%.img}" "$FINAL_OUTPUT_PATH"
        sync && detach_disk "$WORK_DIR/InstallESD_mnt"
    else
        sync && detach_disk "$WORK_DIR/InstallESD_mnt"
        sudo hdiutil makehybrid -quiet -ov -hfs -udf -default-volume-name "$volume_name" \
            "$installer_path/Contents/SharedSupport/InstallESD.dmg" -o "$FINAL_OUTPUT_PATH"
    fi
}

# COMBINED: Manual method for 10.9-10.12 and 10.15 on Apple Silicon
# Handles ISO for 10.9-10.12, and both ISO/DMG for 10.15 alt method
create_image_manual_method() {
    local installer_path="$1"
    local output_file="$2"
    local volume_name="$3"
    local version_num="$4"
    
    log_info "Creating macOS $(get_codename $version_num) $(echo $IMAGE_FORMAT | tr '[:lower:]' '[:upper:]') image (manual method)..."
    
    # Mount InstallESD.dmg
    hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" \
        "$installer_path/Contents/SharedSupport/InstallESD.dmg"
    
    # Determine BaseSystem.dmg location
    local basesystem_path
    if [ "$version_num" == "10.15" ]; then
        basesystem_path="$installer_path/Contents/SharedSupport/BaseSystem.dmg"
    else
        basesystem_path="$WORK_DIR/InstallESD_mnt/BaseSystem.dmg"
    fi
    
    # Determine required size
    local resize_size
    case "$version_num" in
        10.9|10.10) resize_size="7.1g" ;;
        10.11) resize_size="7.1g" ;;
        10.12) resize_size="5.9g" ;;
        10.15) resize_size="9g" ;;
        *) resize_size="7g" ;;
    esac
    
    # For DMG 10.9-10.10: special partition handling
    if [ "$IMAGE_FORMAT" == "dmg" ] && [[ "$version_num" =~ ^10\.(9|10)$ ]]; then
        local BaseSystem_DISK_ID=$(hdiutil attach "$basesystem_path" -nomount | grep -o '/dev/disk[0-9]*' | head -1)
        hdiutil create -quiet -ov -fs hfs+ -size 1400m "$WORK_DIR/installer_gpt.dmg"
        DISK_ID=$(hdiutil attach "$WORK_DIR/installer_gpt.dmg" -nomount | grep -o '/dev/disk[0-9]*' | head -1)
        sudo dd if="${BaseSystem_DISK_ID}s2" of="${DISK_ID}s1" bs=1m
        detach_disk "$BaseSystem_DISK_ID"
        detach_disk "$DISK_ID" && DISK_ID=""
        sudo hdiutil resize -size 7g "$WORK_DIR/installer_gpt.dmg"
        DISK_ID=$(hdiutil attach -nobrowse -mountpoint "$WORK_DIR/installer_mnt" "$WORK_DIR/installer_gpt.dmg" | grep -o '/dev/disk[0-9]*' | head -1)
        local mount_point="$WORK_DIR/installer_mnt"
    else
        # Standard: convert and resize BaseSystem.dmg
        hdiutil convert -quiet "$basesystem_path" -format UDRW -o "$WORK_DIR/BaseSystem_converted.dmg"
        sudo hdiutil resize -size $resize_size "$WORK_DIR/BaseSystem_converted.dmg"
        DISK_ID=$(hdiutil attach -nobrowse -mountpoint "$WORK_DIR/BaseSystem_mnt" "$WORK_DIR/BaseSystem_converted.dmg" | grep -o '/dev/disk[0-9]*' | head -1)
        local mount_point="$WORK_DIR/BaseSystem_mnt"
    fi
    
    # Rename volume
    diskutil rename "${DISK_ID}s1" "$volume_name" 2>/dev/null || true
    
    # Copy files based on version
    if [ "$version_num" == "10.15" ]; then
        # Remove stub app and copy full installer
        rm -rf "$mount_point/$(get_installer_app_name $version_num).app"
        cp -R "$installer_path" "$mount_point/"
    else
        # Remove Packages symlink and copy actual Packages
        rm -f "$mount_point/System/Installation/Packages"
        if [ "$IMAGE_FORMAT" == "dmg" ] && [[ "$version_num" =~ ^10\.(9|10|11|12)$ ]]; then
            ditto "$WORK_DIR/InstallESD_mnt/Packages" "$mount_point/System/Installation/Packages"
        else
            cp -R "$WORK_DIR/InstallESD_mnt/Packages" "$mount_point/System/Installation/"
        fi
        cp "$WORK_DIR/InstallESD_mnt/BaseSystem.dmg" "$mount_point/"
        cp "$WORK_DIR/InstallESD_mnt/BaseSystem.chunklist" "$mount_point/"
        
        # Mavericks special: copy kernel
        if [ "$version_num" == "10.9" ]; then
            cp "$mount_point/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache" "$mount_point/mach_kernel"
        fi
    fi
    
    # Get exact version
    local exact_version=$(get_exact_version "$mount_point")
    set_final_output_path "$output_file" "$exact_version" "$IMAGE_FORMAT"
    
    sync && sleep 5
    detach_disk "$WORK_DIR/InstallESD_mnt"
    detach_disk "$DISK_ID" && DISK_ID=""
    
    # Finalize
    local source_dmg
    if [ "$IMAGE_FORMAT" == "dmg" ] && [[ "$version_num" =~ ^10\.(9|10|11|12)$ ]]; then
        source_dmg="$WORK_DIR/installer_gpt.dmg"
    else
        source_dmg="$WORK_DIR/BaseSystem_converted.dmg"
    fi
    
    finalize_image "$source_dmg" "$volume_name" "$IMAGE_FORMAT"
}

# COMBINED: createinstallmedia method for 10.12+ (both ISO and DMG)
create_image_createinstallmedia() {
    local installer_path="$1"
    local output_file="$2"
    local version_num="$3"
    local volume_name=$(get_codename $version_num)
    
    # Redirect to manual method for Apple Silicon edge cases
    if [ "$CPU_ARCH" == "arm64" ]; then
        if [ "$version_num" == "10.12" ]; then
            create_image_manual_method "$installer_path" "$output_file" \
                "$(get_installer_app_name $version_num)" "$version_num"
            return $?
        elif [ "$version_num" == "10.15" ]; then
            create_image_manual_method "$installer_path" "$output_file" \
                "$(get_installer_app_name $version_num)" "$version_num"
            return $?
        fi
    fi
    
    log_info "Creating macOS $(get_codename $version_num) $(echo $IMAGE_FORMAT | tr '[:lower:]' '[:upper:]') image..."
    
    # Create base image
    if [ "$IMAGE_FORMAT" == "iso" ]; then
        hdiutil create -quiet -size 20g -volname "${volume_name}_iso" -fs HFS+ -type SPARSE -attach "$WORK_DIR/installer.sparseimage"
        local image_file="$WORK_DIR/installer.sparseimage"
        local vol_suffix="_iso"
    else
        local dmg_size=$(get_dmg_size "$version_num")
        hdiutil create -quiet -size $dmg_size -volname "${volume_name}_dmg" -fs HFS+ -type UDIF -attach "$WORK_DIR/installer.dmg"
        local image_file="$WORK_DIR/installer.dmg"
        local vol_suffix="_dmg"
    fi
    
    DISK_ID=$(diskutil list | grep "${volume_name}${vol_suffix}" | head -1 | awk '{print $NF}' | sed 's/s[0-9]*$//')
    
    # Prepare createinstallmedia command
    local cmd="sudo '$installer_path/Contents/Resources/createinstallmedia' --volume /Volumes/${volume_name}${vol_suffix} --nointeraction"
    
    # Version-specific patches
    if [ "$version_num" == "10.12" ]; then
        log_info "Patching Info.plist for Sierra..."
        sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.03'" "$installer_path/Contents/Info.plist"
        cmd="$cmd --applicationpath \"$installer_path\""
    elif [[ "$version_num" =~ ^10\.1[01]$ ]]; then
        cmd="$cmd --applicationpath \"$installer_path\""
    fi
    
    log_info "Running createinstallmedia..."
    bash -c "$cmd"
    sync && sleep 5
    
    # Restore Sierra plist
    if [ "$version_num" == "10.12" ]; then
        sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.06'" "$installer_path/Contents/Info.plist"
        sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.06'" "/Volumes/Install macOS Sierra/Install macOS Sierra.app/Contents/Info.plist"
    fi
    
    # Get exact version
    local exact_version=$(get_exact_version "/Volumes/$(get_installer_app_name $version_num)")
    set_final_output_path "$output_file" "$exact_version" "$IMAGE_FORMAT"
    
    # DMG-specific: optimize partition size
    if [ "$IMAGE_FORMAT" == "dmg" ]; then
        log_info "Optimizing DMG file size..."
        
        local MIN_SIZE=$(diskutil resizeVolume ${DISK_ID}s2 limits | grep "Minimum (constrained by file usage)" | sed 's/.*(\([0-9]*\) Bytes)/\1/')
        
        # Add buffer for 10.10-10.11
        [[ "$version_num" =~ ^10\.1[01]$ ]] && MIN_SIZE=$((MIN_SIZE + 52428800))
        
        log_info "Shrinking partition to minimum..."
        diskutil resizeVolume ${DISK_ID}s2 "${MIN_SIZE}B" free free 0 >/dev/null 2>&1
        
        log_info "Expanding to consolidate..."
        for attempt in $(seq 1 $RETRIES_COUNT); do
            diskutil resizeVolume ${DISK_ID}s2 0 >/dev/null 2>&1 && break
            sync && sleep 5
        done
    fi
    
    detach_disk "$DISK_ID" && DISK_ID=""
    finalize_image "$image_file" "$(get_installer_app_name $version_num)" "$IMAGE_FORMAT"
}

# ========================================
# Main Entry Point for Image Creation
# ========================================

create_installer_image() {
    local installer_path="$1"
    local output_file="$2"
    local version_num="$3"
    local volume_name=$(get_installer_app_name "$version_num")
    
    case "$version_num" in
        10.7|10.8)
            create_image_10_7_10_8 "$installer_path" "$output_file" "$volume_name" "$version_num"
            ;;
        10.9)
            if [ "$IMAGE_FORMAT" == "iso" ]; then
                create_image_manual_method "$installer_path" "$output_file" "$volume_name" "$version_num"
            else
                create_image_manual_method "$installer_path" "$output_file" "$volume_name" "$version_num"
            fi
            ;;
        10.10|10.11)
            if [ "$IMAGE_FORMAT" == "iso" ]; then
                create_image_manual_method "$installer_path" "$output_file" "$volume_name" "$version_num"
            else
                if [ "$CPU_ARCH" == "arm64" ]; then
                    create_image_manual_method "$installer_path" "$output_file" "$volume_name" "$version_num"
                else
                    create_image_createinstallmedia "$installer_path" "$output_file" "$version_num"
                fi
            fi
            ;;
        *)
            create_image_createinstallmedia "$installer_path" "$output_file" "$version_num"
            ;;
    esac
}

# ==========================
# Main Script
# ==========================

main() {
    echo -e "${BOLD}${CYAN}"
    echo "╔══════════════════════════════════════════════════════════════════════════════╗"
    echo "║ mkmaciso – the ultimate tool for creating macOS installer ISO and DMG images ║"
    echo "╚══════════════════════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
    
    check_disk_space
    check_sudo_access
    
    IMAGE_FORMAT=$(echo "$IMAGE_FORMAT" | tr '[:upper:]' '[:lower:]')
    [[ -z "$IMAGE_FORMAT" ]] && IMAGE_FORMAT="iso"
    [[ "$IMAGE_FORMAT" != "iso" && "$IMAGE_FORMAT" != "dmg" ]] && IMAGE_FORMAT="dmg"
    
    VERSION=$(echo "$VERSION" | tr '[:upper:]' '[:lower:]' | tr -d '_- ')
    
    VERSION_NUM=""
    if [[ "$VERSION" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
        VERSION_NUM="$VERSION"
    else
        VERSION_NUM=$(get_version_number "$VERSION")
    fi
    
    VERSION_NAME=$(get_codename "$VERSION_NUM")
    
    if [ -z "$VERSION_NAME" ]; then
        log_error "Unknown macOS version: $VERSION"
        log_info "Supported: 10.7-10.15, 11-15, 26"
        exit 1
    fi
    
    log_info "Target: ${GREEN}$VERSION_NAME ($VERSION_NUM)${NC}"
    log_info "Format: ${GREEN}$(echo $IMAGE_FORMAT | tr '[:lower:]' '[:upper:]')${NC}"
    
    if [ -z "$OUTPUT_PATH" ]; then
        OUTPUT_PATH="$(pwd)/macOS_${VERSION_NAME}.${IMAGE_FORMAT}"
    else
        [[ "$OUTPUT_PATH" != *.$IMAGE_FORMAT ]] && OUTPUT_PATH="${OUTPUT_PATH%.*}.$IMAGE_FORMAT"
        [[ "$OUTPUT_PATH" != /* ]] && OUTPUT_PATH="$(cd "$(dirname "$OUTPUT_PATH")" && pwd)/$(basename "$OUTPUT_PATH")"
    fi
    
    log_info "Output: ${GREEN}$OUTPUT_PATH${NC}"
    echo ""
    
    WORK_DIR=$(mktemp -d -t LongQT-sea)
    log_info "Work dir: ${CYAN}$WORK_DIR${NC}"
    echo ""
    
    INSTALLER_PATH="/Applications/$(get_installer_app_name "$VERSION_NUM").app"
    
    if [ -d "$INSTALLER_PATH" ]; then
        log_info "Found existing installer: ${CYAN}$INSTALLER_PATH${NC}"
    else
        log_info "Downloading installer..."
        if [[ "$VERSION_NUM" =~ ^10\.(7|8|9|10|11|12)$ ]]; then
            download_legacy_macos "$VERSION_NUM"
            install_legacy_app "$VERSION_NUM" "$WORK_DIR/InstallMacOSX.dmg"
        else
            download_modern_macos "$VERSION_NUM" || exit 1
        fi
        
        [ ! -d "$INSTALLER_PATH" ] && log_error "Failed to install" && exit 1
    fi
    
    echo ""
    create_installer_image "$INSTALLER_PATH" "$OUTPUT_PATH" "$VERSION_NUM"
    
    if [ -f "$FINAL_OUTPUT_PATH" ]; then
        local FILE_SIZE_BYTES=$(stat -f%z "$FINAL_OUTPUT_PATH")
        local FILE_SIZE_GB=$(du -h "$FINAL_OUTPUT_PATH" | cut -f1)
        
        if [ "$FILE_SIZE_BYTES" -lt 4294967296 ]; then
            log_error "Image too small (<4GB), likely corrupted"
            rm -f "$FINAL_OUTPUT_PATH"
            exit 1
        fi
        
        echo ""
        log_info "Success!"
        log_info "File: $FINAL_OUTPUT_PATH"
        log_info "Size: $FILE_SIZE_GB"
    else
        log_error "Failed to create image"
        exit 1
    fi
}

# Help
if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
    cat << 'EOF'
mkmaciso – the ultimate tool for creating macOS installer ISO/DMG images

Usage: mkmaciso [VERSION] [FORMAT] [OUTPUT_PATH]

Examples:
  mkmaciso                    Interactive mode
  mkmaciso 14                 Create Sonoma ISO
  mkmaciso 14 dmg             Create Sonoma DMG
  mkmaciso sonoma dmg ~/out   Custom output path

Supported versions: 10.7-10.15, 11-15, 26
EOF
    exit 0
fi

# Interactive mode check
if [ $# -eq 0 ]; then
    if [ -p /dev/stdin ] || [ ! -t 0 ]; then
        log_error "Interactive mode unavailable when piped"
        exit 1
    fi
    run_interactive_menu
fi

main
