name: Docker Build

on:
  push:
    branches:
      - main
  pull_request:
  workflow_dispatch:

permissions:
  contents: read
  packages: write

env:
  REGISTRY: gitea.mouse84.com
  IMAGE_NAME: kim.kanghee/idrac-info
  DOCKERFILE: Dockerfile
  BUILD_CONTEXT: .

jobs:
  docker-build:
    name: Build Docker image
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        shell: bash
        run: |
          git init .
          git remote add origin "${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}.git"
          git fetch --depth 1 origin "${GITHUB_REF}"
          git checkout --force "${GITHUB_SHA}"

      - name: Prepare Docker tag
        shell: bash
        run: |
          SHORT_SHA="$(printf '%s' "${GITHUB_SHA:-local}" | cut -c1-12)"
          IMAGE_REPO="${REGISTRY}/${IMAGE_NAME}"
          echo "IMAGE_REPO=${IMAGE_REPO}" >> "${GITHUB_ENV}"
          echo "IMAGE_TAG=${IMAGE_REPO}:${SHORT_SHA}" >> "${GITHUB_ENV}"
          echo "IMAGE_LATEST=${IMAGE_REPO}:latest" >> "${GITHUB_ENV}"
          echo "SHORT_SHA=${SHORT_SHA}" >> "${GITHUB_ENV}"

      - name: Show Docker version
        run: docker version

      - name: Validate iDRAC Tools packages
        shell: bash
        run: |
          test -f iDRACTools/racadm/UBUNTU24/x86_64/srvadmin-hapi_11.4.0.0_amd64.deb
          test -f iDRACTools/racadm/UBUNTU24/x86_64/srvadmin-idracadm7_11.4.0.0_all.deb
          test -f iDRACTools/racadm/UBUNTU24/x86_64/srvadmin-idracadm8_11.4.0.0_amd64.deb
          test -f iDRACTools/ipmitool/UBUNTU24_x86_64/ipmitool_1.8.18_amd64.deb

      - name: Build Docker image
        run: |
          docker build \
            --pull \
            --file "${DOCKERFILE}" \
            --tag "${IMAGE_TAG}" \
            --tag "${IMAGE_LATEST}" \
            "${BUILD_CONTEXT}"

      - name: Inspect built image
        run: |
          docker image inspect "${IMAGE_TAG}" > /dev/null
          docker images "${IMAGE_REPO}"

      - name: Login to Gitea Container Registry
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        shell: bash
        run: |
          REGISTRY_USERNAME="${{ secrets.REGISTRY_USERNAME }}"
          REGISTRY_PASSWORD="${{ secrets.REGISTRY_TOKEN }}"

          if [ -z "${REGISTRY_USERNAME}" ]; then
            REGISTRY_USERNAME="${{ github.actor }}"
          fi

          if [ -z "${REGISTRY_PASSWORD}" ]; then
            REGISTRY_PASSWORD="${{ secrets.GITHUB_TOKEN }}"
          fi

          if [ -z "${REGISTRY_PASSWORD}" ]; then
            echo "REGISTRY_TOKEN or GITHUB_TOKEN is required for docker login." >&2
            exit 1
          fi

          echo "${REGISTRY_PASSWORD}" | docker login "${REGISTRY}" \
            --username "${REGISTRY_USERNAME}" \
            --password-stdin

      - name: Push Docker image
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        run: |
          docker push "${IMAGE_TAG}"
          docker push "${IMAGE_LATEST}"
