image: node:14.21.2-alpine3.17
definitions:
  services:
    docker:
      memory: 2048
  caches:
    npm-cache: ~/.npm
  steps:
    - step: &install
        name: Install dependencies
        caches:
          - npm-cache
          - node
        script:
          - npm install -g npm@7.24.2
          - npm ci --no-audit --progress=false --prefer-offline
    - step: &lint
        name: Linting
        caches:
          - node
        script:
          - npm run lint
    - step: &deploy
        name: deploy
        services:
          - docker
        size: 2x
        script:
          - export DOCKER_IMAGE_TAG=$AZURE_SERVER/$PROJECT_NAME:$BITBUCKET_DEPLOYMENT_ENVIRONMENT
          - export DOCKER_IMAGE_NAME=${PROJECT_NAME}_${BITBUCKET_DEPLOYMENT_ENVIRONMENT}
          - docker build --build-arg BACKEND_URL=$BACKEND_URL -t $DOCKER_IMAGE_TAG -f ./docker/Dockerfile .
          - docker login $AZURE_SERVER -u $AZURE_USER -p $AZURE_PASSWORD
          - docker push $DOCKER_IMAGE_TAG
          - apk update
          - apk add --no-cache openssh
          - ssh $SSH_USER@$SSH_SERVER "
            docker login $AZURE_SERVER -u $AZURE_USER -p $AZURE_PASSWORD &&
            docker stop $DOCKER_IMAGE_NAME || true &&
            docker rm $DOCKER_IMAGE_NAME || true &&
            docker pull $DOCKER_IMAGE_TAG &&
            docker run -d -p $DOCKER_PORT:80 --name $DOCKER_IMAGE_NAME $DOCKER_IMAGE_TAG
            "

pipelines:
  branches:
    develop:
      - step: *install
      - step: *lint
      - step:
          <<: *deploy
          name: Deploy to development server
          deployment: development
          trigger: automatic
    main:
      - step: *install
      - step: *lint
      - step:
          <<: *deploy
          name: Deploy to production server
          deployment: production
          trigger: manual

