#!/bin/bash

# Initialize variables
RELEASE_VERSION=""
RELEASE_MESSAGE=""
DOCKER_ACCOUNT="josakola"  # Your Docker account name

# Parse input arguments
while getopts r:m: flag
do
    case "${flag}" in
        r) RELEASE_VERSION=${OPTARG};;
        m) RELEASE_MESSAGE=${OPTARG};;
        *)
          echo "Usage: $0 -r <release_version> -m <release_message>"
          exit 1 ;;
    esac
done

# Ensure both version and message are provided
if [ -z "$RELEASE_VERSION" ]; then
  echo "Error: Release version not provided. Use -r <release_version>"
  exit 1
fi

if [ -z "$RELEASE_MESSAGE" ]; then
  echo "Error: Release message not provided. Use -m <release_message>"
  exit 1
fi

# Path to your docker-compose file
DOCKER_COMPOSE_FILE="compose_dev.yaml"

# Get all the img defined in docker-compose
IMAGES=$(docker compose -f $DOCKER_COMPOSE_FILE config | grep 'image:' | awk '{ print $2 }')

# Start tagging only relevant img
for DOCKER_IMAGE in $IMAGES; do
    # Check if the image belongs to your Docker account and ends with :latest
    if [[ $DOCKER_IMAGE == $DOCKER_ACCOUNT* && $DOCKER_IMAGE == *:latest ]]; then
        # Remove the ":latest" tag to use the base image name
        BASE_IMAGE=${DOCKER_IMAGE%:latest}

        echo "Tagging Docker image: $BASE_IMAGE with version: $RELEASE_VERSION"

        # Tag the 'latest' image with the new release version
        docker tag $DOCKER_IMAGE $BASE_IMAGE:$RELEASE_VERSION

        # Push the newly tagged image to Docker Hub
        docker push $BASE_IMAGE:$RELEASE_VERSION
    else
        echo "Skipping image: $DOCKER_IMAGE (not part of $DOCKER_ACCOUNT or not tagged as latest)"
    fi
done

# Step 3: Tag the Git repository with the release version
echo "Tagging Git repository with version: $RELEASE_VERSION"
git tag -a v$RELEASE_VERSION -m "Release $RELEASE_VERSION: $RELEASE_MESSAGE"
git push origin v$RELEASE_VERSION

echo -e "\033[35mRelease process completed for version: $RELEASE_VERSION \033[0m"
echo -e "\033[35mFinished at $(date +"%d/%m/%Y %H:%M:%S")\033[0m"