stages:
  - build
  - deploy

variables:
  COMPOSER_ALLOW_SUPERUSER: '1'

# PREPROD
build_preprod:
  stage: build
  only:
    - preprod
  image: composer:2
  script:
    - apk add --no-cache nodejs npm
    - npm install
    - npm run build:preprod
    - cd dist
    - composer install --no-dev --optimize-autoloader --ignore-platform-req=ext-gd
    - cd ..
  artifacts:
    paths:
      - dist/
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/

deploy_preprod:
  stage: deploy
  image: node:latest
  only:
    - preprod
  before_script:
    - apt-get update -qq && apt-get install -y rsync sshpass
  script:
    - cd dist
    - |
      rsync_deploy() {
        local src=$1
        local dst=$2
        local exclude=$3
        cmd="sshpass -p \"$PASSWORD\" rsync -az --delete -O"
        [[ -n $exclude ]] && cmd="$cmd $exclude"
        cmd="$cmd -e 'ssh -p 2244 -o StrictHostKeyChecking=no' $src $USERNAME@$HOST:$dst"
        echo "$cmd"
        eval $cmd
      }

      rsync_deploy site/ "$PREPROD_PATH/site/" "--exclude 'accounts/' --exclude 'cache/' --exclude 'sessions/'"
      rsync_deploy vendor/ "$PREPROD_PATH/vendor/"
      rsync_deploy kirby/ "$PREPROD_PATH/kirby/"
      rsync_deploy assets/ "$PREPROD_PATH/assets/" "--exclude 'tiles/'"

# PROD
build_prod:
  stage: build
  only:
    - prod
  image: composer:2
  script:
    - apk add --no-cache nodejs npm
    - npm install
    - npm run build
    - cd dist
    - composer install --no-dev --optimize-autoloader --ignore-platform-req=ext-gd
    - cd ..
  artifacts:
    paths:
      - dist/
  cache:
    key: ${CI_COMMIT_REF_SLUG}
    paths:
      - node_modules/

deploy_prod:
  stage: deploy
  image: node:latest
  only:
    - main
  before_script:
    - apt-get update -qq && apt-get install -y rsync sshpass
  script:
    - cd dist
    - |
      rsync_deploy() {
        local src=$1
        local dst=$2
        local exclude=$3
        cmd="sshpass -p \"$PASSWORD\" rsync -az --delete -O"
        [[ -n $exclude ]] && cmd="$cmd $exclude"
        cmd="$cmd -e 'ssh -p 2244 -o StrictHostKeyChecking=no' $src $USERNAME@$HOST:$dst"
        echo "$cmd"
        eval $cmd
      }

      rsync_deploy site/ "$PROD_PATH/site/" "--exclude 'accounts/' --exclude 'cache/' --exclude 'sessions/'"
      rsync_deploy vendor/ "$PROD_PATH/vendor/"
      rsync_deploy kirby/ "$PROD_PATH/kirby/"
      rsync_deploy assets/ "$PROD_PATH/assets/" "--exclude 'tiles/'"
