name: Sync wgcf latest version

on:
  workflow_dispatch:
  schedule:
    - cron: '3 2 * * *'

jobs:
  build:
    name: Sync wgcf latest version
    runs-on: ubuntu-latest
    env:
      USERNAME: ${{ secrets.GH_USERNAME }}
      EMAIL: ${{ secrets.GH_EMAIL }}

    steps:
      - uses: actions/checkout@v3
      - name: Update wgcf to latest version
        run: |
          NOW=$(wget -qO- https://raw.githubusercontent.com/${{ env.USERNAME }}/warp/main/menu.sh | grep 'latest=${latest' | cut -d \' -f2)
          LATEST=$(wget -qO- "https://api.github.com/repos/ViRb3/wgcf/releases/latest" | grep "tag_name" | head -n 1 | cut -d : -f2 | sed 's/[ \"v,]//g')
          NOW1=$(echo $NOW | cut -d \. -f1)
          NOW2=$(echo $NOW | cut -d \. -f2)
          NOW3=$(echo $NOW | cut -d \. -f3)
          LATEST1=$(echo $LATEST | cut -d \. -f1)
          LATEST2=$(echo $LATEST | cut -d \. -f2)
          LATEST3=$(echo $LATEST | cut -d \. -f3)
          NOW_VERSION=$(( NOW1*1000000 + NOW2*1000 + NOW3 ))
          LATEST_VERSION=$(( LATEST1*1000000 + LATEST2*1000 + LATEST3 ))
          if [ $LATEST_VERSION -gt $NOW_VERSION ]; then
            PLATFORM=(  "darwin_amd64"
                        "darwin_arm64"
                        "linux_386"
                        "linux_amd64"
                        "linux_arm64"
                        "linux_386"
                        "linux_s390x"
                        "windows_386.exe"
                        "windows_amd64.exe"
                      )
                    
            SCRIPTS=( "docker.sh"
                      "menu.sh"
                      "pc/mac.sh"
                    )
            
            for i in "${PLATFORM[@]}"; do
              wget -NP ${GITHUB_WORKSPACE}/wgcf/ https://github.com/ViRb3/wgcf/releases/download/v"$LATEST"/wgcf_"$LATEST"_"$i"
              rm -f ${GITHUB_WORKSPACE}/wgcf/wgcf_"$NOW"_"$i"
            done
            
            for j in "${SCRIPTS[@]}"; do
              sed -i "s/$NOW/$LATEST/g" ${GITHUB_WORKSPACE}/$j
            done
            
            echo "VERSION=$LATEST" >> $GITHUB_ENV
          fi
          
      - name: Upload to REPO
        if: ${{ env.VERSION != '' }}
        run: |
          git config --global user.email "${{ env.EMAIL }}"
          git config --global user.name "${{ env.USERNAME }}"
          git add .
          git commit -m "Sync WGCF to V${{ env.VERSION }} by Github Actions, $(date "+%Y/%m/%d %H:%M:%S")"
          git push

