<?php

$taxonomy = 'cac_course_disciplinary_cluster';

$course_ids = get_posts( [
	'post_type' => 'cac_course',
	'nopaging'  => true,
	'fields'    => 'ids',
] );

foreach ( $course_ids as $course_id ) {
	$course = new \CAC\Courses\Course( $course_id );

	$clusters = [];

	// Combine them all.
	$site_ids = $course->get_site_ids();
	foreach ( $site_ids as $site_id ) {
		$site_clusters = cac_get_site_disciplinary_clusters( $site_id );
		if ( $site_clusters ) {
			$clusters = array_merge( $clusters, $site_clusters );
		}
	}

	$group_ids = $course->get_group_ids();
	foreach ( $group_ids as $group_id ) {
		$group_clusters = cac_get_group_disciplinary_clusters( $group_id );
		if ( $group_clusters ) {
			$clusters = array_merge( $clusters, $group_clusters );
		}
	}

	if ( ! $clusters ) {
		return;
	}

	$clusters = array_unique( $clusters );

	wp_set_object_terms( $course_id, $clusters, $taxonomy );
}
