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

.undef _VOPT
_MAKE=${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 /usr/ports/Makefile
_NULLRUN=${.MAKEFLAGS:M-n}

PATCHREQD=index

.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 /usr/ports/.patch_done

update: _update /usr/ports/.patch_done

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

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

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

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

.undef _RUNDONE
.for APORTS in ${TGTS}
.if !target(${APORTS})
${APORTS}: ${_NEEDPATCH}
.ifndef _RUNDONE
	@${ECHO} "***** BUILDING FOR ${TGTS} (TARGET ${APORTS}, DEPEND TO ${_NEEDPATCH})" >&2
	+cd /usr/ports ; ${_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
