# Tekton Git Clone Task for Bakery-IA CI/CD
# This task clones the source code repository

apiVersion: tekton.dev/v1beta1
kind: Task
metadata:
  name: git-clone
  namespace: {{ .Release.Namespace }}
  labels:
    app.kubernetes.io/name: {{ .Values.labels.app.name }}
    app.kubernetes.io/component: source
spec:
  workspaces:
    - name: output
      description: Workspace to clone the repository into
  params:
    - name: url
      type: string
      description: Repository URL to clone
    - name: revision
      type: string
      description: Git revision to checkout
      default: "main"
    - name: depth
      type: string
      description: Git clone depth (0 for full history, minimum 2 for change detection)
      default: "10"
  results:
    - name: commit-sha
      description: The commit SHA that was checked out
    - name: commit-message
      description: The commit message
  steps:
    - name: clone
      image: alpine/git:2.43.0
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        allowPrivilegeEscalation: false
        capabilities:
          drop:
            - ALL
        seccompProfile:
          type: RuntimeDefault
      env:
        - name: HOME
          value: /tekton/home
      script: |
        #!/bin/sh
        set -e

        URL="$(params.url)"
        REVISION="$(params.revision)"
        DEPTH="$(params.depth)"
        OUTPUT_PATH="$(workspaces.output.path)"

        echo "============================================"
        echo "Git Clone Task"
        echo "============================================"
        echo "URL: $URL"
        echo "Revision: $REVISION"
        echo "Depth: $DEPTH"
        echo "============================================"

        # Mark workspace as safe directory to avoid ownership issues
        git config --global --add safe.directory "$OUTPUT_PATH"

        # Clone with depth for faster checkout
        # Note: We need at least 2 commits for change detection (current + parent)
        if [ "$DEPTH" = "0" ]; then
          echo "Cloning full repository..."
          git clone "$URL" "$OUTPUT_PATH"
        else
          echo "Cloning with depth $DEPTH..."
          git clone --depth "$DEPTH" "$URL" "$OUTPUT_PATH"
        fi

        cd "$OUTPUT_PATH"

        # If revision is a specific commit SHA (40 hex chars), we need special handling
        if echo "$REVISION" | grep -qE '^[0-9a-f]{40}$'; then
          echo "Revision is a commit SHA: $REVISION"

          # Check if commit is already in the clone
          if ! git cat-file -e "$REVISION" 2>/dev/null; then
            echo "Commit not in shallow clone, fetching with history..."
            # Fetch more history to include the specific commit
            git fetch --deepen="$DEPTH" origin main 2>/dev/null || true
            git fetch origin "$REVISION" 2>/dev/null || true
          fi

          # Ensure we have the parent commit for change detection
          PARENT_SHA=$(git rev-parse "$REVISION^" 2>/dev/null || echo "")
          if [ -z "$PARENT_SHA" ]; then
            echo "Parent commit not available, deepening history..."
            git fetch --deepen=10 origin 2>/dev/null || true
          fi
        elif [ "$REVISION" != "main" ] && [ "$REVISION" != "master" ]; then
          echo "Fetching branch/tag: $REVISION"
          git fetch --depth "$DEPTH" origin "$REVISION" 2>/dev/null || true
        fi

        # Checkout the revision
        echo "Checking out: $REVISION"
        git checkout "$REVISION" 2>/dev/null || git checkout "origin/$REVISION" 2>/dev/null || git checkout FETCH_HEAD

        # Verify we have enough history for change detection
        COMMIT_COUNT=$(git rev-list --count HEAD 2>/dev/null || echo "0")
        echo "Commits available after checkout: $COMMIT_COUNT"
        if [ "$COMMIT_COUNT" -lt 2 ]; then
          echo "Warning: Not enough history, fetching more..."
          git fetch --deepen=10 origin 2>/dev/null || true
          COMMIT_COUNT=$(git rev-list --count HEAD 2>/dev/null || echo "0")
          echo "Commits available after deepen: $COMMIT_COUNT"
        fi

        # Get commit info
        COMMIT_SHA=$(git rev-parse HEAD)
        COMMIT_MSG=$(git log -1 --pretty=format:"%s")

        echo ""
        echo "============================================"
        echo "Clone Complete"
        echo "============================================"
        echo "Commit: $COMMIT_SHA"
        echo "Message: $COMMIT_MSG"
        echo "============================================"

        # Write results
        echo -n "$COMMIT_SHA" > $(results.commit-sha.path)
        echo -n "$COMMIT_MSG" > $(results.commit-message.path)
      resources:
        limits:
          cpu: 500m
          memory: 512Mi
        requests:
          cpu: 100m
          memory: 128Mi