image: node:20

stages:
  - build
  - deploy

before_script:
  - corepack enable
  - corepack prepare pnpm@latest-8 --activate
  - pnpm config set store-dir .pnpm-store
  - pnpm install
  # Generate .env file
  - chmod +x ./scripts/generate_env.sh
  - ./scripts/generate_env.sh

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

# This job only serves for validating that the app builds correctly on all non deployment branches
build:
  stage: build
  script:
    - pnpm run build
  only:
    variables:
      - $CI_PROJECT_NAMESPACE == "adaures"
  except:
    - main

build-production:
  stage: build
  environment:
    name: production
    url: https://castopod.org/
  script:
    - pnpm run build
  artifacts:
    paths:
      - dist
  only:
    refs:
      - main
    variables:
      - $CI_PROJECT_NAMESPACE == "adaures"

deploy:
  stage: deploy
  environment:
    name: production
    url: https://castopod.org/
  variables:
    HOST: $HOST
    USER: $USER
    TEMP_DIRECTORY: $TEMP_DIRECTORY
    DIRECTORY: $DIRECTORY
    SSH_PORT: 3242
    SOURCE_FOLDER: "dist/"
  before_script:
    # install rsync for file transfers
    - apt-get update && apt-get install rsync -y
    # ssh config
    - "which ssh-agent || ( apt-get update -y && apt-get install openssh-client -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:
    refs:
      - main
    variables:
      - $CI_PROJECT_NAMESPACE == "adaures"
