#!/bin/bash
#ac
# Global Variables
PRJ_NAME="testvaluelist-frontval-f"
DOCKER_USER="risadmin_prod"
DOCKER_PASS=$(sv get "risadmin_prod" dockerPassword)
DOCKER_URL="157.66.191.31:3000"
REPO_NAME="testvaluelist"
GITEA_USER="risadmin_prod"
GITEA_PASS=$(sv get "risadmin_prod" dockerPassword)
GITEA_EMAIL="ganeshk@dekatc.com"
GIT_BRANCH="main"
DOMAIN="157.66.191.31:3000"
CONT_PORT=30167
TARGET_PORT=80
PATH_DIR="/data/42169_1753417942767/sureops_deploy/testvaluelist/sureops/testvaluelist-frontval-f/deployment"
DOCKER_TAG="1.0"
MAX_RETRIES=3
RETRY_DELAY=10

# Stop any existing containers with the same name and ports
docker stop "$PRJ_NAME" >/dev/null 2>&1 || true
docker rm "$PRJ_NAME" >/dev/null 2>&1 || true

# Retry logic for Docker build
build_docker_image() {
    local attempt=1
    local build_status=1

    while [[ $attempt -le $MAX_RETRIES ]]; do
        printf "Attempt %d to build Docker image...\n" "$attempt"

        DOCKER_BUILDKIT=0 docker build --no-cache \
            -t "$DOCKER_URL/$DOCKER_USER/$PRJ_NAME:$DOCKER_TAG" \
            --build-arg BUILD_ID="$DOCKER_TAG" \
            --build-arg GITEA_USER="$GITEA_USER" \
            --build-arg GITEA_PASS="$GITEA_PASS" \
            "$PATH_DIR" && build_status=0 && break

        printf "Docker build failed on attempt %d. Retrying in %d seconds...\n" "$attempt" "$RETRY_DELAY" >&2
        attempt=$((attempt + 1))
        sleep "$RETRY_DELAY"
    done

    return $build_status
}

# Build Docker image with retry logic
if ! build_docker_image; then
    printf "Build process failed after %d attempts.\n" "$MAX_RETRIES" >&2
    exit 1
fi

# Docker login
docker login --username="$DOCKER_USER" --password="$DOCKER_PASS" "$DOCKER_URL"

# Tag and push the Docker image
docker tag "$DOCKER_URL/$DOCKER_USER/$PRJ_NAME:$DOCKER_TAG" "$DOCKER_URL/$DOCKER_USER/$PRJ_NAME:latest"
docker push "$DOCKER_URL/$DOCKER_USER/$PRJ_NAME:latest"
docker push "$DOCKER_URL/$DOCKER_USER/$PRJ_NAME:$DOCKER_TAG"

# Docker logout
docker logout "$DOCKER_URL"

# Trigger repo update via curl
curl -X GET "http://157.66.191.31:31170/sureops/suredocker/updaterepo?repoName=$REPO_NAME&packageName=$PRJ_NAME"

# Prune Docker resources
docker network prune -f
docker image prune -f --filter "dangling=true"
docker volume prune -f
