kind: pipeline
type: docker
name: emosr-web
platform:
  os: linux
  arch: arm64
steps:


  - name: build-package
    image: node:16.20.0
    volumes:
      - name: cache
        path: /drone/src/node_modules
    commands:
      - export CI=false
      - mkdir -p /app/build/$DRONE_REPO_NAME
      - rm -rf /app/build/$DRONE_REPO_NAME/*
      - cp deployment.yml /app/build/$DRONE_REPO_NAME/
      - cp Dockerfile /app/build/$DRONE_REPO_NAME/
      - cp .dockerignore /app/build/$DRONE_REPO_NAME/
      - cp default.conf /app/build/$DRONE_REPO_NAME/
      - cp docker.sh /app/build/$DRONE_REPO_NAME/
      - cp nginx.conf /app/build/$DRONE_REPO_NAME/
      - npm -v
      - mkdir -p ./node_modules
      - export NODE_MODULES_PATH=`pwd`/node_modules
      - npm config set registry https://registry.npmmirror.com
      - set NODE_OPTIONS=--openssl-legacy-provider
      - npm install
      - npm run build
      - ls /app/build/$DRONE_REPO_NAME/
      - echo $NODE_MODULES_PATH
      - cp -r dist /app/build/$DRONE_REPO_NAME


  - name: build-docker # 制作docker镜像
    image: 10.7.127.190:38080/docker/docker # 使用官方docker镜像
    volumes: # 将容器内目录挂载到宿主机
      - name: docker
        path: /var/run/docker.sock # 挂载宿主机的docker
      - name: config
        path: /config
    environment: # 获取到密文的docker用户名和密码
      DOCKER_USERNAME:
        from_secret: docker_username
      DOCKER_PASSWORD:
        from_secret: docker_password
      REGISTRY:
        from_secret: registry
      REGISTRY_NAMESPACE:
        from_secret: registry_namespace
    commands: # 定义在Docker容器中执行的shell命令
      - cat Dockerfile
      - sed -i 's/$REGISTRY/'"$REGISTRY"'/' deployment.yml
      - sed -i 's/$REGISTRY_NAMESPACE/'"$REGISTRY_NAMESPACE"'/' deployment.yml
      - sed -i 's/$DRONE_REPO_NAME/'"$DRONE_REPO_NAME"'/' deployment.yml
      - sed -i 's/$DRONE_COMMIT/'"$DRONE_COMMIT"'/' deployment.yml
      - sed -i 's/$PORTS_NAME/'"emosr-web"'/' deployment.yml
      - sed -i 's/$PORTS_PORT/'"8082"'/' deployment.yml
      # docker登录,不能在脚本中登录,并且不能使用docker login -u -p
      - echo $DOCKER_PASSWORD | docker login $REGISTRY --username $DOCKER_USERNAME --password-stdin
      - chmod +x docker.sh
      - cat docker.sh
      - sh docker.sh
      # 执行完脚本删除本次制作的docker镜像,避免多次后当前runner空间不足
      - docker rmi -f $(docker images | grep $DRONE_REPO_NAME | awk '{print $3}')


  - name: drone-rancher # rancher运行
    image: bitnami/kubectl:1.26.13-debian-11-r1
    volumes: # 将容器内目录挂载到宿主机
      - name: config
        path: /app/config # 将kubectl 配置文件挂载出来
    commands: # 定义在Docker容器中执行的shell命令
      # 将deployment中定义的变量替换为drone中的内置变量
      - kubectl apply -f deployment.yml -n emosr --kubeconfig=/app/config/base-taishan-kubectl.yml



volumes:
  - name: cache
    host:
      path: /home/npm/emosr-web
  - name: config # k8s对接的配置文件
    host:
      path: /home/kubect
  - name: docker # 宿主机中的docker
    host:
      path: /var/run/docker.sock

load:
trigger:
  branch:
    - prod
  event:
    - push
