# yamllint disable rule:line-length
---
name: Generate README
on:
  schedule:
    - cron: 0 17 * * *
  workflow_dispatch: null
jobs:
  README_updater:
    if: github.repository_owner == 'alexbelgium'
    runs-on: ubuntu-20.04
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v4
      - name: Create README file
        run: |
          # Init

          echo "Starting"

          # Prepare template

          cp .templates/.README.md README2.md

          ADDONSLINE="$(sed -n '/%%ADDONS_LIST%%/=' README2.md)"

          sed -i "/**ADDONS_LIST%%/d" README2.md

          # Sort folders by addon name

          # shellcheck disable=SC2086
          for f in $( find -- * -maxdepth 0 -type d | sort -r ); do
            if [ -f "$f"/config.json ]; then
              NAME=$(jq -r '.name' "$f"/config.json)
              if [[ "$f" != "$NAME" ]]; then
                echo "$f" > "$f"/oldname
                mv "$f" "$NAME"
              fi
            fi
          done      


          # Populate template

          find -- * -maxdepth 0 -type d | sort -r | while read -r f; do
            # $f is an addon directory
            if [ -f "$f/config.json" ]; then
              
              echo "Project $f"
              
              # Get variables
              if [ -f "$f/oldname" ]; then FOLDERNAME="$(cat "$f/oldname")"; else FOLDERNAME="$f"; fi
              NAME="$(jq -r '.name' "$f/config.json")"
              DESCRIPTION="$(jq -r '.description' "$f/config.json")"
              # Get icon
              if [ "$(jq '.panel_icon' "$f/config.json")" != null ]; then 
                ICON="$(jq -r '.panel_icon' "$f/config.json")"
                ICON="${ICON#*:}"
                ICON="![image](https://api.iconify.design/mdi/$ICON.svg)"
              else 
                ICON=""
              fi

              # Write infos
              echo "Writing infos"
              sed -i "$ADDONSLINE"'{G;}' README2.md
              if [[ "$(jq '.schema' "$f/config.json" 2>/dev/null)" == *"localdisks"* ]]; then sed -i "$ADDONSLINE"'a ![localdisks][localdisks-badge]' README2.md; fi
              if [[ "$(jq '.schema' "$f/config.json" 2>/dev/null)" == *"networkdisks"* ]]; then sed -i "$ADDONSLINE"'a ![smb][smb-badge]' README2.md; fi
              if [[ "$(jq '.full_access' "$f/config.json" 2>/dev/null)" == "true" ]]; then sed -i "$ADDONSLINE"'a ![full_access][full_access-badge]' README2.md; fi
              if [[ "$(jq '.services[]' "$f/config.json" 2>/dev/null)" == *"mqtt"* ]]; then sed -i "$ADDONSLINE"'a ![mqtt][mqtt-badge]' README2.md; fi
              if [[ "$(jq '.services[]' "$f/config.json" 2>/dev/null)" == *"mysql"* ]]; then sed -i "$ADDONSLINE"'a ![MariaDB][mariadb-badge]' README2.md; fi
              if [[ "$(jq '.ingress' "$f/config.json" 2>/dev/null)" == "true" ]]; then sed -i "$ADDONSLINE"'a ![ingress][ingress-badge]' README2.md; fi
              if [[ "$(jq '.arch[]' "$f/config.json")" == *"armv7"* ]]; then
                sed -i "$ADDONSLINE"'a ![armv7][armv7-badge]' README2.md
              else sed -i "$ADDONSLINE"'a ![armv7no][armv7no-badge]' README2.md; fi || true
              if [[ "$(jq '.arch[]' "$f/config.json")" == *"amd64"* ]]; then 
                sed -i "$ADDONSLINE"'a ![amd64][amd64-badge]' README2.md
              else sed -i "$ADDONSLINE"'a ![amd64no][amd64no-badge]' README2.md; fi || true
              if [[ "$(jq '.arch[]' "$f/config.json")" == *"aarch64"* ]]; then 
                sed -i "$ADDONSLINE"'a ![aarch64][aarch64-badge]' README2.md
              else sed -i "$ADDONSLINE"'a ![aarch64no][aarch64no-badge]' README2.md; fi || true
              if [[ -f "$f/updater.json" ]]; then sed -i "$ADDONSLINE"'a ![Update](https://img.shields.io/badge/dynamic/json?label=Updated&query=%24.last_update&url=https%3A%2F%2Fraw.githubusercontent.com%2Falexbelgium%2Fhassio-addons%2Fmaster%2F'"$FOLDERNAME"'%2Fupdater.json)' README2.md; fi
              sed -i "$ADDONSLINE"'a &emsp;&emsp;![Version](https://img.shields.io/badge/dynamic/json?label=Version&query=%24.version&url=https%3A%2F%2Fraw.githubusercontent.com%2Falexbelgium%2Fhassio-addons%2Fmaster%2F'"$FOLDERNAME"'%2Fconfig.json)' README2.md || true
              sed -i "$ADDONSLINE"'a &#10003; '"$ICON"' ['"$NAME"']('"$FOLDERNAME"'/) : '"$DESCRIPTION\\n" README2.md
            fi
          done

          # Restore folders name

          echo "Restore structure..."
          find -- * -maxdepth 0 -type d | sort -r | while read -r f; do
            if [ -f "$f/oldname" ]; then
              NAME="$(cat "$f/oldname")"
              rm "$f/oldname"
              mv "$f" "$NAME"
            fi
          done
          echo "... done"

          # Write stats

          # shellcheck disable=SC2002
          echo "Global stats..."
          STATS_DOWNLOADS="$(awk 'NR==2{print $1}' Stats)"
          sed -i "s|%%STATS_DOWNLOADS%%|$STATS_DOWNLOADS|g" README2.md && \
          sed -i "s|%%STATS_ADDONS%%|$(find . -name "config.json" | wc -l)|g" README2.md && \
          STATS_ONE="$(awk 'NR==3{print $(NF)}' Stats)" && \
          STATS_TWO="$(awk 'NR==4{print $(NF)}' Stats)" && \
          STATS_THREE="$(awk 'NR==5{print $(NF)}' Stats)"
          echo "Best addon is $STATS_ONE"
          sed -i "s|%%STATS_ONE%%|${STATS_ONE^}|g" README2.md
          sed -i "s|%%STATS_TWO%%|${STATS_TWO^}|g" README2.md
          sed -i "s|%%STATS_THREE%%|${STATS_THREE^}|g" README2.md
          echo "... done"

          # Breakdown per arch
          echo "Breakdown per arch..."
          STATS_ARMV7="$(awk '{SUM+=$3}END{print SUM}' Stats2)"
          STATS_AMD64="$(awk '{SUM+=$4}END{print SUM}' Stats2)"
          STATS_AARCH64="$(awk '{SUM+=$5}END{print SUM}' Stats2)"
          STATS_DOWNLOADS="$(( "$STATS_ARMV7" + "$STATS_AMD64" + "$STATS_AARCH64" ))"
          STATS_ARMV7="$(awk -v t1="$STATS_ARMV7" -v t2="$STATS_AMD64" -v t3="$STATS_AARCH64" -v t4="$STATS_DOWNLOADS" 'BEGIN{printf "%.0f", t1/t4 * 100}')"
          STATS_AMD64="$(awk -v t1="$STATS_ARMV7" -v t2="$STATS_AMD64" -v t3="$STATS_AARCH64" -v t4="$STATS_DOWNLOADS" 'BEGIN{printf "%.0f", t2/t4 * 100}')"
          STATS_AARCH64="$(awk -v t1="$STATS_ARMV7" -v t2="$STATS_AMD64" -v t3="$STATS_AARCH64" -v t4="$STATS_DOWNLOADS" 'BEGIN{printf "%.0f", t3/t4 * 100}')"
          sed -i "s|%%STATS_ARMV7%%|armv7: ${STATS_ARMV7}%|g" README2.md
          sed -i "s|%%STATS_AMD64%%|amd64: ${STATS_AMD64}%|g" README2.md
          sed -i "s|%%STATS_AARCH64%%|aarch64: ${STATS_AARCH64}%|g" README2.md
          #echo $((100*$STATS_THREE/($STATS_ONE+$STATS_TWO+$STATS_THREE)))
          echo "... done"

          for var in "$STATS_ONE" "$STATS_TWO" "$STATS_THREE"; do
          i=0
          j=0
          k=0
            # shellcheck disable=SC2013
            for i in $(sed -n "/$var/p" Stats); do
              k="$((k+1))"
              if [ "$k" -eq 3 ]; then break; fi
              if [ "$i" -eq "$i" ] && [ "$i" -gt "$j" ]; then j="$i"; fi
            done
          sed -i "s|${var^}|${var^} (${j}x)|g" README2.md
          echo "$STATS_ONE has $j downloads"
          done
          echo "... done"

          # Replace template if change

          echo "Replace template..."
          mv README2.md README.md

          echo "... done"

        shell: bash
      - name: Commit if needed
        uses: EndBug/add-and-commit@v9
        with:
          message: "GitHub bot : README updated"
          default_author: github_actions
