• @@datefirst returns the current setting for first day of the week, as set by SET DATEFIRST.  Values are 1 = Monday and so on through to 7 = Sunday.  You have first day of the week set as Sunday.

    This means that DATEPART(dw,[date_of_a_sunday]) would always return 1 (meaning that it is the first day of the week).  If your first day of the week was set as Monday (i.e. @@datefirst = 1) then DATEPART(dw,[date_of_a_sunday]) would return 7.

    So:

    select @Sunday = 8 - @@datefirst

    sets the variable @Sunday to what DATEPART will return if the input date is a Sunday, based on your current @@datefirst setting.  The @Sunday variable is then used within the function to compare against the DATEPART return to identify a Sunday.  This ensures the function works regardless of what it is set at (i.e. if you had Wednesday set as the first day of the week, the function would still correctly identify Saturdays and Sundays).

    The next line works out what day Saturday would be (using modulo arithmetic), for the same purpose.

    Hope that makes sense!