---
kind: pipeline
type: docker
name: catlink-ci

# Trigger настройки
trigger:
  branch:
    - master
    - main
    - develop
  event:
    - push
    - pull_request

# Глобальные переменные
environment:
  DOCKER_BUILDKIT: 1
  COMPOSE_DOCKER_CLI_BUILD: 1

# Этапы пайплайна
steps:
  # 1. Установка зависимостей и подготовка
  - name: prepare
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    commands:
      - apk add --no-cache make curl git bash
      - docker --version
      - echo "Repository:$${DRONE_REPO}"
      - echo "Branch:$${DRONE_BRANCH}"
      - echo "Commit:$${DRONE_COMMIT_SHA:0:8}"
      - chmod +x scripts/ci/*.sh

  # 2. Линтинг и проверка кода
  - name: lint
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    commands:
      - echo "🔍 Running code quality checks..."
      - echo "Current directory:" $(pwd)
      - echo "Directory contents:" && ls -la
      - echo "CI scripts directory:" && ls -la scripts/ci/ || echo "CI scripts directory not found"
      - if [ -f scripts/ci/lint.sh ]; then 
          echo "Found lint.sh, checking permissions and executing...";
          ls -la scripts/ci/lint.sh;
          chmod +x scripts/ci/lint.sh;
          bash scripts/ci/lint.sh;
        elif [ -f scripts/ci/lint-simple.sh ]; then
          echo "Found lint-simple.sh, checking permissions and executing...";
          ls -la scripts/ci/lint-simple.sh;
          chmod +x scripts/ci/lint-simple.sh;
          bash scripts/ci/lint-simple.sh;
        else
          echo "⚠️ No lint script found, running basic checks...";
          apk add --no-cache git;
          echo "Project structure check:";
          ls -la;
          echo "Python files:" $(find . -name "*.py" | wc -l);
          echo "JS/TS files:" $(find . -name "*.js" -o -name "*.ts" -o -name "*.tsx" | wc -l);
        fi
    depends_on:
      - prepare

  # 3. Сборка приложения
  - name: build
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    commands:
      - echo "🏗️ Building application..."
      - if [ -f scripts/ci/build.sh ]; then 
          echo "Found build.sh, executing...";
          chmod +x scripts/ci/build.sh;
          bash scripts/ci/build.sh;
        elif [ -f scripts/ci/build-simple.sh ]; then
          echo "Found build-simple.sh, executing...";
          chmod +x scripts/ci/build-simple.sh;
          bash scripts/ci/build-simple.sh;
        else
          echo "⚠️ No build script found, running basic checks...";
          apk add --no-cache docker-compose;
          if [ -f docker-compose.yml ]; then
            echo "✅ docker-compose.yml found";
            docker-compose config --quiet && echo "✅ Valid" || echo "❌ Invalid";
          else
            echo "⚠️ docker-compose.yml not found";
          fi;
        fi
    depends_on:
      - lint

  # 4. Тестирование
  - name: test
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    environment:
      DATABASE_URL: postgres://catlink:catlink@postgres:5432/catlink_test
    commands:
      - echo "🧪 Running tests..."
      - if [ -f scripts/ci/test.sh ]; then 
          echo "Found test.sh, executing...";
          chmod +x scripts/ci/test.sh;
          bash scripts/ci/test.sh;
        elif [ -f scripts/ci/test-simple.sh ]; then
          echo "Found test-simple.sh, executing...";
          chmod +x scripts/ci/test-simple.sh;
          bash scripts/ci/test-simple.sh;
        else
          echo "⚠️ No test script found, running basic checks...";
          echo "Looking for test files:";
          find . -name "*test*.py" -o -name "test_*.py" | head -5;
          echo "Django manage.py:" $([ -f backend/manage.py ] && echo "✅ Found" || echo "❌ Missing");
        fi
    depends_on:
      - build

  # 5. Анализ безопасности
  - name: security-scan
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    commands:
      - echo "🔒 Running security scans..."
      - if [ -f scripts/ci/security-scan.sh ]; then 
          echo "Found security-scan.sh, executing...";
          chmod +x scripts/ci/security-scan.sh;
          bash scripts/ci/security-scan.sh;
        else
          echo "⚠️ No security script found, running basic checks...";
          apk add --no-cache grep;
          echo "Checking for sensitive files:";
          find . -name ".env" -o -name "*.key" -o -name "*.pem" | head -5;
          echo "Basic security scan completed";
        fi
    depends_on:
      - test
    failure: ignore  # Не останавливаем пайплайн при проблемах безопасности

  # 6. Сборка Docker образов для продакшена
  - name: build-production
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    commands:
      - echo "🚀 Building production images..."
      - if [ -f scripts/ci/build-production.sh ]; then 
          echo "Found build-production.sh, executing...";
          chmod +x scripts/ci/build-production.sh;
          bash scripts/ci/build-production.sh;
        else
          echo "⚠️ build-production.sh not found, skipping production build";
          echo "To enable production builds, create scripts/ci/build-production.sh";
        fi
      - docker images | grep catlink || echo "No catlink images found"
    depends_on:
      - security-scan
    when:
      branch:
        - master
        - main
    failure: ignore

  # 7. Публикация артефактов
  - name: publish
    image: docker:20.10-dind
    volumes:
      - name: docker
        path: /var/run/docker.sock
    commands:
      - echo "📦 Publishing artifacts..."
      - if [ -f scripts/ci/publish.sh ]; then 
          echo "Found publish.sh, executing...";
          chmod +x scripts/ci/publish.sh;
          bash scripts/ci/publish.sh;
        else
          echo "⚠️ publish.sh not found, skipping artifact publishing";
          echo "To enable publishing, create scripts/ci/publish.sh";
        fi
    depends_on:
      - build-production
    when:
      branch:
        - master
        - main
    failure: ignore

  # 8. Развертывание в staging
  - name: deploy-staging
    image: alpine/curl:latest
    commands:
      - echo "🚀 Deploying to staging..."
      - if [ -f scripts/ci/deploy-staging.sh ]; then 
          echo "Found deploy-staging.sh, executing...";
          chmod +x scripts/ci/deploy-staging.sh;
          bash scripts/ci/deploy-staging.sh;
        else
          echo "⚠️ deploy-staging.sh not found";
          echo "Staging deployment would happen here if script exists";
          echo "Create scripts/ci/deploy-staging.sh to enable staging deployments";
        fi
    depends_on:
      - publish
    when:
      branch:
        - develop
        - staging
    failure: ignore

    # 9. Развертывание в production
  - name: deploy-production
    image: alpine/curl:latest
    commands:
      - echo "🚀 Deploying to production..."
      - if [ -f scripts/ci/deploy-production.sh ]; then 
          echo "Found deploy-production.sh, executing...";
          chmod +x scripts/ci/deploy-production.sh;
          bash scripts/ci/deploy-production.sh;
        else
          echo "⚠️ deploy-production.sh not found";
          echo "Production deployment would happen here if script exists";
          echo "Create scripts/ci/deploy-production.sh to enable production deployments";
        fi
    depends_on:
      - publish
    when:
      branch:
        - master
        - main
    failure: ignore

  # 10. Простые уведомления в логах
  - name: notify-console
    image: alpine:latest
    commands:
      - |
        if [ "$${DRONE_BUILD_STATUS}" = "success" ]; then
          echo "✅ BUILD SUCCESS!"
          echo "📁 Repository: $${DRONE_REPO}"
          echo "🌿 Branch: $${DRONE_BRANCH}"
          echo "👤 Author: $${DRONE_COMMIT_AUTHOR}"
          echo "📝 Commit: $${DRONE_COMMIT_SHA:0:8}"
          echo "🕐 Duration: $$(date -d @$${DRONE_BUILD_STARTED} '+%H:%M:%S')"
        else
          echo "❌ BUILD FAILED!"
          echo "📁 Repository: $${DRONE_REPO}"
          echo "🌿 Branch: $${DRONE_BRANCH}"
          echo "👤 Author: $${DRONE_COMMIT_AUTHOR}"
          echo "📝 Commit: $${DRONE_COMMIT_SHA:0:8}"
        fi
    depends_on:
      - deploy-production
      - deploy-staging
    when:
      status:
        - success
        - failure

# Сервисы для тестирования
services:
  # PostgreSQL для тестов
  - name: postgres
    image: postgres:14-alpine
    environment:
      POSTGRES_DB: catlink_test
      POSTGRES_USER: catlink
      POSTGRES_PASSWORD: catlink
      POSTGRES_HOST_AUTH_METHOD: trust
    tmpfs:
      - /var/lib/postgresql/data

  # Redis для кеширования (если потребуется)
  - name: redis
    image: redis:7-alpine

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

---
# Пайплайн для релизов
kind: pipeline
type: docker
name: release

steps:
  - name: create-release
    image: plugins/github-release
    settings:
      api_key:
        from_secret: github_token
      title: "CatLink v${DRONE_TAG}"
      note: "Release ${DRONE_TAG}"
      files:
        - "dist/*"
      checksum:
        - md5
        - sha1
        - sha256

trigger:
  event:
    - tag

---
# Signature для верификации (если используется)
kind: signature
hmac: <your-hmac-signature-here>