#!/bin/bash
#
# Copyright Super iPaaS Integration LLC, an IBM Company 2024
#

# Define Variables
name=$1
npm_user=$2
npm_identity_token=$3
version_json=$5
ARTIFACTORY_URL="https://na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/"
ARTIFACTORY_PACKAGE_URL="${ARTIFACTORY_URL}@apic/$name"


echo "name: $name"
echo "npm_user: $npm_user"
echo "npm_identity_token: $npm_identity_token"
echo "ARTIFACTORY_PACKAGE_URL: $ARTIFACTORY_PACKAGE_URL"
# Step 1: Create .npmrc File
echo "Setting up .npmrc file..."
echo '@apic:registry=https://na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/' > ~/.npmrc
echo "//na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/:_authToken=$npm_identity_token" >> ~/.npmrc
echo "//na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/:email=$npm_user" >> ~/.npmrc
echo "//na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/:always-auth=true" >> ~/.npmrc
echo '@apistudio:registry=https://na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/' > ~/.npmrc
echo "//na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/:_authToken=$npm_identity_token" >> ~/.npmrc
echo "//na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/:email=$npm_user" >> ~/.npmrc
echo "//na.artifactory.swg-devops.com/artifactory/api/npm/apic-prod-npm/:always-auth=true" >> ~/.npmrc

# Step 2: Fetch Latest Version of the Package
echo "Fetching the latest version of the package from JFrog Artifactory..."
response=$(curl --write-out "HTTPSTATUS:%{http_code}" --location --request GET \
  "$ARTIFACTORY_PACKAGE_URL" \
  --user "$npm_user:$npm_identity_token")

# Parse HTTP status and response body
http_body=$(echo "$response" | sed -e 's/HTTPSTATUS\:.*//g')
http_status=$(echo "$response" | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')

echo "======== JFrog API Response ========"
echo "HTTP Status Code: $http_status"
echo "Response Body: $http_body"

# Determine Build Number
if [ "$http_status" -eq 200 ]; then
    latest_version=$(echo "$http_body" | jq -r '.["dist-tags"].latest')
    build_number=$(echo "$latest_version" | awk -F'-' '{print $2}' | awk -F. '{print $1}')
    updated_build_number=$((build_number + 1))
    echo "Extracted Build Number: $build_number"
    echo "Updated Build Number: $updated_build_number"
else
    echo "Package does not exist or request failed. Defaulting to initial build number."
    updated_build_number=1
fi

# # Step 3: Update Package Version and Build Artifact
# echo "Updating package version and building artifact..."
# cd "$path" || { echo "Failed to change directory to $path"; exit 1;  }

package_json="package.json"
majorVersion="$(cat $version_json | jq -r '.majorVersion')"
minorVersion="$(cat $version_json | jq -r '.minorVersion')"
microVersion="$(cat $version_json | jq -r '.microVersion')"
base_version="${majorVersion}.${minorVersion}.${microVersion}"
new_version="${base_version}-${updated_build_number}"

jq ".version = \"${new_version}\"" "$package_json" > temp.json
mv temp.json "$package_json"

# Install dependencies and build the package
npm install --no-workspaces
npm run build || { echo "TypeScript compilation failed"; exit 1; }

# Package the artifact
npm pack || { echo "npm pack failed"; exit 1; }

# Validate the .tgz file exists
tgz_file=$(ls *.tgz)
if [ -z "$tgz_file" ]; then
  echo "No .tgz file found"
  exit 1
fi

# Rename artifact and prepare for publishing
artifact_name="${name}-${new_version}.tgz"
mv "$tgz_file" "$artifact_name"

# Step 4: Publish Artifact to JFrog Artifactory
# echo "Publishing artifact to JFrog Artifactory..."
# npm publish "$artifact_name" --registry=${ARTIFACTORY_URL} --verbose || { echo "npm publish failed"; exit 1; }
# echo "Artifact $artifact_name uploaded successfully to JFrog Artifactory"
