# Workflow derived from https://github.com/r-lib/actions/tree/v2/examples
# Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help
on:
  push:
    branches: [main, master]

name: shiny-deploy.yaml

permissions: read-all

jobs:
  shiny-deploy:
    runs-on: ubuntu-latest
    env:
      GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }}
      APPNAME: __APPNAME__
      CONNECT_SERVER: ${{ secrets.CONNECT_SERVER }}
      CONNECT_API_KEY: ${{ secrets.CONNECT_API_KEY }}
    steps:
      - uses: actions/checkout@v4

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

      - uses: r-lib/actions/setup-r@v2
        with:
          use-public-rspm: true

      - uses: r-lib/actions/setup-renv@v2
        if: ${{ hashFiles('renv.lock') != '' }}

      - uses: r-lib/actions/setup-r-dependencies@v2
        if: ${{ hashFiles('renv.lock') == '' }}
        with:
          extra-packages: any::rsconnect, local::.
          needs: shiny

      - name: Install deployment tooling
        if: ${{ hashFiles('renv.lock') != '' }}
        run: |
          install.packages("rsconnect")
        shell: Rscript {0}

      - name: Check deployment dependencies
        run: |
          required <- c("pkgload", "rsconnect")
          missing <- required[
            !vapply(required, requireNamespace, logical(1), quietly = TRUE)
          ]
          if (length(missing) > 0) {
            stop(
              sprintf(
                paste(
                  "Missing deployment packages: %s.",
                  "Run renv::snapshot() after generating this workflow",
                  "if you use renv."
                ),
                paste(missing, collapse = ", ")
              ),
              call. = FALSE
            )
          }
        shell: Rscript {0}

      - name: Validate deployment settings
        run: |
          required <- c("CONNECT_SERVER", "CONNECT_API_KEY")
          missing <- required[vapply(required, function(x) Sys.getenv(x) == "", logical(1))]
          if (length(missing) > 0) {
            stop(
              sprintf(
                "Missing GitHub Actions secrets: %s",
                paste(missing, collapse = ", ")
              ),
              call. = FALSE
            )
          }
          if (Sys.getenv("APPNAME") == "") {
            stop(
              "Set APPNAME in the workflow before deploying.",
              call. = FALSE
            )
          }
        shell: Rscript {0}

      - name: Generate deployment manifest
        run: |
          rsconnect::writeManifest(appDir = ".", appPrimaryDoc = "app.R")
        shell: Rscript {0}

      - name: Authorize and deploy app
        run: |
          rsconnect::connectApiUser(server = Sys.getenv("CONNECT_SERVER"), apiKey = Sys.getenv("CONNECT_API_KEY"), quiet = TRUE)
          rsconnect::deployApp(appDir = ".", appPrimaryDoc = "app.R", appName = Sys.getenv("APPNAME"), server = Sys.getenv("CONNECT_SERVER"), forceUpdate = TRUE)
        shell: Rscript {0}
