name: itom-platform auto build image

on:
  push:
    branches:
      - dev
  workflow_dispatch: {}

permissions:
  contents: read
  packages: write

jobs:
  build:
    runs-on: openim

    env:
      REGISTRY: git.imall.cloud
      IMAGE: git.imall.cloud/itom-group/open-im-server-deploy
    steps:
      - name: Install git
        shell: sh
        run: |
          set -eu
          if ! command -v git >/dev/null 2>&1; then
            apk add --no-cache git openssh-client ca-certificates
          fi

      - name: Checkout
        shell: sh
        env:
          GIT_USER: ${{ secrets.GIT_USER }}
          GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
          REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
          REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
        run: |
          set -eu
          WORKDIR="${GITHUB_WORKSPACE:-/workspace}"
          mkdir -p "$WORKDIR"
          REPO="${GITHUB_REPOSITORY:-${GITEA_REPOSITORY:-}}"
          SERVER="${GITHUB_SERVER_URL:-${GITEA_SERVER_URL:-https://git.imall.cloud}}"
          if [ -z "$REPO" ]; then
            echo "ERROR: missing repository info."
            exit 1
          fi
          USER=""
          TOKEN=""
          if [ -n "${GIT_USER:-}" ] && [ -n "${GIT_TOKEN:-}" ]; then
            USER="$GIT_USER"
            TOKEN="$GIT_TOKEN"
          elif [ -n "${GITEA_TOKEN:-}" ]; then
            USER="${GITEA_ACTOR:-${FORGEJO_ACTOR:-${GITHUB_ACTOR:-}}}"
            TOKEN="$GITEA_TOKEN"
          elif [ -n "${FORGEJO_TOKEN:-}" ]; then
            USER="${FORGEJO_ACTOR:-${GITHUB_ACTOR:-}}"
            TOKEN="$FORGEJO_TOKEN"
          elif [ -n "${GITHUB_TOKEN:-}" ]; then
            USER="${GITHUB_ACTOR:-}"
            TOKEN="$GITHUB_TOKEN"
          elif [ -n "${REGISTRY_USER:-}" ] && [ -n "${REGISTRY_PASSWORD:-}" ]; then
            USER="$REGISTRY_USER"
            TOKEN="$REGISTRY_PASSWORD"
          fi
          if [ -n "$TOKEN" ]; then
            if [ -z "$USER" ]; then
              echo "ERROR: missing git username for token auth."
              exit 1
            fi
            AUTH_HOST="${SERVER#https://}"
            AUTH_HOST="${AUTH_HOST#http://}"
            git clone "https://${USER}:${TOKEN}@${AUTH_HOST}/${REPO}.git" "$WORKDIR"
          else
            git clone "${SERVER}/${REPO}.git" "$WORKDIR"
          fi
          cd "$WORKDIR"
          SHA="${GITHUB_SHA:-${GITEA_SHA:-}}"
          if [ -n "$SHA" ]; then
            git checkout "$SHA"
          fi

      - name: Prepare tags
        shell: sh
        run: |
          set -eu
          BRANCH="${GITHUB_REF_NAME:-${GITEA_REF_NAME:-}}"
          if [ -z "$BRANCH" ]; then
            BRANCH="$(echo "${GITHUB_REF:-${GITEA_REF:-}}" | sed 's#.*/##')"
          fi
          BRANCH="$(echo "$BRANCH" | tr '/' '-')"
          SHA="${GITHUB_SHA:-${GITEA_SHA:-}}"
          SHA_SHORT="$(printf '%s' "$SHA" | cut -c1-7)"
          echo "BRANCH=$BRANCH" >> "$GITHUB_ENV"
          echo "SHA_SHORT=$SHA_SHORT" >> "$GITHUB_ENV"

      - name: Resolve Dockerfile
        shell: sh
        run: |
          set -eu
          DOCKERFILE_PATH="${DOCKERFILE_PATH:-}"
          BUILD_CONTEXT="${BUILD_CONTEXT:-.}"
          if [ -z "$DOCKERFILE_PATH" ]; then
            for candidate in Dockerfile docker/Dockerfile .docker/Dockerfile build/Dockerfile api/Dockerfile api/docker/Dockerfile; do
              if [ -f "$candidate" ]; then
                DOCKERFILE_PATH="$candidate"
                break
              fi
            done
          fi
          if [ -z "$DOCKERFILE_PATH" ]; then
            echo "ERROR: Dockerfile not found. Set DOCKERFILE_PATH or add Dockerfile."
            exit 1
          fi
          echo "DOCKERFILE_PATH=$DOCKERFILE_PATH" >> "$GITHUB_ENV"
          echo "BUILD_CONTEXT=$BUILD_CONTEXT" >> "$GITHUB_ENV"


      - name: Login registry
        shell: sh
        env:
          GIT_USER: ${{ secrets.GIT_USER }}
          GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
          REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
          REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
          AUTO_REGISTRY_USER: ${{ secrets.DOCKER_USERNAME }}
          AUTO_REGISTRY_PASS: ${{ secrets.DOCKER_PASSWORD }}

        run: |
          set -eu
          login_try() {
            local user="$1"
            local pass="$2"
            local label="$3"
            if [ -z "$user" ] || [ -z "$pass" ]; then
              return 1
            fi
            if echo "$pass" | docker login "$REGISTRY" -u "$user" --password-stdin >/dev/null 2>&1; then
              echo "Registry login ok ($label)"
              return 0
            fi
            return 1
          }

          if login_try "$REGISTRY_USER" "$REGISTRY_PASSWORD" "REGISTRY_USER"; then
            exit 0
          fi
          if login_try "$GIT_USER" "$GIT_TOKEN" "GIT_USER"; then
            exit 0
          fi
          if login_try "${AUTO_REGISTRY_USER:-}" "${AUTO_REGISTRY_PASS:-}" "AUTO_REGISTRY"; then
            exit 0
          fi

          ACTOR="${GITEA_ACTOR:-${FORGEJO_ACTOR:-${GITHUB_ACTOR:-}}}"
          JOB_TOKEN="${GITEA_TOKEN:-${FORGEJO_TOKEN:-${GITHUB_TOKEN:-}}}"
          if login_try "$ACTOR" "$JOB_TOKEN" "JOB_TOKEN"; then
            exit 0
          fi

          echo "ERROR: registry login failed. Provide REGISTRY_USER/REGISTRY_PASSWORD or GIT_USER/GIT_TOKEN with packages write permission."
          exit 1

      - name: Build and push images
        shell: sh
        env:
          GIT_USER: ${{ secrets.GIT_USER }}
          GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
          REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
          REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
        run: |
          set -eu
          cd "${GITHUB_WORKSPACE:-/workspace}"
          IMAGE_BRANCH_TAG="$IMAGE:${BRANCH}"
          IMAGE_SHA_TAG="$IMAGE:sha-${SHA_SHORT}"
          docker build \
            --build-arg GIT_USER="${GIT_USER:-}" \
            --build-arg GIT_TOKEN="${GIT_TOKEN:-}" \
            --build-arg REGISTRY_USER="${REGISTRY_USER:-}" \
            --build-arg REGISTRY_PASSWORD="${REGISTRY_PASSWORD:-}" \
            -t "$IMAGE_BRANCH_TAG" -t "$IMAGE_SHA_TAG" -f "$DOCKERFILE_PATH" "$BUILD_CONTEXT"

          log_image() {
            local tag="$1"
            echo "== Image info: $tag =="
            docker image inspect --format 'Image ID: {{.Id}} Size: {{.Size}}' "$tag" || true
          }

          log_layers() {
            local tag="$1"
            echo "== RootFS layers (base -> top): $tag =="
            docker image inspect --format '{{range $i, $layer := .RootFS.Layers}}{{println $i $layer}}{{end}}' "$tag" || true
          }

          log_history() {
            local tag="$1"
            echo "== Image history (top -> base): $tag =="
            docker history --no-trunc "$tag" | head -n 80 || true
            echo "== (history truncated to 80 lines) =="
          }

          log_image "$IMAGE_BRANCH_TAG"
          log_layers "$IMAGE_BRANCH_TAG"
          log_history "$IMAGE_BRANCH_TAG"

          push_with_diag() {
            local tag="$1"
            local safe_tag
            safe_tag=$(echo "$tag" | tr '/:' '__')
            local log_file="/tmp/docker-push-${safe_tag}.log"
            echo "== docker push $tag =="
            if docker push "$tag" >"$log_file" 2>&1; then
              tail -n 5 "$log_file" || true
              return 0
            fi
              log_image "$tag"
              log_layers "$tag"
              log_history "$tag"
              echo "== Docker system info =="
              docker info || true
              echo "== Disk usage (df -h) =="
              df -h || true
              echo "== Docker disk usage =="
              docker system df -v | head -n 200 || true
              echo "== Push failed (tail) for $tag =="
              tail -n 200 "$log_file" || true
              exit 1
          }

          push_with_diag "$IMAGE_BRANCH_TAG"
          push_with_diag "$IMAGE_SHA_TAG"
