kind: pipeline
type: docker
name: build-and-deploy

trigger:
  branch:
    - main
    - develop
  event:
    - push

steps:
  # 构建后端镜像
  - name: build-backend
    image: docker:dind
    volumes:
      - name: docker-sock
        path: /var/run/docker.sock
    commands:
      - docker build -t ai-interview-backend:${DRONE_COMMIT_SHA:0:8} -f deploy/Dockerfile.backend .
      - docker tag ai-interview-backend:${DRONE_COMMIT_SHA:0:8} ai-interview-backend:latest

  # 构建前端镜像
  - name: build-frontend
    image: docker:dind
    volumes:
      - name: docker-sock
        path: /var/run/docker.sock
    commands:
      - docker build -t ai-interview-frontend:${DRONE_COMMIT_SHA:0:8} -f deploy/Dockerfile.frontend .
      - docker tag ai-interview-frontend:${DRONE_COMMIT_SHA:0:8} ai-interview-frontend:latest

  # 部署到服务器
  - name: deploy
    image: docker:dind
    volumes:
      - name: docker-sock
        path: /var/run/docker.sock
    environment:
      COZE_PAT_TOKEN:
        from_secret: coze_pat_token
      COZE_BOT_ID:
        from_secret: coze_bot_id
      COZE_WORKFLOW_A_ID:
        from_secret: coze_workflow_a_id
      COZE_WORKFLOW_C_ID:
        from_secret: coze_workflow_c_id
      FILE_SERVER_URL:
        from_secret: file_server_url
      FILE_SERVER_TOKEN:
        from_secret: file_server_token
    commands:
      - docker stop ai-interview-backend ai-interview-frontend || true
      - docker rm ai-interview-backend ai-interview-frontend || true
      - docker run -d --name ai-interview-backend -p 8000:8000 --restart unless-stopped -e COZE_PAT_TOKEN=$COZE_PAT_TOKEN -e COZE_BOT_ID=$COZE_BOT_ID -e COZE_WORKFLOW_A_ID=$COZE_WORKFLOW_A_ID -e COZE_WORKFLOW_C_ID=$COZE_WORKFLOW_C_ID -e FILE_SERVER_URL=$FILE_SERVER_URL -e FILE_SERVER_TOKEN=$FILE_SERVER_TOKEN ai-interview-backend:latest
      - docker run -d --name ai-interview-frontend -p 3000:80 --restart unless-stopped ai-interview-frontend:latest
    when:
      branch:
        - main

volumes:
  - name: docker-sock
    host:
      path: /var/run/docker.sock
