name: Generate Apps List

on:
  push:
    branches:
      - main
  #schedule:
  #  - cron: '0 1 * * *' #UTC

jobs:
  generate-apps-list:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Code
        uses: actions/checkout@v2

      - name: Set up Node.js
        uses: actions/setup-node@v2
        with:
          node-version: '14'

      - name: Install jq
        run: sudo apt-get install jq -y

      - name: Generate Apps List
        id: generate-apps-list
        run: |
          # Create an empty README.md file
          echo "" > README.md
  
          app_list=""
          for app_folder in Apps/*; do
            if [ -f "$app_folder/app.json" ]; then
              app_data=$(cat "$app_folder/app.json")
              app_name=$(echo "$app_data" | jq -r .app)
              app_name_url=$(echo "$app_data" | jq -r .app_url)
              app_description=$(echo "$app_data" | jq -r .description)
              app_image=$(echo "$app_data" | jq -r .image)
              app_image_url=$(echo "$app_data" | jq -r .image_url)
              app_tag=$(echo "$app_data" | jq -r .tag)

              app_list+="| <h2><img src="$app_folder/icon.png" width="21" height="21"> $app_name</h2> [![tag](https://img.shields.io/badge/$app_image-$app_tag-blue?style=plastic)]($app_image_url) [![tag](https://img.shields.io/badge/visit-project-green?style=plastic)]($app_name_url) <br /> $app_description | ![thumbnail]($app_folder/thumbnail.png) |\n"
            fi
          done

          echo "::set-output name=content::${app_list}"

      - name: Update README.md with App List
        run: |
          app_list="${{ steps.generate-apps-list.outputs.content }}"
          awk -v app_list="$app_list" '1; ENDFILE { printf "%s", app_list }' ABOUT.md > README.md

      - name: Commit and Push Changes
        run: |
          git config user.name "GitHub Actions"
          git config user.email "actions@github.com"
          git add README.md
          git commit -m "Update README.md with apps list"
          git push --set-upstream origin ${{ github.ref }}
        env:
          GH_TOKEN: ${{ secrets.GH_TOKEN }}
