From 828b53128df8b5d0a3cc88de7d7aa57162a337c8 Mon Sep 17 00:00:00 2001 From: LongQT-sea Date: Mon, 15 Dec 2025 20:54:45 +0700 Subject: [PATCH] ref: Move creation logic to standalone script, add legacy macOS support Move macOS installer image creation logic from GitHub workflow file to a dedicated shell script `mkmaciso` for better maintainability and reusability. Changes: - Add support for legacy macOS versions: - 10.7 (Lion) - 10.8 (Mountain Lion) - 10.9 (Mavericks) - 10.10 (Yosemite) - 10.11 (El Capitan) - 10.12 (Sierra) - Simplify workflow to call external script - Enable running `mkmaciso` locally without GitHub Actions --- .github/workflows/build-recovery.yml | 37 +- .github/workflows/build.yml | 276 +----- README.md | 34 +- mkmaciso | 1271 ++++++++++++++++++++++++++ 4 files changed, 1347 insertions(+), 271 deletions(-) create mode 100644 mkmaciso diff --git a/.github/workflows/build-recovery.yml b/.github/workflows/build-recovery.yml index 5732c76..1a29fa3 100644 --- a/.github/workflows/build-recovery.yml +++ b/.github/workflows/build-recovery.yml @@ -17,12 +17,6 @@ on: - 'Catalina' - 'Mojave' - 'High Sierra' - - 'Sierra' - - 'El Capitan' - - 'Yosemite' - - 'Mavericks' - - 'Mountain Lion' - - 'Lion' release_tag: description: 'Optional: tag the build (e.g., v10.15) to upload it to Releases for long-term storage' required: false @@ -31,7 +25,9 @@ on: jobs: build-recovery-iso: runs-on: macos-latest - timeout-minutes: 10 + permissions: + contents: write # needed to create releases + timeout-minutes: 15 steps: - name: Checkout repository @@ -49,7 +45,7 @@ jobs: - name: Download macrecovery.py run: | echo "Downloading macrecovery.py from acidanthera/OpenCorePkg..." - curl -sL "https://raw.githubusercontent.com/acidanthera/OpenCorePkg/master/Utilities/macrecovery/macrecovery.py" -o macrecovery.py + curl -OL "https://raw.githubusercontent.com/acidanthera/OpenCorePkg/master/Utilities/macrecovery/macrecovery.py" - name: Get version info id: version_info @@ -193,15 +189,27 @@ jobs: name: macOS-${{ steps.version_info.outputs.version_name }}-Recovery-ISO path: ${{ steps.compress_iso.outputs.compressed_file }} compression-level: 0 - retention-days: 5 + retention-days: 7 + + - name: Sanitize release tag + id: sanitize_tag + if: github.event.inputs.release_tag != '' + run: | + tag="${{ github.event.inputs.release_tag }}" + + # Replace spaces and other invalid characters with hyphens + # Keep only alphanumeric, dots, hyphens, and underscores + sanitized_tag=$(echo "$tag" | sed 's/[^a-zA-Z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//') + echo "sanitized_tag=$sanitized_tag" >> $GITHUB_OUTPUT - name: Create Release if: github.event.inputs.release_tag != '' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + continue-on-error: true run: | title="macOS ${{ steps.version_info.outputs.version_name }} Recovery" - tag=${{ github.event.inputs.release_tag }} + tag="${{ steps.sanitize_tag.outputs.sanitized_tag }}" gh release create $tag \ --title "$title" \ @@ -210,8 +218,9 @@ jobs: - name: Summary run: | echo "## Successfully built **macOS ${{ steps.version_info.outputs.version_name }} Recovery** ISO" >> $GITHUB_STEP_SUMMARY - echo "Note: This ISO is intended for creating macOS virtual machine in Proxmox VE, QEMU, VMware, and VirtualBox." >> $GITHUB_STEP_SUMMARY + echo "Note: This ISO is intended for create macOS virtual machine on Proxmox VE, QEMU, VMware, and VirtualBox." >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "If this tool helped you, please consider [giving it a star ⭐](https://github.com/LongQT-sea/macos-iso-builder)" >> $GITHUB_STEP_SUMMARY - echo "> [!Tip]" >> $GITHUB_STEP_SUMMARY - echo "> Enable [Cloudflare WARP](https://one.one.one.one/) for faster downloads." >> $GITHUB_STEP_SUMMARY \ No newline at end of file + echo "Found this useful? Give it a ⭐ star so others can find it too! https://github.com/LongQT-sea/macos-iso-builder" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "> [!TIP]" >> $GITHUB_STEP_SUMMARY + echo "> Enable [Cloudflare WARP](https://one.one.one.one/) for faster downloads." >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 410d866..10ee33f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,6 +17,12 @@ on: - 'Catalina' - 'Mojave' - 'High Sierra' + - 'Sierra' + - 'El Capitan' + - 'Yosemite' + - 'Mavericks' + - 'Mountain Lion' + - 'Lion' image_format: description: 'Select image format: iso for virtual machines, dmg for burning to USB drive' required: true @@ -28,8 +34,8 @@ on: jobs: build-installer: runs-on: macos-15-intel - timeout-minutes: 120 - + timeout-minutes: 70 + steps: - name: Checkout repository uses: actions/checkout@v5 @@ -43,262 +49,48 @@ jobs: echo "Memory:" top -l 1 | grep PhysMem - - name: Fetch available macOS installers - id: fetch_installers + - name: Create Image + id: create_image run: | - echo "Fetching available installers..." - softwareupdate --list-full-installers 2>/dev/null | grep "* Title:" | sed 's/^[[:space:]]*//' > installers.txt - cat installers.txt - - # Get latest version for selected macOS - INSTALLER_VERSION=$(grep "${{ github.event.inputs.macos_version }}" installers.txt | head -1 | sed -n 's/.*Version: \([^,]*\).*/\1/p') - echo "Found latest ${{ github.event.inputs.macos_version }} version: $INSTALLER_VERSION" - echo "version=$INSTALLER_VERSION" >> $GITHUB_OUTPUT - - - name: Download macOS installer - id: download_installer - # Download should finish within 60 minutes. If it takes longer, rerun to try another runner. - timeout-minutes: 60 - continue-on-error: true - run: | - echo "Downloading macOS ${{ github.event.inputs.macos_version }} version ${{ steps.fetch_installers.outputs.version }}" - - # Download with retries - RETRIES_COUNT=3 - - for attempt in $(seq 1 $RETRIES_COUNT); do - echo "Download attempt $attempt of $RETRIES_COUNT..." - if softwareupdate --fetch-full-installer --full-installer-version "${{ steps.fetch_installers.outputs.version }}"; then - echo "Download successful!" - echo "download_success=true" >> $GITHUB_OUTPUT - break - fi - if [ $attempt -eq $RETRIES_COUNT ]; then - echo "Download failed after $RETRIES_COUNT attempts" - echo "download_success=false" >> $GITHUB_OUTPUT - exit 1 - fi - echo "Retrying in 5s..." - sleep 5 - done - - - name: Check download status - if: always() - run: | - if [ "${{ steps.download_installer.outcome }}" == "failure" ] || [ "${{ steps.download_installer.outcome }}" == "cancelled" ]; then - echo "download_failed=true" >> $GITHUB_ENV - elif [ "${{ steps.download_installer.outputs.download_success }}" != "true" ]; then - echo "download_failed=true" >> $GITHUB_ENV + if [ "${{ github.event.inputs.image_format }}" == "iso" ]; then + echo "Creating macOS ${{ github.event.inputs.macos_version }} ISO image" + bash mkmaciso "${{ github.event.inputs.macos_version }}" + echo "image_name=$(basename *.iso)" >> $GITHUB_OUTPUT else - echo "download_failed=false" >> $GITHUB_ENV - fi - - - name: Create ISO - if: github.event.inputs.image_format == 'iso' - id: create_iso - run: | - echo "Creating ISO for macOS ${{ github.event.inputs.macos_version }}" - - # Set variables - ISO_NAME="macOS_${{ github.event.inputs.macos_version }}_${{ steps.fetch_installers.outputs.version }}" - ISO_NAME="${ISO_NAME// /_}" - SPARSE_IMAGE="/tmp/${ISO_NAME}.sparseimage" - ISO_FILE="${GITHUB_WORKSPACE}/${ISO_NAME}.iso" - VOLUME_NAME="myvolume" - INSTALLER_PATH="/Applications/Install macOS ${{ github.event.inputs.macos_version }}.app" - RETRIES_COUNT=10 - - echo "ISO will be created at: $ISO_FILE" - echo "Using installer at: $INSTALLER_PATH" - - # Create sparse image - echo "Creating sparse image..." - hdiutil create -size 20g -volname "$VOLUME_NAME" -fs HFS+ -type SPARSE -attach "$SPARSE_IMAGE" - - # Get the disk identifier - DISK_ID=$(diskutil list | grep "$VOLUME_NAME" | head -1 | awk '{print $NF}' | sed 's/s[0-9]*$//') - - # Create install media - echo "Creating install media..." - sudo "$INSTALLER_PATH/Contents/Resources/createinstallmedia" --volume "/Volumes/$VOLUME_NAME" --nointeraction - - # Should wait for a few seconds - sync && sleep 5 - - # Detach disk - echo "Detaching $DISK_ID ..." - for attempt in $(seq 1 $RETRIES_COUNT); do - echo "Detach attempt $attempt of $RETRIES_COUNT..." - if hdiutil detach "$DISK_ID" || hdiutil detach "$DISK_ID" -force; then - echo "Disk detached successfully." - break - fi - if [ $attempt -lt $RETRIES_COUNT ]; then - echo "Detach failed, retrying..." - sync && sleep 5 - fi - done - - # Create hybrid ISO - hdiutil makehybrid -hfs -udf -o "$ISO_FILE" "$SPARSE_IMAGE" - - # Show ISO info and set output - if [ -f "$ISO_FILE" ]; then - ISO_SIZE=$(du -h "$ISO_FILE" | cut -f1) - echo "" - echo "=========================================" - echo "ISO created successfully!" - echo "ISO size: $ISO_SIZE" - echo "=========================================" - echo "" - echo "image_file=$ISO_FILE" >> $GITHUB_OUTPUT - echo "image_name=${ISO_NAME}.iso" >> $GITHUB_OUTPUT - else - echo "Error: ISO file not created" - exit 1 - fi - - - name: Create DMG - if: github.event.inputs.image_format == 'dmg' - id: create_dmg - run: | - echo "Creating macOS ${{ github.event.inputs.macos_version }} DMG image" - - # Set variables - DMG_NAME="macOS_${{ github.event.inputs.macos_version }}_${{ steps.fetch_installers.outputs.version }}" - DMG_NAME="${DMG_NAME// /_}" - DMG_FILE="${GITHUB_WORKSPACE}/${DMG_NAME}.dmg" - VOLUME_NAME="myvolume" - INSTALLER_PATH="/Applications/Install macOS ${{ github.event.inputs.macos_version }}.app" - RETRIES_COUNT=10 - - echo "DMG will be created at: $DMG_FILE" - echo "Using installer at: $INSTALLER_PATH" - - # Step 1: Create a 20GB disk image and attach it - echo "Step 1: Creating 20GB DMG disk image..." - hdiutil create -size 20g -volname "$VOLUME_NAME" -fs HFS+ -type UDIF -attach "$DMG_FILE" - - # Get the disk identifier - DISK_ID=$(diskutil list | grep "$VOLUME_NAME" | head -1 | awk '{print $NF}' | sed 's/s[0-9]*$//') - - # Step 2: Create install media - echo "Step 2: Creating install media ..." - sudo "$INSTALLER_PATH/Contents/Resources/createinstallmedia" --volume "/Volumes/$VOLUME_NAME" --nointeraction - - sync && sleep 5 - - # Step 3: Check minimum size requirements - echo "Step 3: Check minimum size requirements..." - INSTALLER_PARTITION="${DISK_ID}s2" - diskutil resizeVolume "$INSTALLER_PARTITION" limits | tee resize_limits.txt - - # Extract the byte value from parentheses - MIN_SIZE=$(grep "Minimum (constrained by file usage)" resize_limits.txt | sed -n 's/.*(\([0-9]*\) Bytes).*/\1/p') - echo "Minimum size: $MIN_SIZE bytes" - - # Step 4: Consolidate the installer data partition by shrinking the macOS installer partition to the minimum size. - echo "Step 4: Resizing and consolidating data..." - diskutil resizeVolume "$INSTALLER_PARTITION" "${MIN_SIZE}B" free free 0 - - sync && sleep 5 - - # Step 5: Expand installer partition back - echo "Step 5: Expanding installer partition back..." - for attempt in $(seq 1 $RETRIES_COUNT); do - echo "Resize attempt $attempt of $RETRIES_COUNT..." - if diskutil resizeVolume "$INSTALLER_PARTITION" 0; then - echo "Partition resized successfully." - break - fi - if [ $attempt -lt $RETRIES_COUNT ]; then - echo "Resize failed, retrying..." - sync && sleep 5 - fi - done - - sync && sleep 5 - - # Step 6: Detach the disk - echo "Step 6: Detaching disk..." - for attempt in $(seq 1 $RETRIES_COUNT); do - echo "Detach attempt $attempt of $RETRIES_COUNT..." - if hdiutil detach "$DISK_ID" || hdiutil detach "$DISK_ID" -force; then - echo "Disk detached successfully." - break - fi - if [ $attempt -lt $RETRIES_COUNT ]; then - echo "Detach failed, retrying..." - sync && sleep 5 - fi - done - - sleep 2 - - # Step 7: Optimize DMG size - echo "Step 7: Optimizing DMG size..." - hdiutil resize -size min "$DMG_FILE" - - # Show final DMG info - if [ -f "$DMG_FILE" ]; then - DMG_SIZE=$(du -h "$DMG_FILE" | cut -f1) - echo "" - echo "=========================================" - echo "Optimized DMG created successfully!" - echo "DMG size: $DMG_SIZE" - echo "=========================================" - echo "" - echo "image_file=$DMG_FILE" >> $GITHUB_OUTPUT - echo "image_name=${DMG_NAME}.dmg" >> $GITHUB_OUTPUT - else - echo "Error: DMG file not created" - exit 1 + echo "Creating macOS ${{ github.event.inputs.macos_version }} DMG image" + bash mkmaciso "${{ github.event.inputs.macos_version }}" dmg + echo "image_name=$(basename *.dmg)" >> $GITHUB_OUTPUT fi - name: Upload ISO artifact if: github.event.inputs.image_format == 'iso' uses: actions/upload-artifact@v5 with: - name: macOS-${{ github.event.inputs.macos_version }}-${{ steps.fetch_installers.outputs.version }}-ISO - path: ${{ steps.create_iso.outputs.image_file }} + name: ${{ steps.create_image.outputs.image_name }} + path: ./*.iso compression-level: 0 - retention-days: 5 + retention-days: 7 - name: Upload DMG artifact if: github.event.inputs.image_format == 'dmg' uses: actions/upload-artifact@v5 with: - name: macOS-${{ github.event.inputs.macos_version }}-${{ steps.fetch_installers.outputs.version }}-DMG - path: ${{ steps.create_dmg.outputs.image_file }} + name: ${{ steps.create_image.outputs.image_name }} + path: ./*.dmg compression-level: 0 - retention-days: 5 + retention-days: 7 - name: Summary - if: always() run: | - if [ "${{ env.download_failed }}" == "true" ]; then - echo "## Download macOS Failed" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "> [!WARNING]" >> $GITHUB_STEP_SUMMARY - echo "> This runner may have network issues. Please **re-run the workflow** to try a different runner." >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "> [!TIP]" >> $GITHUB_STEP_SUMMARY - echo "> - Running during off-peak hours" >> $GITHUB_STEP_SUMMARY - echo "> - Selecting a different macOS version" >> $GITHUB_STEP_SUMMARY - echo "> - Or build Recovery ISO instead" >> $GITHUB_STEP_SUMMARY - elif [ "${{ job.status }}" == "success" ]; then - if [ "${{ github.event.inputs.image_format }}" == "iso" ]; then - echo "## Successfully built macOS ${{ github.event.inputs.macos_version }} ${{ steps.fetch_installers.outputs.version }} ISO" >> $GITHUB_STEP_SUMMARY - echo "Note: This ISO is intended for creating macOS virtual machine in Proxmox VE, QEMU, VMware, and VirtualBox." >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "If this tool helped you, please consider [giving it a star ⭐](https://github.com/LongQT-sea/macos-iso-builder)" >> $GITHUB_STEP_SUMMARY - else - echo "## Successfully built macOS ${{ github.event.inputs.macos_version }} ${{ steps.fetch_installers.outputs.version }} DMG" >> $GITHUB_STEP_SUMMARY - echo 'Note: This DMG is intended for create bootable installer USB drive on Windows with [Rufus](https://rufus.ie/en/#download) or on Linux with `dd`' >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "If this tool helped you, please consider [giving it a star ⭐](https://github.com/LongQT-sea/macos-iso-builder)" >> $GITHUB_STEP_SUMMARY - fi - echo "" >> $GITHUB_STEP_SUMMARY - echo "> [!TIP]" >> $GITHUB_STEP_SUMMARY - echo "> Enable [Cloudflare WARP](https://one.one.one.one/) for faster downloads." >> $GITHUB_STEP_SUMMARY + if [ "${{ github.event.inputs.image_format }}" == "iso" ]; then + echo "## Successfully built $(basename *.iso)" >> $GITHUB_STEP_SUMMARY + echo "Note: This ISO is intended for create macOS virtual machine on Proxmox VE, QEMU, VMware, and VirtualBox." >> $GITHUB_STEP_SUMMARY + else + echo "## Successfully built $(basename *.dmg)" >> $GITHUB_STEP_SUMMARY + echo 'Note: This DMG is intended for flash to USB drive using [Rufus](https://rufus.ie/en/#download) (Windows) or dd (Linux)' >> $GITHUB_STEP_SUMMARY fi + echo "" >> $GITHUB_STEP_SUMMARY + echo "Found this useful? Give it a ⭐ star so others can find it too! https://github.com/LongQT-sea/macos-iso-builder" >> $GITHUB_STEP_SUMMARY + echo "" >> $GITHUB_STEP_SUMMARY + echo "> [!TIP]" >> $GITHUB_STEP_SUMMARY + echo "> Enable [Cloudflare WARP](https://one.one.one.one/) for faster downloads." >> $GITHUB_STEP_SUMMARY diff --git a/README.md b/README.md index 7bd9224..01f5122 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,24 @@ -## macOS Installer Image Builder – No Mac Required +## Build macOS Installer ISO and DMG image via Github Action – No Mac Required -* Generate bootable macOS installer images directly from Apple's servers via GitHub Actions. +* Support **macOS 10.7 Lion** through **macOS 26 Tahoe** installers. +* Download macOS installers exclusively from official Apple sources. * Includes intelligent file size optimization to produce the smallest possible installer images. **Supported formats:** -* **ISO** – True DVD format compatible with **Proxmox VE**, **QEMU**, **VirtualBox**, and **VMware** -* **DMG** – Create bootable macOS installer USB drives on Windows with [Rufus](https://rufus.ie/en/#download) or on Linux with **`dd`** +* **ISO** – True DVD/CD format compatible with **Proxmox VE**, **QEMU**, **VirtualBox**, and **VMware** +* **DMG** – For create bootable macOS installer USB drives on Windows with [Rufus](https://rufus.ie/en/#download) or on Linux with **`dd`** **Available workflows:** -* **macOS Recovery ISO (Recommended)** – Lightweight recovery image (build takes ~2-5 min) • Best for virtualization -* **macOS Full Installer** – Complete offline installer (build takes ~20-60 min, 5-18GB) • Best for offline use +* **Recovery ISO (Recommended)** – Lightweight recovery image (build takes ~2-5 min) • Best for virtualization +* **Full Installer** – Complete offline installer (build takes ~10-60 min, 5-18GB) • Best for offline use > [!IMPORTANT] > * Use the **"Build macOS Recovery ISO image"** workflow unless you really need an offline installer. > * GitHub-hosted runners are a free public resource — please use them responsibly. -> * Already have a macOS VM? Build macOS Installer ISO inside your VM with [Create_macOS_ISO.command](https://github.com/LongQT-sea/OpenCore-ISO/blob/main/Create_macOS_ISO.command) +> * Already have macOS? Build macOS installer ISO/DMG image with this command (replace tahoe with the desired version): +> ``` +> curl -L https://raw.githubusercontent.com/LongQT-sea/macos-iso-builder/main/mkmaciso | bash -s tahoe +> ``` --- @@ -22,17 +26,17 @@ 1. **Fork** this repository. 2. Go to the **Actions** tab in your forked repository. -3. Click the green **"I understand my workflows, go ahead and enable them"** button. -4. Select the **"Build macOS Installer ISO/DMG image"** or **"Build macOS Recovery ISO image"** workflow. +3. Click the green button **"I understand my workflows, go ahead and enable them"**. +4. Select the **"Build macOS Installer ISO/DMG image"** or **"Build macOS Recovery ISO image"** workflow from the left sidebar.. 5. Click the **"Run workflow"** button. 6. Configure the workflow inputs: * **macOS version** – Choose a version (*Sequoia*, *Sonoma*, etc.). * **Image format** – Choose `iso` for virtual machines or `dmg` for bootable USB drives. 7. Click the green **"Run workflow"** button to start the build. -8. Wait for the workflow to complete (this may take 20-60 minutes). +8. Wait for the workflow to complete (this may take 10-60 minutes). 9. Open the completed workflow run and scroll to the **Artifacts** section. -10. Download the artifact (e.g., `macOS-Sequoia-15.7.2-ISO`). +10. Download the artifact (e.g., `macOS_Sequoia_15.7.3.iso`). > [!TIP] > Enable [Cloudflare WARP](https://one.one.one.one/) for faster downloads. 11. Extract the ZIP file to get your `.iso` or `.dmg` file. @@ -42,12 +46,12 @@ > [!TIP] > To create a bootable macOS installer USB drive on Windows: > 1. Open [Rufus](https://rufus.ie/en/#download) -> 2. Click **SELECT**, change the filter to **"All files"**, then select your `.dmg` +> 2. Click **SELECT**, change the filter to **"All files"**, then select your macOS `.dmg` > 3. Click **START** -> 4. Optional: After flashing the `dmg` image to the USB drive with Rufus, there will be free/unallocated space remaining on the USB drive. Use Disk Management to create a new FAT32 partition and place your EFI there if needed. +> 4. Optional: After flashing the `dmg` image to the USB drive, there will be free/unallocated space remaining on the USB drive. Use Disk Management to create a new FAT32 partition and place your EFI folder there if needed. > [!NOTE] -> By default, artifacts are kept for 5 days. You can change this in the workflow YAML file. +> By default, artifacts are kept for 7 days. You can change this in the workflow YAML file. > [!TIP] > * For best performance, use a macOS VM on **Proxmox VE** with iGPU or dGPU passthrough. @@ -57,4 +61,4 @@ --- ## Legal Notice -This tool downloads macOS images directly from Apple's servers. Users are responsible for complying with Apple's Software License Agreement. \ No newline at end of file +This tool downloads macOS images directly from Apple's servers. Users are responsible for complying with Apple's Software License Agreement. diff --git a/mkmaciso b/mkmaciso new file mode 100644 index 0000000..780ee80 --- /dev/null +++ b/mkmaciso @@ -0,0 +1,1271 @@ +#!/usr/bin/env bash +# Copyright (c) 2024–2025, LongQT-sea + +# mkmaciso - the ultimate macOS utility for creating macOS installer ISO and DMG images + +# Run with -h or --help to show usage. + +# Goals: +# - Use only macOS built-in tools and commands. +# - Download macOS installers exclusively from official Apple sources. +# - Support macOS 10.7 Lion through macOS 26 Tahoe installers. +# - Produce the smallest possible installer images for both formats. +# - The image must be usable on Windows and Linux. +# +# ISO image: +# - A proper UDF DVD/CD format image (mountable in Windows). +# - Intended for virtual machine use; attach as a virtual CD/DVD drive. +# - Compatible with Proxmox VE, QEMU, VirtualBox, and VMware. +# +# DMG image: +# - Raw disk image with GUID Partition Table, this is mandatory so it can be flash to a USB drive using Rufus (Windows). +# - Can also be used with virtual machines, but must be attached as a virtual hard disk. +# - Most VMM require convert the .dmg image to a compatible virtual disk format using qemu-img, +# e.g. convert to .vhd for Hyper-V or .vmdk for VMware. QEMU can use raw disk image without conversion. + +set -e # Exit on error + +# Official Apple download URLs for macOS 10.7-10.12 (except 10.9) +# https://support.apple.com/en-hk/102662#browser +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" + +# Default parameters +VERSION="${1:-}" +IMAGE_FORMAT="${2:-}" +OUTPUT_PATH="${3:-}" +RETRIES_COUNT=10 +FINAL_OUTPUT_PATH="" + +# Color codes for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +CYAN='\033[0;36m' +BOLD='\033[1m' +NC='\033[0m' # No Color + +# Helper functions +log_info() { + echo -e "${GREEN}[INFO]${NC} $1" +} + +log_warn() { + echo -e "${YELLOW}[WARN]${NC} $1" +} + +log_error() { + echo -e "${RED}[ERROR]${NC} $1" +} + +check_sudo_access() { + if ! sudo -v; then + log_error "This script requires administrator privileges" + exit 1 + fi + + # Keep sudo alive + while true; do sudo -n true; sleep 60; kill -0 "$$" || exit; done 2>/dev/null & +} + +check_disk_space() { + local required_gb=40 + local available=$(df -g . | awk 'NR==2 {print $4}') + + if [ "$available" -lt "$required_gb" ]; then + log_error "WARNING: Low disk space - ${available} GB available, ${required_gb} GB or more recommended" + log_warn "" + log_warn "Continue? (Y/n - auto-yes in 10 seconds): " + read -t 10 answer || answer="y" + case "$answer" in + [Nn]|[Nn][Oo]) + log_error "Aborted" + exit 1 + ;; + *) + log_info "Continuing..." + ;; + esac + 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 hdiutil detach "$disk" 2>/dev/null || hdiutil detach "$disk" -force 2>/dev/null; then + log_info "Disk detached successfully" + return 0 + fi + [ "$attempt" -lt "$RETRIES_COUNT" ] && log_warn "Detach failed, retrying..." + sleep 2 + done + + log_error "Failed to detach $disk after $RETRIES_COUNT attempts" + return 1 +} + +cleanup() { + # Only clean up if WORK_DIR is defined and not root/home + if [ -n "$WORK_DIR" ] && [ "$WORK_DIR" != "/" ] && [ -d "$WORK_DIR" ]; then + if [ -n "$DISK_ID" ]; then + detach_disk "$DISK_ID" + fi + log_info "Cleaning up temporary files..." + sudo rm -rf "$WORK_DIR" + fi +} + +trap cleanup EXIT + +# Version lookup functions +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 version_num="$1" + + case "$version_num" 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 +} + +# ========================== +# Interactive Menu Functions +# ========================== + +print_header() { + clear + echo -e "${BOLD}${CYAN}" + echo "╔══════════════════════════════════════════════════════════════════════════════════════╗" + echo "║ mkmaciso - the ultimate macOS utility for creating macOS installer ISO and DMG images║" + echo "║══════════════════════════════════════════════════════════════════════════════════════║" + echo "║ Interactive mode ║" + echo "╚══════════════════════════════════════════════════════════════════════════════════════╝" + echo -e "${NC}" +} + +print_separator() { + echo -e "${CYAN}──────────────────────────────────────────────────────────────────────${NC}" +} + +# Array of macOS versions for the menu +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" +) + +show_version_menu() { + print_header + echo -e "${BOLD}Step 1/3: Select macOS Version${NC}" + print_separator + echo "" + + local i=1 + local col=0 + + # Print versions in two columns + 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/dev/null | od -An -tx1 | tr -d ' \n' | tr '[:lower:]' '[:upper:]') + + # Create key_info file + { + 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" + + # Generate key + local key=$(openssl dgst -sha256 -binary < "$WORK_DIR/key_info" | od -An -tx1 | tr -d ' \n' | tr '[:lower:]' '[:upper:]') + rm "$WORK_DIR/key_info" + + # Get installation payload + 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") + + # Extract asset URL and token + 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 "Mavericks URL detected: $mavericks_url" + echo "" + log_info "Downloading macOS Mavericks using special method..." + + # Download Mavericks InstallESD.dmg and cache it in /Applications to avoid redownload in the future + curl --progress-bar "$mavericks_url" -H "Cookie: AssetToken=$token" > "$WORK_DIR/InstallESD.dmg" && mkdir -p "/Applications/Install OS X Mavericks.app/Contents/SharedSupport" + + if [ -d "/Applications/Install OS X Mavericks.app/Contents/SharedSupport" ]; then + mv -f "$WORK_DIR/InstallESD.dmg" "/Applications/Install OS X Mavericks.app/Contents/SharedSupport/InstallESD.dmg" + fi +} + +install_legacy_app() { + local version_num="$1" + local dmg_file="$2" + + log_info "Installing macOS $(get_codename $version_num) installer to /Applications..." + + # Mount the downloaded DMG + hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/installer_mnt" "$dmg_file" + + # Install the package + sudo installer -pkg "$WORK_DIR/installer_mnt"/*.pkg -target / + + # Unmount + sync && detach_disk "$WORK_DIR/installer_mnt" +} + +download_modern_macos() { + local version_num="$1" + version_name=$(get_codename $version_num) + version_name="${version_name/_/ }" + + # Get CPU architecture + local cpu_arch=$(uname -m) + + # Get current macOS kernel version + local kernel_version=$(uname -r | cut -d'.' -f1) + + # Convert kernel version to macOS version number + local current_macos_version="" + case "$kernel_version" in + 8) current_macos_version="10.4" ;; + 9) current_macos_version="10.5" ;; + 10) current_macos_version="10.6" ;; + 11) current_macos_version="10.7" ;; + 12) current_macos_version="10.8" ;; + 13) current_macos_version="10.9" ;; + 14) current_macos_version="10.10" ;; + 15) current_macos_version="10.11" ;; + 16) current_macos_version="10.12" ;; + 17) current_macos_version="10.13" ;; + 18) current_macos_version="10.14" ;; + 19) current_macos_version="10.15" ;; + 20) current_macos_version="11" ;; + 21) current_macos_version="12" ;; + 22) current_macos_version="13" ;; + 23) current_macos_version="14" ;; + 24) current_macos_version="15" ;; + 25) current_macos_version="26" ;; + 27) current_macos_version="27" ;; + *) current_macos_version="unknown" ;; + esac + + current_macos_codename=$(get_codename $current_macos_version) + + log_info "Current macOS version: ${CYAN}$current_macos_codename ${NC}" + + # Extract major version from version_num for comparison + local requested_major_version + if [[ "$version_num" =~ ^10\.([0-9]+)$ ]]; then + requested_major_version="${version_num}" + else + requested_major_version="$version_num" + fi + + # Check CPU architecture compatibility + if [ "$cpu_arch" == "x86_64" ]; then + log_info "Intel CPU detected" + + # Intel Macs require macOS 11 or newer for softwareupdate + # Check if current system is at least macOS 11 (kernel 20) + if [ "$kernel_version" -lt 20 ]; then + log_error "Intel Macs must be running macOS 11 (Big Sur) or newer to download macOS using softwareupdate" + log_error "Current macOS version: $current_macos_codename" + log_error "Please upgrade your macOS to version 11 or newer" + return 1 + fi + + elif [ "$cpu_arch" == "arm64" ]; then + log_info "Apple Silicon detected" + + # Check if requested version is older than macOS 11 + if [[ "$version_num" =~ ^10\. ]]; then + log_error "Apple Silicon Macs cannot download macOS versions older than 11 (Big Sur)" + log_error "Requested version: $version_name" + log_error "Please request macOS 11 or newer" + return 1 + fi + + # For macOS 11 or newer on Apple silicon, show warning + log_warn "╔════════════════════════════════════════════════════════════════════╗" + log_warn "║ Apple Silicon Limitation ║" + log_warn "╠════════════════════════════════════════════════════════════════════╣" + log_warn "║ On Apple Silicon, softwareupdate cannot download macOS versions ║" + log_warn "║ older than the one that originally shipped with your device. ║" + log_warn "╚════════════════════════════════════════════════════════════════════╝" + else + log_error "Unknown CPU architecture: $cpu_arch" + return 1 + fi + + log_info "Fetching available macOS installers..." + softwareupdate --list-full-installers 2>/dev/null | grep "* Title:" | sed 's/^[[:space:]]*//' > $WORK_DIR/installers.txt + + if [ ! -s $WORK_DIR/installers.txt ]; then + log_error "Failed to fetch installer list" + log_error "This feature requires macOS Big Sur or newer" + return 1 + fi + + # Get latest installer version + 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 ($version_num) is not available for download on this system" + log_info "Available installers:" + cat "$WORK_DIR/installers.txt" + return 1 + fi + + log_info "Found latest $version_name version: $selected_version_number" + log_info "Downloading and installing macOS $version_name installer (this may take a while)..." + + # Download with retries (max 4 times) + local download_retries=4 + for attempt in $(seq 1 $download_retries); do + log_info "Download attempt $attempt of $download_retries..." + if softwareupdate --fetch-full-installer --full-installer-version "$selected_version_number"; then + log_info "Download successful!" + return 0 + fi + if [ $attempt -eq $download_retries ]; then + log_error "Download failed after $download_retries attempts" + return 1 + fi + log_warn "Retrying in 5 seconds..." + sleep 5 + done +} + +create_iso_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) ISO image..." + echo "" + + # Mount InstallESD.dmg for version extraction + hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" "$installer_path/Contents/SharedSupport/InstallESD.dmg" + + # Extract the exact version number and append it to the file name + exact_version_number=$(defaults read "$WORK_DIR/InstallESD_mnt/System/Library/CoreServices/SystemVersion" ProductVersion) + FINAL_OUTPUT_PATH="${output_file%.iso}_$exact_version_number.iso" + + # Unmount + sync && detach_disk "$WORK_DIR/InstallESD_mnt" + + # Create ISO directly from InstallESD.dmg + sudo hdiutil makehybrid -ov -hfs -udf -default-volume-name "$volume_name" \ + "$installer_path/Contents/SharedSupport/InstallESD.dmg" -o "$FINAL_OUTPUT_PATH" +} + +create_dmg_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) DMG image..." + echo "" + + # Mount InstallESD.dmg + hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" "$installer_path/Contents/SharedSupport/InstallESD.dmg" + + # Extract the exact version number and append it to the file name + exact_version_number=$(defaults read "$WORK_DIR/InstallESD_mnt/System/Library/CoreServices/SystemVersion" ProductVersion) + FINAL_OUTPUT_PATH="${output_file%.dmg}_$exact_version_number.dmg" + + # Create DMG with GUID Partition Table from mounted InstallESD.dmg + sudo hdiutil create -layout GPTSPUD -format UDRW -ov \ + -volname "$volume_name" -srcdir "$WORK_DIR/InstallESD_mnt" "$FINAL_OUTPUT_PATH" + + # Unmount + sync && detach_disk "$WORK_DIR/InstallESD_mnt" +} + +create_iso_10_9_10_11() { + local installer_path="$1" + local output_file="$2" + local volume_name="$3" + local version_num="$4" + + log_info "Creating macOS $(get_codename $version_num) ISO image..." + echo "" + + # Mount InstallESD.dmg + local installesd_path="$installer_path/Contents/SharedSupport/InstallESD.dmg" + + hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" "$installesd_path" + + # Convert BaseSystem.dmg + hdiutil convert "$WORK_DIR/InstallESD_mnt/BaseSystem.dmg" -format UDRW -o "$WORK_DIR/BaseSystem" >/dev/null 2>&1 + + # Resize + sudo hdiutil resize -size 8g "$WORK_DIR/BaseSystem.dmg" + + # Mount the converted DMG + DISK_ID=$(hdiutil attach -nobrowse -mountpoint "$WORK_DIR/BaseSystem_mnt" "$WORK_DIR/BaseSystem.dmg" | grep -o '/dev/disk[0-9]*' | head -1) + + # Remove Packages symlink and copy actual Packages + rm "$WORK_DIR/BaseSystem_mnt/System/Installation/Packages" + cp -R "$WORK_DIR/InstallESD_mnt/Packages" "$WORK_DIR/BaseSystem_mnt/System/Installation/" + + # Copy required files + cp "$WORK_DIR/InstallESD_mnt/BaseSystem.dmg" "$WORK_DIR/BaseSystem_mnt/" + cp "$WORK_DIR/InstallESD_mnt/BaseSystem.chunklist" "$WORK_DIR/BaseSystem_mnt/" + + # Note: For Mavericks UDF format, boot.efi attempts to load /mach_kernel, but none exists. + # Although we can extract it from Packages/BaseSystemBinaries.pkg, there's a simpler solution: + if [ "$version_num" == "10.9" ]; then + cp "$WORK_DIR/BaseSystem_mnt/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache" "$WORK_DIR/BaseSystem_mnt/mach_kernel" + fi + + # Extract the exact version number and append it to the file name + exact_version_number=$(defaults read "$WORK_DIR/BaseSystem_mnt/System/Library/CoreServices/SystemVersion" ProductVersion) + FINAL_OUTPUT_PATH="${output_file%.iso}_$exact_version_number.iso" + + # Unmount + detach_disk "$WORK_DIR/InstallESD_mnt" + detach_disk "$DISK_ID" && DISK_ID="" + + # Create ISO + sudo hdiutil makehybrid -ov -hfs -udf -default-volume-name "$volume_name" \ + "$WORK_DIR/BaseSystem.dmg" -o "$FINAL_OUTPUT_PATH" +} + +create_dmg_10_9() { + local installer_path="$1" + local output_file="$2" + local volume_name="$3" + local version_num="$4" + + log_info "Creating macOS $(get_codename $version_num) DMG image..." + echo "" + + # Mount InstallESD.dmg + local installesd_path="$installer_path/Contents/SharedSupport/InstallESD.dmg" + + hdiutil attach -nobrowse -quiet -mountpoint "$WORK_DIR/InstallESD_mnt" "$installesd_path" + + # Attach BaseSystem.dmg + BaseSystem_DISK_ID=$(hdiutil attach "$WORK_DIR/InstallESD_mnt/BaseSystem.dmg" -nomount | grep -o '/dev/disk[0-9]*' | head -1) + + # Create a DMG with GUID Partition Table and attach it + hdiutil create -ov -fs hfs+ -size 1.4g "$WORK_DIR/installer_gpt.dmg" >/dev/null 2>&1 + DISK_ID=$(hdiutil attach "$WORK_DIR/installer_gpt.dmg" -nomount | grep -o '/dev/disk[0-9]*' | head -1) + + # Write the bootable recovery partition to the first partition on the DMG image + sudo dd if="${BaseSystem_DISK_ID}s2" of="${DISK_ID}s1" bs=1m && detach_disk "$BaseSystem_DISK_ID" + + # Unmount + detach_disk "$DISK_ID" && DISK_ID="" + + # Increase size + sudo hdiutil resize -size 8g "$WORK_DIR/installer_gpt.dmg" + + # Mount DMG image and change volume name + DISK_ID=$(hdiutil attach -nobrowse -mountpoint "$WORK_DIR/installer_mnt" "$WORK_DIR/installer_gpt.dmg" | grep -o '/dev/disk[0-9]*' | head -1) + diskutil rename "${DISK_ID}s1" "$volume_name" + + # Remove Packages symlink and copy actual Packages + rm "$WORK_DIR/installer_mnt/System/Installation/Packages" + cp -R "$WORK_DIR/InstallESD_mnt/Packages" "$WORK_DIR/installer_mnt/System/Installation/" + + # Copy required files + cp "$WORK_DIR/InstallESD_mnt/BaseSystem.dmg" "$WORK_DIR/installer_mnt/" + cp "$WORK_DIR/InstallESD_mnt/BaseSystem.chunklist" "$WORK_DIR/installer_mnt/" + + # Extract the exact version number and append it to the file name + exact_version_number=$(defaults read "$WORK_DIR/installer_mnt/System/Library/CoreServices/SystemVersion" ProductVersion) + FINAL_OUTPUT_PATH="${output_file%.dmg}_$exact_version_number.dmg" + + sync && sleep 5 + + # Unmount + detach_disk "$WORK_DIR/InstallESD_mnt" + detach_disk "$DISK_ID" && DISK_ID="" + + # Optimize DMG file size + log_info "Optimizing DMG file size..." + sudo hdiutil resize -size min "$WORK_DIR/installer_gpt.dmg" + + # Move to output + mv -f "$WORK_DIR/installer_gpt.dmg" "$FINAL_OUTPUT_PATH" +} + +create_iso_10_12_and_later() { + local installer_path="$1" + local output_file="$2" + local version_num="$3" + + log_info "Creating macOS $(get_codename $version_num) ISO image..." + echo "" + + # Create sparse image + hdiutil create -size 20g -volname "$(get_codename $version_num)_iso" -fs HFS+ -type SPARSE -attach "$WORK_DIR/installer.sparseimage" >/dev/null 2>&1 + DISK_ID=$(diskutil list | grep $(get_codename $version_num)_iso | head -1 | awk '{print $NF}' | sed 's/s[0-9]*$//') + + # Prepare createinstallmedia command + local cmd="sudo '$installer_path/Contents/Resources/createinstallmedia' --volume /Volumes/$(get_codename $version_num)_iso --nointeraction" + + # For macOS 10.12, need to patch Info.plist + # For macOS 10.10-10.12, need to add --applicationpath + if [ "$version_num" == "10.12" ]; then + log_info "Patching Info.plist for Sierra compatibility..." + sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.03'" "$installer_path/Contents/Info.plist" + cmd="$cmd --applicationpath \"$installer_path\"" + fi + + # Create install media + log_info "Running createinstallmedia..." + bash -c "$cmd" + sync && sleep 5 + + # Extract the exact version number and append it to the file name + exact_version_number=$(defaults read "/Volumes/$(get_installer_app_name "$version_num")/System/Library/CoreServices/SystemVersion" ProductVersion) + FINAL_OUTPUT_PATH="${output_file%.iso}_$exact_version_number.iso" + + # Restore Info.plist + if [ "$version_num" == "10.12" ]; then + sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.06'" "/Applications/Install macOS Sierra.app/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 + + # Unmount + detach_disk "$DISK_ID" && DISK_ID="" + + # Create ISO from sparse image + log_info "Converting to ISO format..." + sudo hdiutil makehybrid -ov -hfs -udf "$WORK_DIR/installer.sparseimage" -o "$FINAL_OUTPUT_PATH" +} + +create_dmg_10_10_and_later() { + local installer_path="$1" + local output_file="$2" + local version_num="$3" + + log_info "Creating macOS $(get_codename $version_num) DMG image..." + echo "" + + # Create DMG disk image + hdiutil create -size 20g -volname "$(get_codename $version_num)_dmg" -fs HFS+ -type UDIF -attach "$WORK_DIR/installer.dmg" >/dev/null 2>&1 + DISK_ID=$(diskutil list | grep $(get_codename $version_num)_dmg | head -1 | awk '{print $NF}' | sed 's/s[0-9]*$//') + + # Prepare createinstallmedia command + local cmd="sudo '$installer_path/Contents/Resources/createinstallmedia' --volume /Volumes/$(get_codename $version_num)_dmg --nointeraction" + + # For macOS 10.12, need to patch Info.plist + # For macOS 10.10-10.12, need to add --applicationpath + case "$version_num" in + 10.10|10.11) + cmd="$cmd --applicationpath \"$installer_path\"" + ;; + 10.12) + log_info "Patching Info.plist for Sierra compatibility..." + sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.03'" "$installer_path/Contents/Info.plist" + cmd="$cmd --applicationpath \"$installer_path\"" + ;; + esac + + # Create install media + log_info "Running createinstallmedia..." + bash -c "$cmd" + sync && sleep 5 + + # Restore Info.plist on macOS 10.12 + if [ "$version_num" == "10.12" ]; then + sudo /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString '12.6.06'" "/Applications/Install macOS Sierra.app/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 + + log_info "Starting DMG file size optimization technique" + + # Check minimum size requirements + MIN_SIZE=$(diskutil resizeVolume ${DISK_ID}s2 limits | grep "Minimum (constrained by file usage)" | sed 's/.*(\([0-9]*\) Bytes)/\1/') + + # Add 50MB to $MIN_SIZE for macOS 10.10–10.11 because the installation fails when resized to the minimum size + case "$version_num" in + 10.10|10.11) + MIN_SIZE=$((MIN_SIZE + 52428800)) + ;; + esac + + # Consolidate the installer data partition by shrinking the macOS installer partition to the minimum size. + log_info "Shrinking macOS installer partition to minimum..." + diskutil resizeVolume ${DISK_ID}s2 "${MIN_SIZE}B" free free 0 >/dev/null 2>&1 + + # Expand back to consolidate + log_info "Expanding back to consolidate data ..." + for attempt in $(seq 1 $RETRIES_COUNT); do + log_info "Resize attempt $attempt of $RETRIES_COUNT..." + if diskutil resizeVolume ${DISK_ID}s2 0 >/dev/null 2>&1; then + log_info "Partition resized successfully" + break + fi + if [ $attempt -lt $RETRIES_COUNT ]; then + log_warn "Resize failed, retrying..." + sync && sleep 5 + fi + done + + # Extract the exact version number and append it to the file name + exact_version_number=$(defaults read "/Volumes/$(get_installer_app_name "$version_num")/System/Library/CoreServices/SystemVersion" ProductVersion) + FINAL_OUTPUT_PATH="${output_file%.dmg}_$exact_version_number.dmg" + + # Unmount + detach_disk "$DISK_ID" && DISK_ID="" + + # Optimize DMG file size + log_info "Final optimization..." + sudo hdiutil resize -size min "$WORK_DIR/installer.dmg" + + # Move to output + mv -f "$WORK_DIR/installer.dmg" "$FINAL_OUTPUT_PATH" +} + +# Main script +main() { + echo -e "${BOLD}${CYAN}" + echo "╔══════════════════════════════════════════════════════════════════════════════════════╗" + echo "║ mkmaciso - the ultimate macOS utility for creating macOS installer ISO and DMG images║" + echo "╚══════════════════════════════════════════════════════════════════════════════════════╝" + echo -e "${NC}" + + # Check for availble disk space + check_disk_space + + # Require sudo + check_sudo_access + + # Validate image format (default to iso if empty, fallback to dmg if invalid input) + IMAGE_FORMAT=$(echo "$IMAGE_FORMAT" | tr '[:upper:]' '[:lower:]') + if [[ -z "$IMAGE_FORMAT" ]]; then + IMAGE_FORMAT="iso" + elif [[ "$IMAGE_FORMAT" != "iso" && "$IMAGE_FORMAT" != "dmg" ]]; then + log_warn "Invalid image format '$IMAGE_FORMAT'; falling back to dmg" + IMAGE_FORMAT="dmg" + fi + + # Default VERSION to 26 (Tahoe) if empty + if [ -z "$VERSION" ]; then + VERSION="26" + fi + + # Normalize version input + VERSION=$(echo "$VERSION" | tr '[:upper:]' '[:lower:]' | tr -d '_- ') + + # Determine if input is a codename or version number + VERSION_NUM="" + VERSION_NAME="" + + # Try as version number first, then as codename + if [[ "$VERSION" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then + VERSION_NUM="$VERSION" + else + VERSION_NUM=$(get_version_number "$VERSION") + fi + + # Get proper codename (also validates the version number) + VERSION_NAME=$(get_codename "$VERSION_NUM") + + if [ -z "$VERSION_NAME" ]; then + log_info "Run with -h or --help for usage" + echo "" + log_error "Unknown macOS version: $VERSION" + log_info "Supported versions: 10.7, 10.8, 10.9, 10.10, 10.11, 10.12, 10.13, 10.14, 10.15, 11, 12, 13, 14, 15, 26" + log_info "Supported codenames: lion, mountain-lion, mavericks, yosemite, el-capitan, sierra, high-sierra, mojave, catalina, big-sur, monterey, ventura, sonoma, sequoia, tahoe" + exit 1 + fi + + log_info "Target macOS:${GREEN} $VERSION_NAME ($VERSION_NUM) ${NC}" + log_info "Image format:${GREEN} $(echo $IMAGE_FORMAT | tr '[:lower:]' '[:upper:]') ${NC}" + + # Determine output filename if not specified + if [ -z "$OUTPUT_PATH" ]; then + OUTPUT_PATH="$(pwd)/macOS_${VERSION_NAME}.${IMAGE_FORMAT}" + else + # Ensure output path has correct extension + if [[ "$OUTPUT_PATH" != *.$IMAGE_FORMAT ]]; then + OUTPUT_PATH="${OUTPUT_PATH%.*}.$IMAGE_FORMAT" + fi + # Convert to absolute path + if [[ "$OUTPUT_PATH" != /* ]]; then + # Use dirname + basename to avoid "./" in the middle + OUTPUT_PATH="$(cd "$(dirname "$OUTPUT_PATH")" && pwd)/$(basename "$OUTPUT_PATH")" + fi + fi + + log_info "Output path:${GREEN} $OUTPUT_PATH ${NC}" + echo "" + + # Check if trying to install legacy macOS on ARM64 + if [[ "$VERSION_NUM" =~ ^10\.(7|8|9|10|11|12)$ ]]; then + local cpu_arch=$(uname -m) + if [ "$cpu_arch" == "arm64" ]; then + log_error "Cannot create installer for macOS $VERSION_NUM on Apple silicon" + log_error "Legacy macOS installers (10.7-10.12) require Intel (x86_64) Macs" + log_error "Please use an Intel Mac to create installers for these versions" + exit 1 + fi + fi + + # Create work directory + WORK_DIR=$(mktemp -d) + log_info "Working directory:${CYAN} $WORK_DIR ${NC}" + echo "" + + # Check if installer already exists + INSTALLER_PATH=$(echo /Applications/$(get_installer_app_name "$VERSION_NUM").app) + + if [ "$VERSION_NUM" == "10.9" ]; then + # Mavericks special handling + if [ -d "$INSTALLER_PATH" ]; then + log_info "Found existing Mavericks installer at:${CYAN} $INSTALLER_PATH ${NC}" + echo "" + else + download_mavericks + echo "" + fi + elif [ -n "$INSTALLER_PATH" ] && [ -d "$INSTALLER_PATH" ]; then + log_info "Found existing installer at:${CYAN} $INSTALLER_PATH ${NC}" + echo "" + else + log_info "Installer not found, downloading..." + + # Download and install + if [[ "$VERSION_NUM" =~ ^10\.(7|8|10|11|12)$ ]]; then + # Legacy macOS versions (not Mavericks) + download_legacy_macos "$VERSION_NUM" + install_legacy_app "$VERSION_NUM" "$WORK_DIR/InstallMacOSX.dmg" + else + # Modern macOS (10.13 and later) + download_modern_macos "$VERSION_NUM" || exit 1 + fi + + if [ ! -d "$INSTALLER_PATH" ]; then + log_error "Failed to install macOS installer app" + exit 1 + fi + fi + + # Get volume name for the installer + VOLUME_NAME=$(get_installer_app_name "$VERSION_NUM") + + if [ "$IMAGE_FORMAT" == "iso" ]; then + case "$VERSION_NUM" in + "10.7"|"10.8") + create_iso_10_7_10_8 "$INSTALLER_PATH" "$OUTPUT_PATH" "$VOLUME_NAME" "$VERSION_NUM" ;; + "10.9"|"10.10"|"10.11") + create_iso_10_9_10_11 "$INSTALLER_PATH" "$OUTPUT_PATH" "$VOLUME_NAME" "$VERSION_NUM" ;; + *) + create_iso_10_12_and_later "$INSTALLER_PATH" "$OUTPUT_PATH" "$VERSION_NUM" ;; + esac + else + case "$VERSION_NUM" in + "10.7"|"10.8") + create_dmg_10_7_10_8 "$INSTALLER_PATH" "$OUTPUT_PATH" "$VOLUME_NAME" "$VERSION_NUM" ;; + "10.9") + create_dmg_10_9 "$INSTALLER_PATH" "$OUTPUT_PATH" "$VOLUME_NAME" "$VERSION_NUM" ;; + *) + create_dmg_10_10_and_later "$INSTALLER_PATH" "$OUTPUT_PATH" "$VERSION_NUM" ;; + esac + fi + + # Final checks + if [ -f "$FINAL_OUTPUT_PATH" ]; then + FILE_SIZE_BYTES=$(stat -f%z "$FINAL_OUTPUT_PATH") + FILE_SIZE_GB=$(du -h "$FINAL_OUTPUT_PATH" | cut -f1) + + # 4GB in bytes + MIN_SIZE=4294967296 + + if [ "$FILE_SIZE_BYTES" -lt "$MIN_SIZE" ]; then + log_error "Final image is smaller than 4GB" + log_error "The file is likely corrupted or incomplete" + log_warn "Remove corrupted file..." + rm -f "$FINAL_OUTPUT_PATH" + exit 1 + fi + + echo "" + log_info "Successfully created installer image!" + log_info "File: $FINAL_OUTPUT_PATH" + log_info "Size: $FILE_SIZE_GB" + echo "" + + if [ "$IMAGE_FORMAT" == "iso" ]; then + log_info "This ISO image is intended for creating macOS virtual machine:" + log_info " - Compatible with Proxmox VE, QEMU, VMware, and VirtualBox" + log_info " - Add as DVD/CD drive to the VM" + echo "" + else + log_info "This DMG image is intended for:" + log_info " - Flash to USB drive using Rufus (Windows) or dd (Linux)" + log_info " - Can also be used with virtual machines (requires conversion to .vhdx for Hyper-V or .vmdk for VMware)" + log_info " - Add to the VM as a virtual hard drive" + echo "" + fi + else + log_error "Failed to create macOS_${VERSION_NAME}.${IMAGE_FORMAT} image" + exit 1 + fi +} + +# Show usage if -h or --help is passed +if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then + echo "╔══════════════════════════════════════════════════════════════════════════════════════╗" + echo "║ mkmaciso - the ultimate macOS utility for creating macOS installer ISO and DMG images║" + echo "╚══════════════════════════════════════════════════════════════════════════════════════╝" + echo "" + echo "Usage: $0 [VERSION] [FORMAT] [OUTPUT_PATH]" + echo " $0 # Run with no arguments to enter interactive mode" + echo "" + echo "Parameters:" + echo " VERSION - macOS version (number or codename), default: 26 (Tahoe)" + echo "" + echo " FORMAT - Image format: iso or dmg, default: iso" + echo "" + echo " OUTPUT_PATH - Output file path, default: ./macOS_." + echo "" + echo "Interactive Mode:" + echo " Run without any parameters to use the interactive menu." + echo "" + echo "Supported versions:" + echo " 10.7 (Lion) 10.14 (Mojave)" + echo " 10.8 (Mountain Lion) 10.15 (Catalina)" + echo " 10.9 (Mavericks) 11 (Big Sur)" + echo " 10.10 (Yosemite) 12 (Monterey)" + echo " 10.11 (El Capitan) 13 (Ventura)" + echo " 10.12 (Sierra) 14 (Sonoma)" + echo " 10.13 (High Sierra) 15 (Sequoia)" + echo " 26 (Tahoe)" + echo "" + echo "Examples:" + echo " $0 # Interactive mode" + echo " $0 14 # Create macOS Sonoma ISO in current directory" + echo " $0 14 dmg # Create macOS Sonoma DMG in current directory" + echo " $0 sonoma dmg ~/Desktop/Sonoma.dmg # Create Sonoma DMG on Desktop" + echo "" + echo "Requirements:" + echo " - macOS 11 (Big Sur) or later for create macOS 10.13+ image" + echo " - Internet connection for downloading installers" + echo " - Sufficient disk space (~20-30GB temporary, final size varies)" + echo " - Administrator privileges (sudo)" + echo " - Note: On Apple silicon Macs only the macOS version that originally" + echo " shipped with your device (or newer) can be download using this script" + echo "" + exit 0 +fi + +# Check if running in interactive mode (no parameters) +if [ $# -eq 0 ]; then + run_interactive_menu +fi + +# Run main function +main