name: Fetch and Publish Latest Release

on:
    schedule:
        - cron: '0 18 * * *' # 3:00 AM GMT+9
    workflow_dispatch:
        inputs:
            tag_name:
                description: 'Tag name for the manual release'
                required: true
                default: 'YYYYMMDD-manual-HHMMSS'
    push:
        branches:
            - main

jobs:
  fetch-and-publish:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout this repository
      uses: actions/checkout@v2

    - name: Fetch latest release from Vita3K
      id: fetch_release
      run: |
        latest_release=$(curl -s https://api.github.com/repos/Vita3K/Vita3K/releases/latest)
        tag_name="$(echo $latest_release | jq -r .tag_name)"

        # fetching assets
        mkdir -p artifacts
        for url in $(echo $latest_release | jq -r '.assets[] | .browser_download_url'); do
          wget -P artifacts $url
        done

        ls -lah artifacts

        release_name="$(echo $latest_release | jq -r .body | grep -oP 'Vita3K Build: \d+' | sed 's/Vita3K Build: /Vita3K - Build /')"
        echo "release_name=$release_name"

        commit_hash="$(echo $latest_release | jq -r .body | grep -oP 'Corresponding commit: \K[0-9a-f]{40}')"
        echo "commit_hash=$commit_hash"

        release_body+="Corresponding commit: [$commit_hash](https://github.com/Vita3K/Vita3K/commit/$commit_hash)</br>"
        release_body+="$release_name" 
        echo "release_body=$release_body"

        echo "tag_name=$tag_name" >> $GITHUB_ENV
        echo "release_body=$release_body" >> $GITHUB_ENV
        echo "release_name=$release_name" >> $GITHUB_ENV
        
    - name: Create release in this repository
      id: create_release
      uses: actions/create-release@v1
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      with:
        tag_name: ${{ format('YYYYMMDD-HHmmss', github.event.inputs['time']) }}
        release_name: ${{ env.release_name }}
        body: ${{ env.release_body }}
        draft: false
        prerelease: false

    - name: Upload assets to the new release
      run: |
        for file in artifacts/*; do
          echo "Uploading $file..."
          gh release upload ${{ env.tag_name }} "$file" --clobber
        done
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}