name: Build FujiNet-PC

on:
  # push:
  #   branches:
  #     - "**"
  workflow_dispatch:
    inputs:
      # buildType:
      #   description: 'Build Type'
      #   required: true
      #   type: choice
      #   options:
      #   - Debug
      #   - RelWithDebInfo
      #   - Release
      #   default: 'Debug'
      prepRelease:
        description: 'Prepare GitHub Release Draft'
        type: boolean
        default: false

  pull_request:
    # Do not build release branch
    branches:
      - "**"
      - "!release"

  schedule:
    - cron: '12 3 * * *'

# env:
#   # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.)
#   BUILD_TYPE: ${{ github.event.inputs.buildType }}

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        os:
          - name: Ubuntu 22.04
            runner: ubuntu-22.04
            target: ubuntu-22.04-amd64
            default-shell: bash
          - name: Ubuntu 24.04
            runner: ubuntu-24.04
            target: ubuntu-24.04-amd64
            default-shell: bash
          - name: macOS 13
            target: macos-13
            runner: macos-13
            default-shell: bash
          - name: macOS 14
            target: macos-14
            runner: macos-14
            default-shell: bash
          - name: Windows
            target: windows-x64
            runner: windows-latest
            sys: clang64
            default-shell: msys2 {0}
          # # mbedtls not available anymore for clang32 :-(
          # - name: Windows x86
          #   target: windows-x86
          #   runner: windows-latest
          #   sys: clang32
          #   default-shell: msys2 {0}
        fujinet_target:
          - APPLE
          - ATARI
          - COCO

    # continue-on-error: true
    name: "${{ matrix.os.name }}: Target ${{ matrix.fujinet_target }}"
    runs-on: ${{ matrix.os.runner }}
    defaults:
      run:
        shell: ${{ matrix.os.default-shell }}
    outputs:
      fujinet_version: ${{ steps.version.outputs.fujinet }}
      build_date: ${{ steps.version.outputs.build_date }}

    steps:
    # Setup MSYS2 on Windows
    - name: '[Windows] Setup MSYS2'
      if: ${{ startsWith(matrix.os.target, 'windows') }}
      uses: msys2/setup-msys2@v2
      with:
        msystem: ${{matrix.os.sys}}
        update: true
        install: >-
          git
          base-devel
        pacboy: >-
          toolchain:p
          cmake:p
          ninja:p
          python-pip:p
          mbedtls:p

    - name: '[macOS] Install MbedTLS'
      if: ${{ startsWith(matrix.os.target, 'macos') }}
      run: |
        brew update
        brew install mbedtls

    - name: '[Ubuntu] Install MbedTLS'
      if: ${{ startsWith(matrix.os.target, 'ubuntu') }}
      run: |
        sudo apt-get update
        sudo apt-get install -y libmbedtls-dev

    - name: About ${{ matrix.os.name }}
      run: |
        echo "Building for ${{ matrix.os.name }} (${{ matrix.os.target }}) on ${{ matrix.os.runner }}"
        uname -a

    - name: '🧰 Checkout'
      uses: actions/checkout@v4

    - name: Fetch tags
      run: git fetch --prune --unshallow --tags

    - name: 'Install Python'
      # if: ${{ !startsWith(matrix.os.target, 'windows') }}
      uses: actions/setup-python@v5
      id: cp310
      with:
        python-version: '3.10'

    - name: Check Python version (default)
      run: |
        which python
        python --version
        printenv PATH
        printenv pythonLocation

    - name: Check Python version (from setup-python)
      run: |
        echo '${{ steps.cp310.outputs.python-path }}'
        '${{ steps.cp310.outputs.python-path }}' --version

    - name: 'Install Python packages'
      run: |
        '${{ steps.cp310.outputs.python-path }}' -m pip install -U Jinja2 pyyaml

    - name: '[regular OS] 🚧 Build FujiNet-PC (matrix.fujinet_target)'
      if: ${{ !startsWith(matrix.os.target, 'windows') }}
      run: |
        ./build.sh -p ${{ matrix.fujinet_target }}

    # For MSYS tune PATH variable for PYTHON:
    # add 'C:\hostedtoolcache\windows\Python\3.10.11\x64' as '/c/hostedtoolcache/windows/Python/3.10.11/x64'
    - name: '[Windows MSYS2] 🚧 Build FujiNet-PC (matrix.fujinet_target)'
      if: ${{ startsWith(matrix.os.target, 'windows') }}
      run: |
        export PATH=$(printenv pythonLocation | sed 's@\\@/@g' | sed 's@^c:/@/c/@i'):$PATH
        printenv PATH
        ./build.sh -p ${{ matrix.fujinet_target }}

    # - name: Configure CMake
    #   #run: cmake -B build -DFUJINET_TARGET=${{matrix.fujinet_target}} -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}}
    #   run: cmake -B build -DFUJINET_TARGET=${{matrix.fujinet_target}} -DCMAKE_BUILD_TYPE=Release

    # - name: '🚧 Build FujiNet-PC'
    #   run: cmake --build build --target all -j 8

    # - name: Prepare dist
    #   run: cmake --build build --target dist

    - name: List dist
      working-directory: build/dist
      run: ls -la

    - name: 'Get build version'
      id: version
      working-directory: build/dist
      run: |
        ./fujinet -V
        echo "fujinet=$(./fujinet -V | awk '{if(tolower($1)=="fujinet-pc") print $2}')" >> $GITHUB_OUTPUT
        echo "build_date=$(date +'%Y-%m-%d')" >> $GITHUB_OUTPUT

    - name: 'Tar dist files'
      working-directory: build
      run: |
        mv dist fujinet-pc-${{ matrix.fujinet_target }}
        tar -cvf fujinet-pc-${{ matrix.fujinet_target }}_${{ steps.version.outputs.fujinet }}_${{ matrix.os.target }}.tar fujinet-pc-${{ matrix.fujinet_target }}

    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: fujinet-pc-${{ matrix.fujinet_target }}_${{ steps.version.outputs.fujinet }}_${{ matrix.os.target }}
        path: build/fujinet-pc-${{ matrix.fujinet_target }}_${{ steps.version.outputs.fujinet }}_${{ matrix.os.target }}.tar
        
  release:
    if: ${{ github.event_name == 'schedule' || github.event.inputs.prepRelease == 'true' }}
    # Create GitHub release
    runs-on: ubuntu-latest
    name: Release
    needs: build

    steps:
    - name: Download build artifacts
      uses: actions/download-artifact@v4
      with:
        path: release

    - name: Display structure of downloaded files
      run: ls -lR release
      
    - name: Zip release files
      working-directory: release
      run: |
        for D in fujinet-pc-*_*ubuntu* fujinet-pc-*_*macos*; do gzip -9v $D/fujinet-pc-*_*.tar; done
        for D in fujinet-pc-*_*windows*; do (cd $D; F=(fujinet-pc-*_*.tar); tar -xvf $F; rm -f $F; zip -r ${F%.*}.zip fujinet-pc-*); done
        
    - name: Prepare Release Draft
      if: ${{ github.event.inputs.prepRelease == 'true' }}
      uses: softprops/action-gh-release@v2
      with:
          name: "FujiNet-PC ${{ needs.build.outputs.fujinet_version }}"
          tag_name: ${{ needs.build.outputs.fujinet_version }}
          draft: true
          files: |
            release/fujinet-pc-*_*/fujinet-pc-*_*.tar.gz
            release/fujinet-pc-*_*/fujinet-pc-*_*.zip

    - name: Create Nightly Build Release
      if: ${{ github.event_name == 'schedule' }}
      uses: softprops/action-gh-release@v2
      with:
          name: "FujiNet-PC Nightly ${{ needs.build.outputs.build_date }}"
          body: |
            FujiNet-PC **${{ needs.build.outputs.fujinet_version }}** nightly builds for: Apple 2, Atari 8-bit and Tandy Color Computer
            ⚠️ There is NO guarantee that these builds work!! ⚠️
          tag_name: nightly_fn_pc_${{ needs.build.outputs.fujinet_version }}
          prerelease: true 
          make_latest: false
          files: |
            release/fujinet-pc-*_*/fujinet-pc-*_*.tar.gz
            release/fujinet-pc-*_*/fujinet-pc-*_*.zip

  postrelease:
    if: ${{ github.event_name == 'schedule' }}
    # Delete old nightly releases
    runs-on: ubuntu-latest
    name: Post-Release
    needs: release

    steps:
    - name: 'Checkout'
      # Checkout, to make "gh" command working
      uses: actions/checkout@v4

    - name: Delete old nightly releases
      run: |
        gh release list --json tagName,createdAt \
          --jq 'map(select(.tagName | test("^nightly_fn_pc"))) | sort_by(.createdAt)[0:-3][].tagName' |\
          xargs -I% sh -c 'echo Deleting release %; gh release delete % --cleanup-tag'
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
