name: Deploy Staging

on:
  workflow_dispatch:
    inputs:
      environment:
        description: Environment to deploy to
        required: true
        default: staging
      version:
        description: Version to deploy (default is latest)
        required: false
        default: latest
        type: choice
        options:
          - latest
      logLevel:
        description: Log level
        required: false
        default: info
        type: choice
        options:
          - info
          - debug
          - warning

jobs:
  get_available_versions:
    name: Get available versions
    runs-on: ubuntu-22.04
    outputs:
      version_options: ${{ steps.get_versions.outputs.version_options }}
    steps:
      - name: Get available versions from Docker Registry
        id: get_versions
        env:
          REGISTRY: docker.io
          REPO: test-deploy
        run: |
          TOKEN=$(curl -s -u "${{ secrets.DOCKER_USERNAME }}:${{ secrets.DOCKER_PASSWORD }}" \
            "https://$REGISTRY/v2/token?service=$REGISTRY&scope=repository:$REPO:pull" | jq -r .token)

          TAGS=$(curl -s -H "Authorization: Bearer $TOKEN" \
            "https://$REGISTRY/v2/$REPO/tags/list" | jq -r '.tags[] | select(. != "latest")' | sort -rV | head -10 | tr '\n' ',')

          echo "version_options=latest,${TAGS%,}" >> $GITHUB_OUTPUT

          echo "Tags: $TAGS"
          echo "Version options: $version_options"

  deploy_to_staging:
    name: Deploy to Staging
    runs-on: ubuntu-22.04

    env:
      STACK_NAME: molvaapp-${{ inputs.environment }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Extract Git metadata
        id: git-metadata
        run: |
          echo "GIT_SHA=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
          echo "GIT_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo 'none')" >> $GITHUB_OUTPUT

      - name: Login to Docker Registry
        run: |
          echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin

      - name: Build and Push Docker Image
        needs: git-metadata
        env:
          IMAGE_NAME: molvaapp/test_deploy
          CONFIG_FILE: .build/config/staging.yaml
        run: |
          IMAGE_TAG=${{ inputs.environment }}-${{ steps.git-metadata.outputs.GIT_TAG != 'none' && steps.git-metadata.outputs.GIT_TAG || steps.git-metadata.outputs.GIT_SHA }}

          docker build \
            --build-arg BUILD_LDFLAGS="-w -s" \
            --build-arg CONFIG_FILE_PATH=$CONFIG_FILE \
            -t $IMAGE_NAME:$IMAGE_TAG \
            -t $IMAGE_NAME:latest \
            .

          docker tag $IMAGE_NAME:$IMAGE_TAG $IMAGE_NAME:latest

          docker push $IMAGE_NAME:$IMAGE_TAG
          docker push $IMAGE_NAME:latest

          echo "Pushed image $IMAGE_NAME:$IMAGE_TAG and :latest"

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y gettext jq

      - name: Prepare environment
        run: |
          mkdir -p /tmp/swarm-certs
          echo "${{ secrets.SWARM_CA_PEM }}" > /tmp/swarm-certs/ca.pem
          echo "${{ secrets.SWARM_CERT_PEM }}" > /tmp/swarm-certs/cert.pem
          echo "${{ secrets.SWARM_KEY_PEM }}" > /tmp/swarm-certs/key.pem
          chmod 600 /tmp/swarm-certs/*.pem

      - name: Deploy to Swarm
        env:
          DOCKER_HOST: tcp://${{ secrets.SWARM_MANAGER_HOST }}:2376
          DOCKER_TLS_VERIFY: 1
          DOCKER_CERT_PATH: /tmp/swarm-certs

          VERSION: ${{ inputs.version }}

          KEYCLOAK_BASE_URL: ${{ secrets.KEYCLOAK_BASE_URL }}
          KEYCLOAK_REALM: ${{ secrets.KEYCLOAK_REALM }}
          KEYCLOAK_CLIENT_ID: ${{ secrets.KEYCLOAK_CLIENT_ID }}
          KEYCLOAK_CLIENT_SECRET: ${{ secrets.KEYCLOAK_CLIENT_SECRET }}

          BROKER_HOST: ${{ secrets.BROKER_HOST }}
          BROKER_PORT: ${{ secrets.BROKER_PORT }}
          BROKER_USERNAME: ${{ secrets.BROKER_USERNAME }}
          BROKER_PASSWORD: ${{ secrets.BROKER_PASSWORD }}

          SHORTENER_SECRET_KEY: ${{ secrets.SHORTENER_SECRET_KEY }}

          CACHE_ADDRS: ${{ secrets.CACHE_ADDRS }}
          CACHE_PASSWORD: ${{ secrets.CACHE_PASSWORD }}

          DB_HOSTS: ${{ secrets.DB_HOSTS }}
          DB_PORT: ${{ secrets.DB_PORT }}
          DB_USERNAME: ${{ secrets.DB_STG_USERNAME }}
          DB_PASSWORD: ${{ secrets.DB_STG_PASSWORD }}
          DB_DBNAME: ${{ secrets.DB_DBNAME }}

          INTEGRATION_VKUSVILL_API_TOKEN: ${{ secrets.INTEGRATION_VKUSVILL_API_TOKEN }}
        run: |
          envsubst < docker-compose.staging.yaml > docker-compose.runtime.yaml

          echo "Deploying version $VERSION to ${{ inputs.environment }}..."
          echo "Log level: ${{ inputs.logLevel }}"

          docker stack deploy \
            --with-registry-auth \
            -c docker-compose.runtime.yaml \
            ${{ env.STACK_NAME }}

      - name: Cleanup
        run: |
          rm -rf /tmp/swarm-certs
          rm -f docker-compose.runtime.yaml

      - name: Post-deploy
        run: |
          echo "Deployment to ${{ inputs.environment }} completed."
          echo "Version deployed: ${{ inputs.version }}"
