on:
  push:
    branches:
    - main
    - dev
env:
  NAMESPACE: ${{ github.repository_owner }}
  DOCKER_REGISTRY: ghcr.io
  DOCKER_REPOSITORY: ${{ github.repository }}
jobs:
  build-and-deploy:
    env:
      IMAGE: ${{ env.DOCKER_REGISTRY }}/${{ env.DOCKER_REPOSITORY }}
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Install kpack-cli
      env:
        KPACK_CLI_VERSION: 0.13.0
        KPACK_CLI_SHA256: 52f0c927a1350f4f1bb281575ec246f406fb96aa69dc974ed10a2fe52c538158
      working-directory: /tmp
      run: |
        set -ex
        curl -sLO "https://github.com/buildpacks-community/kpack-cli/releases/download/v${KPACK_CLI_VERSION}/kp-linux-amd64-${KPACK_CLI_VERSION}"
        echo "${KPACK_CLI_SHA256} kp-linux-amd64-${KPACK_CLI_VERSION}" | sha256sum --check || exit 1
        sudo mv kp-linux-amd64-${KPACK_CLI_VERSION} /usr/local/bin/kp
        sudo chmod +x /usr/local/bin/kp
        kp version
    - name: Install kubectl
      uses: azure/setup-kubectl@v4
    - name: Configure kubectl
      uses: azure/k8s-set-context@v1
      with:
        kubeconfig: ${{ secrets.KUBE_CONFIG }}
    - name: Update kpack image
      env:
        SHA: ${{ github.sha }}
      run: |
        SHORT_SHA=$(git rev-parse --short HEAD)
        echo "SHORT_SHA=${SHORT_SHA}" >> $GITHUB_ENV
        IMAGE_NAME="${GITHUB_REPOSITORY#$GITHUB_REPOSITORY_OWNER/}-${GITHUB_REF##*/}"
        echo "IMAGE_NAME=${IMAGE_NAME}" >> $GITHUB_ENV
        kp image patch $IMAGE_NAME --replace-additional-tag "${IMAGE}:sha-${SHORT_SHA}" --git-revision "${SHA}" -n $NAMESPACE
        kp image status $IMAGE_NAME -n $NAMESPACE
    - name: Wait for build to complete
      run: |
        BUILD=$(kubectl -n $NAMESPACE get image $IMAGE_NAME -o jsonpath='{.status.buildCounter}')
        BUILD_REF=$(kubectl -n $NAMESPACE get image $IMAGE_NAME -o jsonpath='{.status.latestBuildRef}')
        kp build logs $IMAGE_NAME -n $NAMESPACE --build ${BUILD}
        kp build status $IMAGE_NAME -n $NAMESPACE -b $BUILD
        if [ "$(kubectl -n $NAMESPACE get build $BUILD_REF -o jsonpath='{.status.conditions[0].status}')" != "True" ]; then exit 1; fi
#    - name: Update Kubernetes deployment
#      run: |
#        kubectl set image deployment/my-app my-app=<registry>/<repository>:${{ github.sha }}
