#!/bin/bash
IP=$1

# --- Function to compare version numbers ---
version_ge() {
  # Compares two version strings (e.g., 3.27.0 vs 3.24.3)
  # Returns 0 (true) if $1 is greater than or equal to $2, 1 (false) otherwise
  if [ "$1" == "$2" ]; then
    return 0
  fi

  # Use sort -V (version sort) to compare
  printf '%s\n' "$1" "$2" | sort -V | head -n 1 | grep -q "$2"
}
# ------------------------------------------


# Define the minimum required version
MIN_VERSION="3.27.0"

output="Thank you for downloading the Getting Started with CFEngine Enterprise
Vagrant environment

Please complete your setup of Mission Portal: https://$IP
"

# 1. Check if cf-hub executable exists
if [[ -x /var/cfengine/bin/cf-hub ]]; then
    # 2. Get the full version string (e.g., "CFEngine Enterprise 3.24.3a.ab880fd")
    CFHUB_VERSION_FULL=$(/var/cfengine/bin/cf-hub --version 2>/dev/null | grep 'CFEngine Enterprise')

    # 3. Extract just the version number (e.g., "3.24.3a.ab880fd")
    # This uses a regex to grab the version part after "CFEngine Enterprise "
    # We strip off the "a.be3370375" or similar parts later for the comparison
    CFHUB_VERSION_RAW=$(echo "$CFHUB_VERSION_FULL" | sed -E 's/^CFEngine Enterprise (.*)$/\1/')

    # 4. Extract the main numeric version (e.g., "3.24.3" from "3.24.3a.ab880fd")
    # This keeps only the initial numeric parts separated by dots
    CFHUB_VERSION_NUMERIC=$(echo "$CFHUB_VERSION_RAW" | sed -E 's/([0-9]+\.[0-9]+\.[0-9]+).*/\1/')

    # 5. Check if the numeric version is greater than or equal to the minimum
    if version_ge "$CFHUB_VERSION_NUMERIC" "$MIN_VERSION"; then
        output="$output \n$(/var/cfengine/bin/cf-hub --new-setup-code)"
    else
        output="$output \n"
    fi
else
    echo "Warning: /var/cfengine/bin/cf-hub not found or not executable."
fi

echo -e "$output"
echo -e "$output" > /vagrant/hub_output.txt
