The patch provided is partially wrong. I copy & pasted the code from sync_enrolments and forgot to adjust a few variable names.
As a result, there are several places where we use $extcourse which is not defined in the contextd it's used, so we use an empty value for several critical course fields ($CFG->enrol_localcoursefield, fullname and shortname.).
So we need to rename all those $extcourse to $coursefield. The attached patch does it.
Sorry for the (big) mistake. Btw, we need to apply this to HEAD too.