# Define the checksum file
CHECKSUM_FILE=".env.checksum"

# Calculate the current checksum of the .env file
CURRENT_CHECKSUM=$(shasum -a 256 .env | awk '{ print $1 }')

# Check if checksum file exists
if [ -f "$CHECKSUM_FILE" ]; then
  # Read the previous checksum
  PREVIOUS_CHECKSUM=$(cat "$CHECKSUM_FILE")

  # Compare the current checksum with the previous checksum
  if [ "$CURRENT_CHECKSUM" = "$PREVIOUS_CHECKSUM" ]; then
    echo ".env file has not changed. Skipping Netlify environment import."
    exit 0
  fi
fi

# If the checksum is different or the file doesn't exist, import the variables
echo "Importing environment variables to Netlify..."
netlify env:import .env

if [ $? -ne 0 ]; then
  echo "Failed to import environment variables to Netlify. Aborting push."
  exit 1
fi

# Save the new checksum
echo "$CURRENT_CHECKSUM" > "$CHECKSUM_FILE"

git add "$CHECKSUM_FILE"
git commit --amend --no-edit
git push --force-with-lease --force-if-includes

echo "Environment variables imported successfully."
