on:
  schedule:
    - cron:  '0 8 * * *'
  push:
    branches:
      - master
      - main
    paths:
      - "data-raw/upgrade.R"
  workflow_dispatch:

name: upgrade

jobs:
  upgrade:
    runs-on: ubuntu-20.04

    name: Upgrade bundled SQLite

    env:
      RSPM: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"
      R_REMOTES_NO_ERRORS_FROM_WARNINGS: true
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}

    steps:
      - name: Check rate limits
        run: |
          curl -s --header "authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/rate_limit
        shell: bash

      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: r-lib/actions/setup-r@v2

      - name: Install remotes
        run: |
          if (!requireNamespace("curl", quietly = TRUE)) install.packages("curl")
          if (!requireNamespace("remotes", quietly = TRUE)) install.packages("remotes")
        shell: Rscript {0}

      - name: Prepare cache keys
        if: runner.os != 'Windows'
        run: |
          saveRDS(remotes::dev_package_deps(dependencies = TRUE, type = .Platform$pkgType), ".github/depends.Rds", version = 2)
          writeLines(sprintf("R-%i.%i", getRversion()$major, getRversion()$minor), ".github/R-version")
        shell: Rscript {0}

      - name: Cache R packages
        if: runner.os != 'Windows'
        uses: actions/cache@v2
        with:
          path: ${{ env.R_LIBS_USER }}
          key: backends-${{ hashFiles('.github/R-version') }}-2-${{ hashFiles('.github/depends.Rds') }}
          restore-keys: backends-${{ hashFiles('.github/R-version') }}-2-

      - name: Install system dependencies
        if: runner.os == 'Linux'
        run: |
          while read -r cmd
          do
            eval sudo $cmd
          done < <(Rscript -e 'writeLines(remotes::system_requirements("ubuntu", "20.04"))')

      - name: Install package and dependencies
        run: |
          remotes::install_deps(dependencies = TRUE, type = .Platform$pkgType)
        shell: Rscript {0}

      - name: Session info
        run: |
          options(width = 100)
          if (!requireNamespace("sessioninfo", quietly = TRUE)) install.packages("sessioninfo")
          pkgs <- installed.packages()[, "Package"]
          sessioninfo::session_info(pkgs, include_base = TRUE)
        shell: Rscript {0}

      - name: Configure Git identity
        run: |
          env | sort
          git config --global user.name "$GITHUB_WORKFLOW"
          git config --global user.email "${GITHUB_EVENT_NAME}@ghactions.local"
        shell: bash

      - name: Run preparation
        run: |
          R -q -f data-raw/upgrade.R

      - name: Check rate limits
        if: always()
        run: |
          curl -s --header "authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/rate_limit
        shell: bash
