image: node:20

stages:
  - build
  - deploy

.documentation-setup:
  before_script:
    - corepack enable
    - corepack prepare pnpm@latest-9 --activate
    - pnpm config set store-dir .pnpm-store
    - cd docs
    - chmod +x ./scripts/i18n-filter.sh
    - ./scripts/i18n-filter.sh src/content/docs
    - pnpm install

cache:
  key:
    files:
      - docs/pnpm-lock.yaml
  paths:
    - .pnpm-store

# This job only serves for validating that the docs builds correctly on all non deployment branches
build:
  extends: .documentation-setup
  stage: build
  script:
    - pnpm run build
  except:
    - develop
    - main
    - beta
    - alpha
    - next

build-production:
  extends: .documentation-setup
  stage: build
  environment:
    name: production
    url: https://docs.castopod.org/
  script:
    - BASE=/$CI_COMMIT_REF_SLUG pnpm run build --outDir=./dist/$CI_COMMIT_REF_SLUG --base=/$CI_COMMIT_REF_SLUG
  artifacts:
    paths:
      - docs/dist/$CI_COMMIT_REF_SLUG
    expire_in: 30 mins
  only:
    - develop
    - main
    - beta
    - alpha
    - next

deploy:
  stage: deploy
  environment:
    name: production
    url: https://docs.castopod.org/
  variables:
    HOST: $DOCS_HOST
    USER: $DOCS_USER
    TEMP_DIRECTORY: $DOCS_TEMP_DIRECTORY/$CI_COMMIT_REF_SLUG/
    DIRECTORY: $DOCS_DIRECTORY/$CI_COMMIT_REF_SLUG/
    SSH_PORT: 3242
    SOURCE_FOLDER: "docs/dist/$CI_COMMIT_REF_SLUG/"
  before_script:
    # install rsync for file transfers
    - apt-get update && apt-get install rsync -y
    # Run ssh-agent (inside the build environment)
    - eval $(ssh-agent -s)
    # Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
    - ssh-add <(echo "$SSH_PRIVATE_KEY" | base64 --decode)
    - mkdir -p ~/.ssh
    - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
  script:
    - rsync -avzuh -e "ssh -p $SSH_PORT" $SOURCE_FOLDER $USER@$HOST:$TEMP_DIRECTORY --progress
    - ssh $USER@$HOST -p $SSH_PORT "rsync -rtv $TEMP_DIRECTORY $DIRECTORY"
  only:
    - develop
    - main
    - beta
    - alpha
    - next
