TGTS=${.TARGETS:Nupdate}
TGTU=${.TARGETS:Mupdate}

.undef _VOPT
_MAKE=cd ${.CURDIR} ; ${MAKE:Q} 
.for _V in ${.MAKEFLAGS}
.if ! ( empty (${_V:N-V}) || defined(_VOPT) )
_MAKE+=${_V:Q}
.endif
.undef _VOPT
.if empty (${_V:N-V})
_VOPT=1
.endif
.endfor
_MAKE+=-s -f ${.CURDIR}/Makefile
_NULLRUN=${.MAKEFLAGS:M-n}

PATCHREQD=universe buildworld world buildkernel kernel

.undef _VOPT
.for _V in ${MFLAGS}
.if defined (_VOPT)
${_V}!=${_MAKE} -V ${_V}
.endif
.undef _VOPT
.if empty (${_V:N-V})
_VOPT=1
.endif
.endfor

.NOTPARALLEL:

.ORDER: _update ${.CURDIR}/.patch_done

update: _update ${.CURDIR}/.patch_done

_update:
	@${ECHO} "***** RUNNING UPDATE" >&2
	+cd /usr/src
.if !(defined(SUP_UPDATE) || defined(CVS_UPDATE)) && exists(${.CURDIR}/.svn)
	@${ECHO} ">>> Reverting /usr/src using Subversion"
	+svn revert -R /usr/src
.endif
	+${_MAKE} update
	+touch ${.CURDIR}/.update_done

${.CURDIR}/.patch_done: .update_done
.if defined(LOCAL_SRC_PATCHES) && !empty(LOCAL_SRC_PATCHES)
.for p in ${LOCAL_SRC_PATCHES}
.if !exists(${p})
	@${ECHO} "The patch file ${p} does not exist!" >&2
	@exit 1
.endif
.endfor
.endif
.if defined(LOCAL_SRC_PATCHES) && !empty(LOCAL_SRC_PATCHES)
	@${ECHO} "***** RUNNING PATCH" >&2
.for p in ${LOCAL_SRC_PATCHES}
	 patch -d ${.CURDIR} ${PATCH_FLAGS} < ${p}
.endfor
	 touch ${.CURDIR}/.patch_done
#	 touch ${.OBJDIR}/.patch_done
.endif

_PX=
.for I in ${TGTS}
_PX+=${PATCHREQD:M${I}}
.endfor

.if ${_PX:S/ //g} != "" 
_NEEDPATCH=${.CURDIR}/.patch_done
.endif

.undef _RUNDONE
.for ASRC in ${TGTS}
.if !target(${ASRC})
${ASRC}: ${_NEEDPATCH}
.ifndef _RUNDONE
	@${ECHO} "***** BUILDING FOR ${TGTS} (TARGET ${ASRC}, DEPEND TO ${_NEEDPATCH})" >&2
	+${_MAKE} ${TGTS}
	@${ECHO} "***** RETURN FROM ${TGTS}" >&2
_RUNDONE=1
.endif
.endif
.endfor
.undef _RUNDONE

.BEGIN: ${TGTU}
	@${ECHO} "***** GLOBAL START FOR ${.TARGETS}" >&2

.END:
	@${ECHO} "***** GLOBAL END FOR ${.TARGETS}" >&2
