#!/bin/bash
# Copyright 2025 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# Function to pull or push with retry logic
perform_oras_command() {
  command="$1"
  echo "[*] Running oras command: $command"

  retries=3
  attempt=0

  while [ $attempt -lt $retries ]; do
    set +e
    $command
    status=$?
    set -e

    if [ $status -eq 0 ]; then
      echo "[+] Command successful."
      return 0
    else
      echo "[!] $command failed with code $status"
      login_to_registry
      attempt=$((attempt + 1))
      echo "[*] Retry attempt $attempt/$retries"
    fi
  done

  echo "[!] Failed after $retries attempts."
  return 1
}

if [ ! -f ./export.tar.gz ]; then
  echo "bdu not found"
  ./bdu-to-json/bdu-to-json
else
  if [ "$(( `date +%s` - `stat -L --format %Y ./export.tar.gz` ))" -gt "300" ]; then
    echo "Remove stale bdu"
    rm -rf ./export.tar.gz
    ./bdu-to-json/bdu-to-json
  fi
fi

host=$(echo "$1" | awk -F/ '{print $1}')
case "$host" in
  "$DECKHOUSE_REGISTRY_HOST")
    auth="-u $DECKHOUSE_REGISTRY_USER -p $DECKHOUSE_REGISTRY_PASSWORD"
    ;;
  "$GHCR_HOST")
    auth="-u $GHCR_IO_REGISTRY_USER -p $GHCR_IO_REGISTRY_PASSWORD"
    ;;
  "$DECKHOUSE_CSE_REGISTRY_HOST")
    auth="-u $DECKHOUSE_CSE_REGISTRY_USER -p $DECKHOUSE_CSE_REGISTRY_PASSWORD"
    ;;
  "$DECKHOUSE_DEV_CSE_REGISTRY_HOST")
    auth="-u $DECKHOUSE_CSE_DEV_REGISTRY_USER -p $DECKHOUSE_CSE_DEV_REGISTRY_PASSWORD"
    ;;
  "$DECKHOUSE_DEV_REGISTRY_HOST")
    auth="-u $DECKHOUSE_DEV_REGISTRY_USER -p $DECKHOUSE_DEV_REGISTRY_PASSWORD"
    ;;
  *)
    echo "[!] Unknown registry: $host"
    exit 1
    ;;
esac
perform_oras_command "./oras push -d -v $auth --artifact-type application/octet-stream ${1} export.tar.gz:application/deckhouse.io.bdu.layer.v1.tar+gzip"
