name: "02 - Steampipe: Build and Publish DB Image"

# Controls when the action will run.
on:
  workflow_dispatch:
    inputs:
      version:
        description: |
          Version number for the OCI image for this release - usually the same as the
          postgres version
        required: true
        default: 14.19.0

      postgres_version:
        description: "Postgres Version to package (eg 14.2.0)"
        required: true
        default: 14.19.0

env:
  PROJECT_ID: steampipe
  IMAGE_NAME: db
  CORE_REPO: ghcr.io/turbot/steampipe
  ORG: turbot
  CONFIG_SCHEMA_VERSION: "2020-11-18"
  VERSION: ${{ github.event.inputs.version }}
  PG_VERSION: ${{ github.event.inputs.postgres_version }}
  PATH_BASE: https://repo1.maven.org/maven2/io/zonky/test/postgres
  NAME_PREFIX: embedded-postgres-binaries
  STEAMPIPE_UPDATE_CHECK: false
  ORAS_VERSION: 1.1.0

jobs:
  # This workflow contains a single job called "build"
  build:
    name: Build and Publish DB Image
    # The type of runner that the job will run on
    runs-on: ubuntu-latest
    # Steps represent a sequence of tasks that will be executed as part of the job
    steps:
      - name: Trim asset version prefix and Validate
        run: |-
          echo $VERSION
          trim=${VERSION#"v"}
          echo $trim
          if [[ $trim =~  ^[0-9]+\.[0-9]+\.[0-9]+(-.+)?$ ]]; then
            echo "Version OK: $trim"
          else
            echo "Invalid version: $trim"
            exit 1
          fi
          echo "VERSION=${trim}" >> $GITHUB_ENV

      - name: Ensure Version Does Not Exist
        run: |-

          URL=https://$(echo $CORE_REPO | sed 's/\//\/v2\//')/$IMAGE_NAME/tags/list
          IDX=$(curl -L $URL | jq ".tags | index(\"$VERSION\")")
          if [ $IDX == "null" ]; then
            echo "OK - Version does not exist: $VERSION"
          else
            echo "Version already exists: $VERSION"
            exit 1
          fi

      - name: Checkout
        uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
        with:
          ref: ${{ github.event.inputs.branch }}

      # Login to GHCR
      - name: Log in to the Container registry
        uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GH_PUBLISH_ACCESS_TOKEN }}

      - name: Pull & Extract - darwin amd64
        run: |-
          EXTRACT_DIR=extracted-darwin-amd64
          # new link (darwin-amd64.txz) - https://drive.google.com/file/d/1eFFtffVnZiyGbqdSEsT1rJwsx6B8UPfW/view?usp=drive_link
          curl -L -o darwin-amd64.txz "https://drive.google.com/uc?export=download&id=1eFFtffVnZiyGbqdSEsT1rJwsx6B8UPfW"
          mkdir $EXTRACT_DIR
          tar -xf darwin-amd64.txz --directory $EXTRACT_DIR

      - name: Pull & Extract - darwin arm64
        run: |-
          EXTRACT_DIR=extracted-darwin-arm64
          # new link (darwin-arm64.txz) - https://drive.google.com/file/d/1JWaAsd6_DUpUPLgwmvlGkeeuv70V9Hfx/view?usp=drive_link
          curl -L -o darwin-arm64.txz "https://drive.google.com/uc?export=download&id=1JWaAsd6_DUpUPLgwmvlGkeeuv70V9Hfx"
          mkdir $EXTRACT_DIR
          tar -xf darwin-arm64.txz --directory $EXTRACT_DIR

      - name: Pull & Extract - linux amd64
        run: |-
          EXTRACT_DIR=extracted-linux-amd64
          # new link (linux-amd64.txz) - https://drive.google.com/file/d/17XnB7ipjnnDzvjAVAMCjvePRVyOvyiC-/view?usp=drive_link
          curl -L -o linux-amd64.txz "https://drive.google.com/uc?export=download&id=17XnB7ipjnnDzvjAVAMCjvePRVyOvyiC-"
          mkdir $EXTRACT_DIR
          tar -xf linux-amd64.txz --directory $EXTRACT_DIR

      - name: Pull & Extract - linux arm64
        run: |-
          EXTRACT_DIR=extracted-linux-arm64
          # new link (linux-arm64.txz) - https://drive.google.com/file/d/1dBKin4bgTbbBSk7fToLnkNxWhixGIbtt/view?usp=drive_link
          curl -L -o linux-arm64.txz "https://drive.google.com/uc?export=download&id=1dBKin4bgTbbBSk7fToLnkNxWhixGIbtt"
          mkdir $EXTRACT_DIR
          tar -xf linux-arm64.txz --directory $EXTRACT_DIR

      - name: Build Config JSON
        run: |-
          JSON_STRING=$( jq -n \
            --arg name "$IMAGE_NAME" \
            --arg organization "$ORG" \
            --arg version "$VERSION" \
            --arg schemaVersion "$CONFIG_SCHEMA_VERSION" \
            --arg dbVersion "$PG_VERSION" \
            '{schemaVersion: $schemaVersion, db: { name: $name, organization: $organization, version: $version, dbVersion: $dbVersion} }' )

          echo $JSON_STRING > config.json

      - name: Build Annotations JSON
        run: |-
          JSON_STRING=$( jq -n \
              --arg title "$IMAGE_NAME" \
              --arg desc "$ORG" \
              --arg version "$VERSION" \
              --arg timestamp "$(date +%FT%TZ)" \
              --arg vendor "Turbot HQ, Inc." \
            '{ 
                "$manifest": { 
                    "org.opencontainers.image.title": $title, 
                    "org.opencontainers.image.description": $desc,
                    "org.opencontainers.image.version": $version, 
                    "org.opencontainers.image.created": $timestamp,
                    "org.opencontainers.image.vendor":  $vendor
                }
            }' )

            echo $JSON_STRING > annotations.json

      # Setup ORAS
      - name: Install specific version of ORAS
        run: |
          curl -LO https://github.com/oras-project/oras/releases/download/v${ORAS_VERSION}/oras_${ORAS_VERSION}_linux_amd64.tar.gz
          sudo tar xzf oras_${ORAS_VERSION}_linux_amd64.tar.gz -C /usr/local/bin oras
          oras version

      # Publish to GHCR
      - name: Push to Registry
        run: |-
          REF="$CORE_REPO/$IMAGE_NAME:$VERSION"
          LATEST_REF="$CORE_REPO/$IMAGE_NAME:latest"

          oras push $REF \
              --config config.json:application/vnd.turbot.steampipe.config.v1+json \
              --annotation-file annotations.json \
              extracted-darwin-amd64:application/vnd.turbot.steampipe.db.darwin-amd64.layer.v1+tar \
              extracted-darwin-arm64:application/vnd.turbot.steampipe.db.darwin-arm64.layer.v1+tar \
              extracted-linux-amd64:application/vnd.turbot.steampipe.db.linux-amd64.layer.v1+tar \
              extracted-linux-arm64:application/vnd.turbot.steampipe.db.linux-arm64.layer.v1+tar

          # check if the version is NOT an pre-release version before tagging as latest
          if [[ $VERSION =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Tagging as latest: $LATEST_REF"
            oras tag $REF latest
          else
            echo "Skipping latest tag for pre-release version: $VERSION"
          fi
