name: release macOS

on:
  workflow_dispatch:
    inputs:
      release_tag:
        required: false
        type: string
  push:
    branches:
      - master

permissions:
  contents: write

jobs:
  build:
    uses: ./.github/workflows/build.yml
    with:
      target: macos

  release-zip:
    if: inputs.release_tag != ''
    needs: build
    uses: ./.github/workflows/package-zip.yml
    with:
      target: macos
      release_tag: ${{ inputs.release_tag }}
    
  dmg:
    name: package and release macOS dmg
    if: inputs.release_tag != ''
    needs: build
    strategy:
      matrix:
        arch: [ x64, arm64 ]
    runs-on: macos-latest
    env:
      Arch: |-
        ${{
          case(
            matrix.arch == 'x64', '64',
            matrix.arch
          ) 
        }} 
    steps:
    - name: Checkout
      uses: actions/checkout@v6

    - name: Restore build artifacts
      uses: actions/download-artifact@v8
      with:
        name: ${{ matrix.arch }}
        path: v2rayN-macos-${{ env.Arch }}
    
    - name: Setup create-dmg
      run: brew install create-dmg

    - name: Ensure script permissions
      run: chmod 755 package-osx.sh

    - name: Package dmg
      run: ./package-osx.sh macos-$Arch v2rayN-macos-$Arch ${{ inputs.release_tag }}

    - name: Sleep for race condition between matrix jobs
      run: sleep "$(od -An -N2 -tu2 /dev/urandom | awk 'NR==1{printf "%.2f", $1/5461}')"
    
    - name: Upload dmg to release
      uses: svenstaro/upload-release-action@v2
      with:
        file: ${{ github.workspace }}/v2rayN*.dmg
        tag: ${{ inputs.release_tag }}
        file_glob: true
        prerelease: true
