name: Deploy firmware via FTP (master)

on:
    push:
        branches:
            - master

concurrency:
    group: deploy-master
    cancel-in-progress: true

jobs:
    deploy:
        name: Build and FTP Sync
        runs-on: ubuntu-latest
        steps:
            - name: Checkout
              uses: actions/checkout@v4

            - name: Setup Python
              uses: actions/setup-python@v5
              with:
                  python-version: '3.x'

            - name: Install PlatformIO
              run: |
                  python -m pip install --upgrade pip
                  python -m pip install platformio

            - name: Build firmware bundle
              run: pio run -e uno_linux

            - name: Install lftp client
              run: |
                  if command -v lftp >/dev/null 2>&1; then
                      echo 'lftp is already available on this runner image'
                      exit 0
                  fi

                  if command -v sudo >/dev/null 2>&1; then
                      sudo apt-get update
                      sudo apt-get install -y lftp
                      exit 0
                  fi

                  apt-get update
                  apt-get install -y lftp

            - name: Upload firmware bundle via lftp
              env:
                  FTP_SERVER: ${{ secrets.FTP_SERVER }}
                  FTP_USERNAME: ${{ secrets.FTP_USERNAME }}
                  FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }}
                  FTP_SERVER_DIR: ${{ secrets.FTP_SERVER_DIR }}
              run: |
                  lftp <<EOF
                  set cmd:fail-exit true
                  set net:timeout 120
                  set net:max-retries 2
                  set net:reconnect-interval-base 5
                  set ftp:passive-mode true
                  set ftp:prefer-epsv false
                  set ftp:ssl-force true
                  set ftp:ssl-protect-data true
                  set ftp:ssl-auth TLS
                  set ssl:verify-certificate no
                  open -u "$FTP_USERNAME","$FTP_PASSWORD" -p 21 "$FTP_SERVER"
                  mirror -R --verbose --delete \
                    --exclude-glob .DS_Store \
                    firmware/ "$FTP_SERVER_DIR"
                  quit
                  EOF
