version: 2

ANCHORS:
 node_steps: &node_steps
   steps:
     - checkout
     - run: npm install
     - run: npm test
     # Check whether "run build" is successful
     - run: npm run build
     # Check whether the build of an example is successful
     - run:
         name: Build example
         command: cd example && npm install && npm run build
     - run:
         name: Run example
         command: cd example && ! timeout 5 npm start

jobs:
  node_10:
    docker:
      - image: circleci/node:10
    <<: *node_steps

  node_8:
    docker:
      - image: circleci/node:8
    <<: *node_steps

  docker_test:
    machine: true
    steps:
      - checkout
      # Check whether "docker build" is successful or not
      - run: docker build -t http-knocking .
      - run:
          name: Working test with Docker image
          command: |
            # Create a network
            docker network create knocking-net
            # Run ngix server
            docker run --name=web1 --net=knocking-net --expose=80 --rm -d nginx:1.15-alpine
            # Run http-knocking to the nginx server
            docker run --rm --net=knocking-net -d -p 8282:8282 http-knocking --port=8282 --target-host=web1 --target-port=80 --open-knocking="/alpha,/foxtrot,/lima"

            # Wait for running servers
            sleep 1

            # Knocking
            curl localhost:8282/alpha
            curl localhost:8282/foxtrot
            curl localhost:8282/lima

            # Access nginx
            curl localhost:8282

  # (from: https://circleci.com/blog/publishing-npm-packages-using-circleci-2-0/)
  npm_publish:
    docker:
      - image: circleci/node:10
    steps:
      - checkout
      - run: npm install
      - run:
          name: Authenticate with registry
          command: echo -e "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc
      - run: npm publish

workflows:
  version: 2
  node_tests:
    jobs:
      - node_10:
          filters:
            tags:
              only: /.*/
      - node_8:
          filters:
            tags:
              only: /.*/
      - docker_test
      - npm_publish:
          requires:
            - node_10
            - node_8
          filters:
            tags:
              only: /.*/
            branches:
              ignore: /.*/
