name: Release

on:
  push:
    branches:
      - main

env:
  APP_NAME: blog
  NAMESPACE: app
  REGISTRY: ${{ secrets.DOCKER_REGISTRY && secrets.DOCKER_REGISTRY || 'docker.io' }}
  REPOSITORY: ${{ github.repository }}
  DOMAIN: blog.icodef.com
  ENV: ${{ startsWith(github.ref, 'refs/heads/release/') && 'pre' || startsWith(github.ref, 'refs/heads/test/') && 'test' || github.ref=='refs/heads/main' && 'prod' }}
  RUNNER_TOOL_CACHE: /toolcache
  BASEIMAGE: ${{ secrets.BASEIMAGE && secrets.BASEIMAGE || '' }}


jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0

    - name: Use Node.js
      uses: actions/setup-node@v4.1.1
      with:
        node-version: "20.x"
        cache: 'npm'

    - name: Build
      run: |
        npm ci
        npm run build

    - name: Set up QEMU
#      uses: docker/setup-qemu-action@v3
      uses: actions/setup-qemu-action@v3

    - name: Set up Docker Buildx
#      uses: docker/setup-buildx-action@v3
      uses: actions/setup-buildx-action@v3

    - name: Login to Docker Hub
#      uses: docker/login-action@v3
      uses: actions/login-action@v1
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ secrets.DOCKER_USERNAME }}
        password: ${{ secrets.DOCKER_TOKEN }}

    - name: Set outputs
      id: vars
      run: |
        echo "sha_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT

    - name: Docker build and push
#      use: docker/build-push-action@v5
      uses: actions/build-push-action@v5
      with:
        push: true
        file: deploy/docker/Dockerfile
        tags: ${{ env.REGISTRY }}/${{ env.REPOSITORY }}:${{ steps.vars.outputs.sha_short }}
        context: .
        build-args: |
          BASEIMAGE=${{ env.BASEIMAGE }}/nginx:1.25

    - name: Set up kubeconfig
#      uses: azure/k8s-set-context@v3
      uses: actions/k8s-set-context@v3
      with:
        method: kubeconfig
        kubeconfig: ${{ secrets.KUBE_CONFIG }}
        context: k8s-context

    - name: Set up Helm
#      uses: azure/setup-helm@v3
      uses: actions/setup-helm@v3.6
      with:
         version: 'v3.13.1' # default is latest (stable)

    - name: Deploy ${{ env.ENV }}
      env:
        RESOURCE_CPU: ${{ env.ENV=='prod' && '100m' || '50m' }}
        RESOURCE_MEMORY: ${{ env.ENV=='prod' && '256Mi' || '128Mi' }}
      run: |
        cd deploy/helm
        helm upgrade --install \
        --namespace $NAMESPACE $APP_NAME . \
        -f values.yaml \
        --set image.tag=${{ steps.vars.outputs.sha_short }} \
        --set image.repository=$REGISTRY/$REPOSITORY \
        --set resources.requests.cpu=$RESOURCE_CPU \
        --set resources.requests.memory=$RESOURCE_MEMORY
        