#!/bin/bash

# Start a GitHub Actions group for input validation
echo "::group::Validating Inputs"

# Check if the correct number of arguments is passed
if [ "$#" -ne 6 ]; then
    echo "Incorrect number of arguments provided."
    echo "Usage: $0 <TIBI_USERNAME> <TIBI_PASSWORD> <TIBI_API_URL> <PROJECT_API_CONFIG> <PROJECT_NAMESPACE> <PROJECT_NAME>"
    exit 1
fi

# Assigning passed arguments to variables for better readability
TIBI_USERNAME=$1
TIBI_PASSWORD=$2
TIBI_API_URL=$3
PROJECT_API_CONFIG=$4
PROJECT_NAMESPACE=$5
PROJECT_NAME=$6

echo "Provided TIBI_USERNAME: $TIBI_USERNAME"
echo "TIBI_API_URL: $TIBI_API_URL"
# Be cautious with logging sensitive data like passwords and tokens
# Echoing the password or sensitive information is generally not recommended

# End the input validation group
echo "::endgroup::"

# Start a group for authentication
echo "::group::Authenticating User"

# Prepare authentication request payload
auth_payload=$(jq -n --arg username "$TIBI_USERNAME" --arg password "$TIBI_PASSWORD" '{username: $username, password: $password}')
echo "Authentication payload: $auth_payload"
# Fetch the authentication token
echo "Requesting authentication token..."
auth_response=$(curl -s -X POST -H "Content-Type: application/json" -d "$auth_payload" "$TIBI_API_URL/login")
# Logging the response for debugging (remove sensitive data as necessary)
echo "Authentication response: $auth_response"

# Extract token from the response
TIBI_AUTH_TOKEN=$(echo $auth_response | jq -r '.token')

# Check if the token was successfully retrieved
if [ -z "$TIBI_AUTH_TOKEN" ]; then
    echo "Failed to get authentication token. Exiting script."
    exit 1
fi

echo "Authentication token received successfully."
echo "::endgroup::"

# Start a group for fetching project data
echo "::group::Fetching Project Data"

# Get the list of projects from the API
echo "Retrieving projects..."
response=$(curl -s -H "X-Auth-Token: $TIBI_AUTH_TOKEN" "$TIBI_API_URL/project")
echo $response
projects=$(echo $response) # Parse the JSON response to get project data

echo "::endgroup::"

# Start a group for processing project data
echo "::group::Processing Project Data"

# Initialize variables to track project existence
projectFound=false
projectId=""

# Loop through each project to find if the required project exists
for row in $(echo "${projects}" | jq -r '.[] | @base64'); do
    _jq() {
        echo ${row} | base64 --decode | jq -r ${1}
    }

    api_name=$(_jq '.name')
    # Check if the current project's namespace matches the target
    if [ "$api_name" == "$PROJECT_NAME" ]; then
        projectId=$(_jq '.id')
        projectData=$(echo ${row} | base64 --decode)
        projectFound=true
        break
    fi
done

echo "::endgroup::"

# Start a group for creating or updating the project
echo "::group::Creating or Updating Project"

# Conditionally create a new project or update the existing one
if [ "$projectFound" = true ]; then
    echo "Project found with ID: $projectId, updating..."
    # Prepare updated project data
    updatedProjectData=$(echo $projectData | jq --arg configFile "$PROJECT_API_CONFIG" '.configFile = $configFile | del(.id)')
    # Send a PUT request to update the project
    updateResponse=$(curl -s -X PUT -H "Content-Type: application/json" -H "X-Auth-Token: $TIBI_AUTH_TOKEN" -d "$updatedProjectData" "$TIBI_API_URL/project/$projectId")
    # Logging the response for debugging (remove sensitive data as necessary)
    echo "Update response: $updateResponse"

else
    echo "Project not found. Creating new project..."
    # Send a POST request to create a new project
    createResponse=$(curl -s -X POST -H "Content-Type: application/json" -H "X-Auth-Token: $TIBI_AUTH_TOKEN" -d "{\"configFile\":\"$PROJECT_API_CONFIG\", \"name\":\"$PROJECT_NAMESPACE\", \"namespace\":\"$PROJECT_NAMESPACE\", \"description\":\"$PROJECT_NAMESPACE\"}" "$TIBI_API_URL/project")
fi

echo "::endgroup::"
