#!/bin/bash

DCNAME=$(/usr/lib/vmware-vmafd/bin/vmafd-cli get-dc-name-ex --server-name localhost)
DOMAINNAME=$(/usr/lib/vmware-vmafd/bin/vmafd-cli get-domain-name --server-name localhost)
DOMAINDN="dc=$(echo $DOMAINNAME | sed -r 's/[.]+/,dc=/g')"

DCACCOUNTDN=$(/opt/likewise/bin/lwregshell list_values '[HKEY_THIS_MACHINE\Services\vmdir]' | grep dcAccountDN | awk '{$1=$2=$3="";print $0}' | sed -e 's/^\s*"\(.*\)"\s*$/\1/g')

DCACCOUNTPW=$(/opt/likewise/bin/lwregshell list_values '[HKEY_THIS_MACHINE\Services\vmdir]' | grep dcAccountPassword | awk '{$1=$2=$3="";print $0}' | sed -e 's/^\s*"\(.*\)"\s*$/\1/g' | sed -e 's/\\\(.\)/\1/g')

echo "DC Name: $DCNAME"
echo "Domain Name: $DOMAINNAME"
echo "Domain DN: $DOMAINDN"
echo "DC Account DN: $DCACCOUNTDN"


# Search for any external IDPs that might be configured
echo
echo "Searching for configured external identity providers ..."
echo
EXTERNALIDPSDN="cn=VCIdentityProviders,cn=$DOMAINNAME,cn=Tenants,cn=IdentityManager,cn=Services,$DOMAINDN"
IDPSOUTPUT="$(ldapsearch -LLL -h "$DCNAME" -b "$EXTERNALIDPSDN" '(objectclass=vmwSTSExternalIdp)' dn vmwSTSIsDefaultIdp -D "$DCACCOUNTDN" -w "$DCACCOUNTPW")"
echo "$IDPSOUTPUT"
echo

# Look for the default IDP. The DN may span multiple lines, so
# it's easier just to take the first line of the dn attribute
# and use sed to extract the UUID of the IDP rather than trying
# to get the full DN with awk
DEFAULTIDP="$(echo "$IDPSOUTPUT" | awk '/^[dD][nN]:/ {idpdn=$2} /vmwSTSIsDefaultIdp:\s*true/ {defaultdn=idpdn} END {print defaultdn}' | sed -e 's/^\s*[cC][nN]=\([^,]*\).*/\1/g')"

if [ -z "$DEFAULTIDP" ]; then
  echo "No default external identity providers configured. No further cleanup needed."
  exit 0
fi

echo "Found default external identity provider: $DEFAULTIDP"
echo
DEFAULTIDPDN="cn=$DEFAULTIDP,$EXTERNALIDPSDN"

# This cleanup only needs to occur for "Oauth2" IDPs, which were only used in
# GovCloud, where local VC group memberships were not managed directly by the
# admin, but rather, only claim map JITing established these local memberships
# via ForeignSecurityPrincipals. In this case, all ForeignSecurityPrincipals
# for the Oauth2 IDP's domain can be removed since all local group memberships
# will be re-established with the new JITing logic.

# Determine if this is an "Oauth2" IDP, which is determined based on the
# absence of the OIDCDiscoveryEndpoint, which is only present on "OIDC" IDPs
echo "Verifying that identity provider $DEFAULTIDP is an 'Oauth2' provider ..."
echo
FOUNDOIDC="$(ldapsearch -LLL -h "$DCNAME" -b "cn=Endpoints,$DEFAULTIDPDN" '(cn=OIDCDiscoveryEndpoint)' -D "$DCACCOUNTDN" -w "$DCACCOUNTPW" | awk '/^[cC][nN]:/ {print $2}')"
if [ -n "$FOUNDOIDC" ]; then
  echo "Found endpoint $FOUNDOIDC. This is an 'Oidc' identity provider. No further cleanup needed."
  exit 0
fi

# Find the domains of the JITed users for this IDP
echo "Finding JITed user domains ..."
JITDOMAINS="$(ldapsearch -LLL -h "$DCNAME" -b "cn=Domains,cn=JIT,$DEFAULTIDPDN" '(objectclass=vmwSTSJitDomain)' cn -D "$DCACCOUNTDN" -w "$DCACCOUNTPW" | awk '/^[cC][nN]:/ {print $2}')"

if [ -z "$JITDOMAINS" ]; then
  echo "No JITed domains found for identity provider $DEFAULTIDP. No further cleanup needed."
  exit 0
fi

echo "$JITDOMAINS"
echo

# For each found JIT domain, look for all FSPs corresponding to that
# domain and remove them
FSPCONTAINERDN="cn=ForeignSecurityPrincipals,$DOMAINDN"
while IFS= read -r domain; do
  echo "Finding ForeignSecurityPrincipals for domain $domain ..."
  jitfsps="$(ldapsearch -LLL -h "$DCNAME" -b "$FSPCONTAINERDN" '(objectclass=foreignSecurityPrincipal)' externalObjectId -D "$DCACCOUNTDN" -w "$DCACCOUNTPW" | awk -v dom="$domain" '$1 ~ "externalObjectId:" && $2 ~ ".*@"dom"$" {print $2}')"
  if [ -z "$jitfsps" ]; then
    echo "No ForeignSecurityPrincipals found for domain $domain"
    echo
    continue
  fi
  echo "$jitfsps"
  echo
  while IFS= read -r fsp; do
    fspdn="externalObjectId=$fsp,$FSPCONTAINERDN"
    echo "Removing ForeignSecurityPrincipal: $fspdn"
    ldapdelete -h "$DCNAME" "$fspdn" -D "$DCACCOUNTDN" -w "$DCACCOUNTPW"
  done <<< "$jitfsps"
  echo
done <<< "$JITDOMAINS"

echo
echo "Finished cleaning up ForeignSecurityPrincipals for default 'Oauth2' provider $DEFAULTIDP"
echo

