name: Build All Formats and Release

on:
  push:
    tags:
      - v*
  workflow_dispatch:
    inputs:
      build_args:
        description: 'Args for build.py'
        required: false
        default: ''
        type: string

permissions:
  contents: write

jobs:
  build:
    strategy:
      matrix:
        config: [
          {name: normal-liga, args: "--normal --liga"},
          {name: normal-no-liga, args: "--normal --no-liga"},
          {name: liga, args: "--liga"},
          {name: no-liga, args: "--no-liga"}
        ]
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-python@v5
      with:
        python-version: '3.12'
        cache: 'pip'
        cache-dependency-path: './requirements.txt'
    - run: pip install -r requirements.txt
    - name: Build fonts
      run: |
        python build.py --archive --cn-both --hinted ${{ matrix.config.args }} ${{ github.event.inputs.build_args }}
        python build.py --archive --cn-both --no-hinted --cache ${{ matrix.config.args }} ${{ github.event.inputs.build_args }}
    - uses: actions/upload-artifact@v4
      with:
        name: release-artifacts-${{ matrix.config.name }}
        path: fonts/archive/*

  create-release:
    needs: build
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0
    - uses: actions/download-artifact@v4
      with:
        pattern: release-artifacts*
        path: release

    - name: Release artifacts
      run: |
        TAG="${{ github.ref_name }}"
        if [ "${{ github.event_name }}" == "workflow_dispatch" ]; then
          TAG="v$(date +%s)"
          PREV=$(git tag --list --sort=committerdate | tail -n 1)
          CHANGELOG=$(git log --pretty=format:"- %s" "$PREV"..HEAD | awk '1; END {print ""}' | tail -r)
        else
          PREV=$(git tag --list --sort=committerdate | tail -n 2 | head -n 1)
          CHANGELOG=$(git log --pretty=format:"- %s" "$PREV".."$TAG" | sed '1d' | awk '1; END {print ""}' | tail -r)
        fi
        sed -i 's|<!-- changelog -->|'"${CHANGELOG//$'\n'/\\n}"'|' .github/release_template.md

        sed -i "s|https://<url>|https://github.com/subframe7536/maple-font/releases/download/${TAG//\//\\/}|g" .github/release_template.md


        TITLE=$(python3 -c "print(' '.join(part.capitalize() for part in '$TAG'.split('-')))")

        gh release create "$TAG" release/**/*.* --notes-file .github/release_template.md --draft -t "$TITLE"
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}