]> TLD Linux GIT Repositories - packages/rpm-build-tools.git/blob - builder
- fix -at option with git (get last git tag)
[packages/rpm-build-tools.git] / builder
1 #!/bin/ksh
2 #
3 # This program is free software, distributed under the terms of
4 # the GNU General Public License Version 2.
5 #
6 # -----------
7 # Exit codes:
8 #         0 - succesful
9 #         1 - help displayed
10 #         2 - no spec file name in cmdl parameters
11 #         3 - spec file not stored in repo
12 #         4 - some source, patch or icon files not stored in repo
13 #         5 - package build failed
14 #         6 - spec file with errors
15 #         7 - wrong source in /etc/poldek.conf
16 #         8 - Failed installing buildrequirements and subrequirements
17 #         9 - Requested tag already exist
18 #        10 - Refused to build fractional release
19 #       100 - Unknown error (should not happen)
20 #   110 - Functions not yet implemented
21
22 # Notes (todo/bugs):
23 # - when Icon: field is present, -5 and -a5 doesn't work
24 # - builder -R skips installing BR if spec is not present before builder invocation (need to run builder twice)
25 # - does not respect NoSource: X, and tries to cvs up such files [ example: VirtualBox-bin.spec and its Source0 ]
26 # TODO:
27 # - ability to do ./builder -bb foo.spec foo2.spec foo3.spec
28 # - funny bug, if source-md5 is set then builder will download from distfiles even if there is no url present:
29 #   Source10:   forwardfix.pl
30 #   # Source10-md5:     8bf85f7368933a4e0cb4f875bac28733
31 # - builder --help:
32 #       basename: missing operand
33 #       Try `basename --help' for more information.
34 #       -- and the normal usage info --
35
36 PROGRAM=${0##*/}
37 APPDIR=$(d=$0; [ -L "$d" ] && d=$(readlink -f "$d"); dirname "$d")
38 RCSID='$Id: builder,v 1.645 2011/02/13 17:54:10 glen Exp $' r=${RCSID#* * } rev=${r%% *}
39 VERSION="v0.35/$rev"
40 VERSIONSTRING="\
41 Build package utility from PLD Linux Packages repository
42 $VERSION (C) 1999-2012 Free Penguins".
43
44 PATH="/bin:/usr/bin:/usr/sbin:/sbin:/usr/X11R6/bin"
45
46 # required rpm-build-macros
47 RPM_MACROS_VER=1.534
48
49 COMMAND="build"
50 TARGET=""
51
52 SPECFILE=""
53 BE_VERBOSE=""
54 QUIET=""
55 CLEAN=""
56 DEBUG=""
57 NOURLS=""
58 NOCVSSPEC=""
59 NODIST=""
60 NOINIT=""
61 PREFMIRRORS=""
62 UPDATE=""
63 ADD5=""
64 NO5=""
65 ALWAYS_CVSUP=${ALWAYS_CVSUP:-"yes"}
66
67 # use rpm 4.4.6+ digest format instead of comments if non-zero
68 USEDIGEST=
69
70 # user agent when fetching files
71 USER_AGENT="PLD/Builder($VERSION)"
72
73 # It can be used i.e. in log file naming.
74 # See LOGFILE example.
75 DATE=`date +%Y-%m-%d_%H-%M-%S`
76
77 # target arch, can also be used for log file naming
78 TARGET=$(rpm -E %{_target})
79
80 # Example: LOGFILE='../log.$PACKAGE_NAME'
81 # Example: LOGFILE='../LOGS/log.$PACKAGE_NAME.$DATE'
82 # Example: LOGFILE='$PACKAGE_NAME/$PACKAGE_NAME.$DATE.log'
83 # Example: LOGFILE='$PACKAGE_NAME.$DATE.log'
84 # Yes, you can use variable name! Note _single_ quotes!
85 LOGFILE=''
86
87 LOGDIR=""
88 LOGDIROK=""
89 LOGDIRFAIL=""
90 LASTLOG_FILE=""
91
92 CHMOD="no"
93 CHMOD_MODE="0644"
94 RPMOPTS=""
95 RPMBUILDOPTS=""
96 BCOND=""
97 GROUP_BCONDS="no"
98
99 # create symlinks for tools in PACKAGE_DIR, see get_spec()
100 SYMLINK_TOOLS="yes"
101
102 PATCHES=""
103 SOURCES=""
104 ICONS=""
105 PACKAGE_RELEASE=""
106 PACKAGE_VERSION=""
107 PACKAGE_NAME=""
108 ASSUMED_NAME=""
109 PROTOCOL="http"
110
111 # use lftp by default when available
112 USE_LFTP=
113 lftp --version > /dev/null 2>&1 && USE_LFTP=yes
114 PARALLEL_DOWNLOADS=10
115
116 WGET_RETRIES=${MAX_WGET_RETRIES:-0}
117
118 # TLD git/df config
119 TLD_GIT_SERVER="git://git.tld-linux.org"
120 TLD_GIT_PUSH="git@git.tld-linux.org"
121 TLD_PACKAGES_DIR="packages"
122 TLD_DISTFILES_SERVER="://df.tld-linux.org"
123 TLD_ATTICDISTFILES_SERVER=""
124
125 # PLD git/df config
126 PLD_GIT_SERVER="git://git.pld-linux.org"
127 PLD_GIT_PUSH="git@git.pld-linux.org"
128 PLD_PACKAGES_DIR="packages"
129 PLD_DISTFILES_SERVER="://distfiles.pld-linux.org"
130 PLD_ATTICDISTFILES_SERVER="://attic-distfiles.pld-linux.org"
131
132 CVS_FORCE=""
133 CVSIGNORE_DF="yes"
134 CVSTAG=""
135 GIT_SERVER=${TLD_GIT_SERVER}
136 GIT_PUSH=${TLD_GIT_PUSH}
137 PACKAGES_DIR=${TLD_PACKAGES_DIR}
138 HEAD_DETACHED=""
139 DEPTH=""
140 ALL_BRANCHES=""
141 REMOTE_PLD="origin"
142 NEW_REPO=""
143
144 RES_FILE=""
145
146 DISTFILES_SERVER=${TLD_DISTFILES_SERVER}
147 ATTICDISTFILES_SERVER=${TLD_ATTICDISTFILES_SERVER}
148
149 DEF_NICE_LEVEL=19
150 SCHEDTOOL="auto"
151
152 FAIL_IF_NO_SOURCES="yes"
153
154 # let get_files skip over files which are present to get those damn files fetched
155 SKIP_EXISTING_FILES="no"
156
157 TRY_UPGRADE=""
158 # should the specfile be restored if upgrade failed?
159 REVERT_BROKEN_UPGRADE="yes"
160
161 if rpm --specsrpm 2>/dev/null; then
162         FETCH_BUILD_REQUIRES_RPMSPECSRPM="yes"
163         FETCH_BUILD_REQUIRES_RPMGETDEPS="no"
164 else
165         FETCH_BUILD_REQUIRES_RPMSPECSRPM="no"
166         if [ -x /usr/bin/rpm-getdeps ]; then
167                 FETCH_BUILD_REQUIRES_RPMGETDEPS="yes"
168         else
169                 FETCH_BUILD_REQUIRES_RPMGETDEPS="no"
170         fi
171 fi
172
173 UPDATE_POLDEK_INDEXES_OPTS=""
174
175 # Here we load saved user environment used to
176 # predefine options set above, or passed to builder
177 # in command line.
178 # This one reads global system environment settings:
179 if [ -f ~/etc/builderrc ]; then
180         . ~/etc/builderrc
181 fi
182 # And this one cascades settings using user personal
183 # builder settings.
184 # Example of ~/.builderrc:
185 #
186 #UPDATE_POLDEK_INDEXES="yes"
187 #UPDATE_POLDEK_INDEXES_OPTS="--mo=nodiff"
188 #FETCH_BUILD_REQUIRES="yes"
189 #REMOVE_BUILD_REQUIRES="force"
190 #GROUP_BCONDS="yes"
191 #LOGFILE='../LOGS/log.$PACKAGE_NAME.$DATE'
192 #TITLECHANGE=no
193 #
194 SU_SUDO=""
195 if [ -n "$HOME_ETC" ]; then
196         USER_CFG="$HOME_ETC/.builderrc"
197         BUILDER_MACROS="$HOME_ETC/.builder-rpmmacros"
198 else
199         USER_CFG=~/.builderrc
200         BUILDER_MACROS=~/.builder-rpmmacros
201 fi
202
203 [ -f "$USER_CFG" ] && . "$USER_CFG"
204
205 if [ "$SCHEDTOOL" = "auto" ]; then
206         if [ -x /usr/bin/schedtool ] && schedtool -B -e echo >/dev/null; then
207                 SCHEDTOOL="schedtool -B -e"
208         else
209                 SCHEDTOOL="no"
210         fi
211 fi
212
213 if [ -n "$USE_PROZILLA" ]; then
214         GETURI="proz --no-getch -r -P ./ -t$WGET_RETRIES $PROZILLA_OPTS"
215         GETURI2="$GETURI"
216         OUTFILEOPT="-O"
217 elif [ -n "$USE_AXEL" ]; then
218         GETURI="axel -a $AXEL_OPTS"
219         GETURI2="$GETURI"
220         OUTFILEOPT="-o"
221 elif [ -n "$USE_LFTP" ]; then
222         GETURI=download_lftp
223         GETURI2=$GETURI
224         OUTFILEOPT=""
225 else
226         wget --help 2>&1 | grep -q -- ' --no-check-certificate ' && WGET_OPTS="$WGET_OPTS --no-check-certificate"
227         wget --help 2>&1 | grep -q -- ' --inet ' && WGET_OPTS="$WGET_OPTS --inet"
228         wget --help 2>&1 | grep -q -- ' --retry-connrefused ' && WGET_OPTS="$WGET_OPTS --retry-connrefused"
229         WGET_OPTS="$WGET_OPTS --user-agent=$USER_AGENT"
230
231         GETURI="wget --passive-ftp -c -nd -t$WGET_RETRIES $WGET_OPTS"
232         GETURI2="wget -c -nd -t$WGET_RETRIES $WGET_OPTS"
233         OUTFILEOPT="-O"
234 fi
235
236 GETLOCAL="cp -a"
237
238 if rpm --version 2>&1 | grep -q '4.0.[0-2]'; then
239         RPM="rpm"
240         RPMBUILD="rpm"
241 else
242         RPM="rpm"
243         RPMBUILD="rpmbuild"
244 fi
245
246 #
247 # sanity checks
248 #
249 if [ -d $HOME/rpm/SOURCES ]; then
250         echo "ERROR: ~/rpm/{SPECS,SOURCES} structure is obsolete" >&2
251         echo "ERROR: get rid of your ~/rpm/SOURCES" >&2
252         exit 1
253 fi
254
255 POLDEK_INDEX_DIR="$($RPM --eval %_rpmdir)/"
256 POLDEK_CMD="$SU_SUDO /usr/bin/poldek --noask"
257
258 run_poldek() {
259         RES_FILE=$(tempfile)
260         if [ -n "$LOGFILE" ]; then
261                 LOG=`eval echo $LOGFILE`
262                 if [ -n "$LASTLOG_FILE" ]; then
263                         echo "LASTLOG=$LOG" > $LASTLOG_FILE
264                 fi
265                 (${NICE_COMMAND} ${POLDEK_CMD} `while test $# -gt 0; do echo "$1 ";shift;done` ; echo $? > ${RES_FILE})|tee -a $LOG
266                 return $exit_pldk
267         else
268                 (${NICE_COMMAND} ${POLDEK_CMD} `while test $# -gt 0; do echo "$1 ";shift;done` ; echo $? > ${RES_FILE}) 1>&2 >/dev/null
269                 return `cat ${RES_FILE}`
270                 rm -rf ${RES_FILE}
271         fi
272 }
273
274 #---------------------------------------------
275 # functions
276
277 download_lftp() {
278         local outfile=$1 url=$2 retval tmpfile
279         # TODO: use mktemp
280         tmpfile=$outfile.tmp
281         lftp -c "
282                 $([ "$DEBUG" = "yes" ] && echo "debug 5;")
283                 set ssl:verify-certificate no;
284                 set net:max-retries $WGET_RETRIES;
285                 set http:user-agent \"$USER_AGENT\";
286                 pget -n $PARALLEL_DOWNLOADS -c \"$url\" -o \"$tmpfile\"
287         "
288
289         retval=$?
290         if [ $retval -eq 0 ]; then
291                 mv -f "$tmpfile" "$outfile"
292         else
293                 rm -f "$tmpfile"
294         fi
295         return $retval
296 }
297
298 usage() {
299         if [ -n "$DEBUG" ]; then set -xv; fi
300         echo "\
301 Usage: builder [--all-branches] [-D|--debug] [-V|--version] [--short-version]  [-a|--add_cvs] [-b|-ba|--build]
302 [-bb|--build-binary] [-bs|--build-source] [-bc] [-bi] [-bl] [-u|--try-upgrade]
303 [{-cf|--cvs-force}] [{-B|--branch} <branch>] [--depth <number>]
304 [-g|--get] [-h|--help] [--ftp] [--http] [{-l|--logtofile} <logfile>] [-m|--mr-proper]
305 [-q|--quiet] [--date <yyyy-mm-dd> [-r <tag>] [{-T|--tag <tag>]
306 [-Tvs|--tag-version-stable] [-Ts|--tag-stable] [-Tv|--tag-version]
307 [{-Tp|--tag-prefix} <prefix>] [{-tt|--test-tag}]
308 [-nu|--no-urls] [-v|--verbose] [--opts <rpm opts>] [--short-circuit]
309 [--show-bconds] [--with/--without <feature>] [--define <macro> <value>]
310 <package>[.spec][:tag]
311
312 -4                  - force ipv4 when transferring files
313 -5, --update-md5    - update md5 comments in spec, implies -nd -ncs
314 -6                  - force ipv6 when transferring files
315 -a5, --add-md5      - add md5 comments to URL sources, implies -nc -nd -ncs
316 --all-branches      - make shallow fetch of all branches; --depth required
317 -n5, --no-md5       - ignore md5 comments in spec
318 -D, --debug         - enable builder script debugging mode,
319 -debug              - produce rpm debug package (same as --opts -debug)
320 -V, --version       - output builder version string
321 --short-version     - output builder short version
322 -a, --add_vcs       - try add new package to PLD repo.
323 -b, -ba, --build    - get all files from PLD repo or HTTP/FTP and build package
324                       from <package>.spec,
325 -bb, --build-binary - get all files from PLD repo or HTTP/FTP and build binary
326                       only package from <package>.spec,
327 -bp, --build-prep   - execute the %prep phase of <package>.spec,
328 -bc                 - execute the %build phase of <package>.spec,
329 -bi                 - execute the %install phase of <package>.spec
330 -bl                 - execute the %files phase of <package>.spec
331 -bs, --build-source - get all files from PLD repo or HTTP/FTP and only pack
332                       them into src.rpm,
333 --short-circuit     - short-circuit build
334 -B, --branch        - add branch
335 -c, --clean         - clean all temporarily created files (in BUILD\$RPM_BUILD_ROOT) after rpmbuild commands.
336                       may be used with building process.
337 -m, --mr-proper     - clean all temporarily created files (in BUILD, SOURCES,
338                       SPECS and \$RPM_BUILD_ROOT). Doesn't run any rpm building.
339 -cf, --cvs-force    - use -f when tagging
340 --define <macro> <value>
341                     - define a macro <macro> with value <value>,
342 --depth <number>    - make shallow fetch
343 --alt_kernel <kernel>
344                     - same as --define 'alt_kernel <kernel>'
345 --nodeps            - rpm won't check any dependences
346 -g, --get           - get <package>.spec and all related files from PLD repo
347                       or HTTP/FTP,
348 -h, --help          - this message,
349 -jN, -j N           - set %_smp_mflags to propagate concurrent jobs
350 --ftp, --http       - use ftp or http protocol to access distfiles server
351 -l <logfile>, --logtofile <logfile>
352                     - log all to file,
353 -ncs, --no-cvs-specs
354                     - don't pull from PLD repo
355 -nd, --no-distfiles - don't download from distfiles
356 -nm, --no-mirrors   - don't download from mirror, if source URL is given,
357 -nu, --no-urls      - don't try to download from FTP/HTTP location,
358 -ns, --no-srcs      - don't download Sources/Patches
359 -ns0, --no-source0  - don't download Source0
360 -nn, --no-net       - don't download anything from the net
361 -pN, -p N           - set PARALLEL_DOWNLOADS to N (default $PARALLEL_DOWNLOADS)
362 -pm, --prefer-mirrors
363                     - prefer mirrors (if any) over distfiles for SOURCES
364 --no-init           - don't initialize builder paths (SPECS and SOURCES)
365 -ske,
366 --skip-existing-files
367                     - skip existing files in get_files
368 --opts <rpm opts>   - additional options for rpm
369 -q, --quiet         - be quiet,
370 --date yyyy-mm-dd   - build package using resources from specified date,
371 -r <tag>, --cvstag <ref>
372                     - build package using resources from specified branch/tag,
373 -A                  - build package using master branch as any sticky
374                       tags/branch/date being reset.
375 -R, --fetch-build-requires
376                     - fetch what is BuildRequired,
377 -RB, --remove-build-requires
378                     - remove all you fetched with -R or --fetch-build-requires
379                       remember, this option requires confirmation,
380 -FRB, --force-remove-build-requires
381                     - remove all you fetched with -R or --fetch-build-requires
382                       remember, this option works without confirmation,
383 -sd, --source-distfiles
384                     - list sources available from distfiles (intended for
385                       offline operations; does not work when Icon field is
386                       present but icon file is absent),
387 -sc, --source-cvs   - list sources available from PLD repo
388 -sdp, --source-distfiles-paths
389                     - list sources available from distfiles -
390                       paths relative to distfiles directory (intended for
391                       offline operations; does not work when Icon field is
392                       present but icon file is absent),
393 -sf, --source-files - list sources - bare filenames (intended for offline
394                       operations; does not work when Icon field is present
395                       but icon file is absent),
396 -lsp, --source-paths
397                     - list sources - filenames with full local paths (intended
398                       for offline operations; does not work when Icon field is
399                       present but icon file is absent),
400 -su, --source-urls  - list urls - urls to sources and patches
401                       intended for copying urls with spec with lots of macros
402                       in urls
403 -T <tag> , --tag <tag>
404                     - add git tag <tag> for files,
405 -Tvs, --tag-version-stable
406                     - add git tags STABLE and NAME-VERSION-RELEASE for files,
407 -Ts, --tag-stable
408                     - add git tag STABLE for files,
409 -Tv, --tag-version
410                     - add git tag NAME-VERSION-RELEASE for files,
411 -Tp, --tag-prefix <prefix>
412                     - add <prefix> to NAME-VERSION-RELEASE tags,
413 -tt, --test-tag <prefix>
414                     - fail if tag is already present,
415 -ir, --integer-release-only
416                     - allow only integer and snapshot releases
417 -v, --verbose       - be verbose,
418 -u, --try-upgrade   - check version, and try to upgrade package
419 -un, --try-upgrade-with-float-version
420                     - as above, but allow float version
421                       php-pear-Services_Digg/
422 --upgrade-version   - upgrade to specified version in try-upgrade
423 -U, --update        - refetch sources, don't use distfiles, and update md5
424                       comments
425 -Upi, --update-poldek-indexes
426                     - refresh or make poldek package index files.
427 -sp, --skip-patch <patchnumber>
428                     - don't apply <patchnumber>. may be repeated.
429 -np, --nopatch <patchnumber>
430                     - abort instead of applying patch <patchnumber>
431 --show-bconds       - show available conditional builds, which can be used
432                     - with --with and/or --without switches.
433 --show-bcond-args   - show active bconds, from ~/.bcondrc. this is used by
434                       ./repackage.sh script. In other words, the output is
435                       parseable by scripts.
436 --show-avail-bconds - show available bconds
437 --with/--without <feature>
438                     - conditional build package depending on %_with_<feature>/
439                       %_without_<feature> macro switch.  You may now use
440                       --with feat1 feat2 --without feat3 feat4 --with feat5
441                       constructions. Set GROUP_BCONDS to yes to make use of it.
442 --target <platform>, --target=<platform>
443                     - build for platform <platform>.
444 --init-rpm-dir      - initialize ~/rpm directory structure
445 --git-pld           - force use of PLD git and distfiles
446 --git-tld           - force use of TLD git and distfiles (note: it will fall
447                       back to PLD git/df if package doesn't exist in TLD git)
448 "
449 }
450
451 # create tempfile. as secure as possible
452 tempfile() {
453         mktemp -t builder.XXXXXX || ${TMPDIR:-/tmp}/builder.$RANDOM.$$
454 }
455
456 tempdir() {
457         mktemp -d builder.XXXXXX
458 }
459
460 # inserts git log instead of %changelog
461 # outputs name of modified file created by tempfile
462 insert_gitlog() {
463         local SPECFILE=$1 specdir=$(tempdir) gitlog=$(tempfile) speclog=$(tempfile)
464
465         # allow this being customized
466         local log_entries=$(rpm -E '%{?_buildchangelogtruncate}')
467
468         # rpm5.org/rpm.org do not parse any other date format than 'Wed Jan 1 1997'
469         # otherwise i'd use --date=iso here
470         # http://rpm5.org/cvs/fileview?f=rpm/build/parseChangelog.c&v=2.44.2.1
471         # http://rpm.org/gitweb?p=rpm.git;a=blob;f=build/parseChangelog.c#l31
472         # NOTE: changelog date is always in UTC for rpmbuild
473         # * 1265749244 +0000 Random Hacker <nikt@pld-linux.org> 9370900
474         git rev-list -${log_entries:-20} HEAD | while read sha1; do
475                 local logfmt='%B%n'
476                 git notes list $sha1 1>/dev/null 2>&1 && logfmt=%N
477                 git log -n 1 $sha1 --format=format:"* %ad %an <%ae> %h%n${logfmt}%n" --date=raw | sed '/^$/q'
478         done > $gitlog
479         LC_ALL=C gawk '/^\* /{printf("* %s %s\n", strftime("%a %b %d %Y", $2), substr($0, length($1)+length($2)+length($3)+4)); next}{print}' $gitlog > $speclog
480         sed '/^%changelog/,$d' $SPECFILE | sed -e "\${
481                         a%changelog
482                         r $speclog
483                 }
484         " > $specdir/$SPECFILE
485         rm -f $gitlog $speclog
486         echo $specdir
487 }
488
489 # change dependency to specname
490 # common changes:
491 # - perl(Package::Name) -> perl-Package-Name
492 depspecname() {
493         local package="$1"
494
495         package=$(echo "$package" | sed -e '/perl(.*)/{s,perl(\(.*\)),perl-\1,;s,::,-,g};' -e 's/-\(devel\|static\)$//' )
496         echo "$package"
497 }
498
499 update_shell_title() {
500         [ -t 1 ] || return
501         local len=${COLUMNS:-80}
502         local msg="$(echo "$*" | cut -c-$len)"
503
504         if [ -n "$BE_VERBOSE" ]; then
505                 echo >&2 "$(date +%s.%N) $*"
506         fi
507
508         if [ "x$TITLECHANGE" = "xyes" -o "x$TITLECHANGE" = "x" ]; then
509                 local pkg
510                 if [ -n "$PACKAGE_NAME" ]; then
511                         pkg=${PACKAGE_NAME}-${PACKAGE_VERSION}-${PACKAGE_RELEASE}
512                 else
513                         pkg=${SPECFILE}
514                 fi
515
516                 msg="$pkg: ${SHELL_TITLE_PREFIX:+$SHELL_TITLE_PREFIX }$msg"
517                 msg=$(echo $msg | tr -d '\n\r')
518                 case "$TERM" in
519                         cygwin|xterm*)
520                         echo >&2 -ne "\033]1;$msg\007\033]2;$msg\007"
521                 ;;
522                         screen*)
523                         echo >&2 -ne "\033]0;$msg\007"
524                 ;;
525                 esac
526         fi
527 }
528
529 # set TARGET from BuildArch: from SPECFILE
530 set_spec_target() {
531         if [ -n "$SPECFILE" ] && [ -z "$TARGET" ]; then
532                 tmp=$(awk '/^BuildArch:/ { print $NF; exit }' $ASSUMED_NAME/$SPECFILE)
533                 if [ "$tmp" ]; then
534                                 target_platform=$(rpm -E '%{_target_vendor}-%{_target_os}%{?_gnu}')
535                                 TARGET="$tmp"
536                                 case "$RPMBUILD" in
537                                 "rpmbuild")
538                                         TARGET_SWITCH="--target ${TARGET}-${target_platform}" ;;
539                                 "rpm")
540                                         TARGET_SWITCH="--target=$TARGET" ;;
541                                 esac
542                 fi
543         fi
544 }
545
546 # runs rpm with minimal macroset
547 minirpm() {
548         # we reset macros not to contain macros.build as all the %() macros are
549         # executed here, while none of them are actually needed.
550         # at the time of this writing macros.build + macros contained 70 "%(...)" macros.
551         safe_macrofiles=$(rpm $TARGET_SWITCH --showrc | awk -F: '/^macrofiles/ { gsub(/^macrofiles[ \t]+:/, "", $0); gsub(/:.*macros.build:/, ":", $0); print $0 } ')
552
553         # TODO: move these to /usr/lib/rpm/macros
554         cat > $BUILDER_MACROS <<'EOF'
555 %x8664 x86_64 amd64 ia32e
556 %alt_kernel %{nil}
557 %_alt_kernel %{nil}
558 %bootstrap_release() %{1}
559 %requires_releq_kernel_up(s:n:) %{nil}
560 %requires_releq_kernel_smp(s:n:) %{nil}
561 %requires_releq_kernel(s:n:) %{nil}
562 %requires_releq() %{nil}
563 %pyrequires_eq() %{nil}
564 %requires_eq() %{nil}
565 %requires_eq_to() %{nil}
566 %requires_ge() %{nil}
567 %requires_ge_to() %{nil}
568 %requires_ge() %{nil}
569 %releq_kernel_up(n:) ERROR
570 %releq_kernel_smp(n:) ERROR
571 %releq_kernel(n:) ERROR
572 %kgcc_package ERROR
573 %_fontsdir ERROR
574 %ruby_version ERROR
575 %ruby_ver_requires_eq() %{nil}
576 %ruby_mod_ver_requires_eq() %{nil}
577 %__php_api_requires() %{nil}
578 %php_major_version ERROR
579 %php_api_version ERROR
580 %requires_xorg_xserver_extension %{nil}
581 %requires_xorg_xserver_xinput %{nil}
582 %requires_xorg_xserver_font %{nil}
583 %requires_xorg_xserver_videodrv %{nil}
584 %py_ver ERROR
585 %perl_vendorarch ERROR
586 %perl_vendorlib ERROR
587 # damn. need it here! - copied from /usr/lib/rpm/macros.build
588 %tmpdir         %(echo "${TMPDIR:-/tmp}")
589 %patchset_source(f:b:) %(
590         base=%{-b*}%{!-b*:10000};
591         start=$(expr $base + %1);
592         end=$(expr $base + %{?2}%{!?2:%{1}});
593         # we need to call seq twice as it doesn't allow two formats
594         seq -f 'Patch%g:' $start $end > %{tmpdir}/__ps1;
595         seq -f '%{-f*}' %1 %{?2}%{!?2:%{1}} > %{tmpdir}/__ps2;
596         paste %{tmpdir}/__ps{1,2};
597         rm -f %{tmpdir}/__ps{1,2};
598 ) \
599 %{nil}
600 %add_etc_shells(p) %{p:<lua>}
601 %remove_etc_shells(p) %{p:<lua>}
602 %lua_add_etc_shells()  %{nil}
603 %lua_remove_etc_shells() %{nil}
604 %required_jdk %{nil}
605 %buildrequires_jdk %{nil}
606 %pear_package_print_optionalpackages %{nil}
607 EOF
608         if [ "$NOINIT" = "yes" ] ; then
609                 cat >> $BUILDER_MACROS <<'EOF'
610 %_specdir ./
611 %_sourcedir ./
612 EOF
613         fi
614         eval $RPMBUILD $TARGET_SWITCH --macros "$safe_macrofiles:$BUILDER_MACROS" $QUIET $RPMOPTS $RPMBUILDOPTS $BCOND $* 2>&1
615 }
616
617 cache_rpm_dump() {
618         if [ -n "$DEBUG" ]; then
619                 set -x
620                 set -v
621         fi
622
623         if [ -x /usr/bin/rpm-specdump ]; then
624                 update_shell_title "cache_rpm_dump using rpm-specdump command"
625                 rpm_dump_cache=$(rpm-specdump $TARGET_SWITCH $BCOND $SPECFILE)
626         else
627                 update_shell_title "cache_rpm_dump using rpmbuild command"
628                 local rpm_dump
629                 rpm_dump=`
630                         # what we need from dump is NAME, VERSION, RELEASE and PATCHES/SOURCES.
631                         dump='%{echo:dummy: PACKAGE_NAME %{name} }%dump'
632                         case "$RPMBUILD" in
633                         rpm)
634                                 ARGS='-bp'
635                                 ;;
636                         rpmbuild)
637                                 ARGS='--nodigest --nosignature --nobuild'
638                                 ;;
639                         esac
640                         minirpm $ARGS --define "'prep $dump'" --nodeps $SPECFILE
641                 `
642                 if [ $? -gt 0 ]; then
643                         error=$(echo "$rpm_dump" | sed -ne '/^error:/,$p')
644                         echo "$error" >&2
645                         Exit_error err_build_fail
646                 fi
647
648                 # make small dump cache
649                 rpm_dump_cache=`echo "$rpm_dump" | awk '
650                         $2 ~ /^SOURCEURL/ {print}
651                         $2 ~ /^PATCHURL/  {print}
652                         $2 ~ /^nosource/ {print}
653                         $2 ~ /^PACKAGE_/ {print}
654                 '`
655         fi
656
657         update_shell_title "cache_rpm_dump: OK!"
658 }
659
660 rpm_dump() {
661         if [ -z "$rpm_dump_cache" ] ; then
662                 echo >&2 "internal error: cache_rpm_dump not called! (missing %prep?)"
663         fi
664         echo "$rpm_dump_cache"
665 }
666
667 get_icons() {
668         update_shell_title "get icons"
669         ICONS=$(awk '/^Icon:/ {print $2}' $PACKAGE_DIR/${SPECFILE})
670         if [ -z "$ICONS" ]; then
671                 return
672         fi
673
674         rpm_dump_cache="kalasaba" NODIST="yes" get_files $ICONS
675 }
676
677 parse_spec() {
678         update_shell_title "parsing specfile"
679         if [ -n "$DEBUG" ]; then
680                 set -x
681                 set -v
682         fi
683
684         # icons are needed for successful spec parse
685         get_icons
686
687         cd $PACKAGE_DIR
688         cache_rpm_dump
689
690         if rpm_dump | grep -qEi ":.*nosource.*1"; then
691                 FAIL_IF_NO_SOURCES="no"
692         fi
693
694         if [ "$NOSRCS" != "yes" ]; then
695                 SOURCES=$(rpm_dump | awk '$2 ~ /^SOURCEURL[0-9]+/ {print substr($2, length("SOURCEURL") + 1), $3}' | LC_ALL=C sort -n | awk '{print $2}')
696                 PATCHES=$(rpm_dump | awk '$2 ~ /^PATCHURL[0-9]+/ {print substr($2, length("PATCHURL") + 1), $3}' | LC_ALL=C sort -n | awk '{print $2}')
697                 ICONS=$(awk '/^Icon:/ {print $2}' ${SPECFILE})
698         fi
699
700         PACKAGE_NAME=$(rpm_dump | awk '$2 == "PACKAGE_NAME" { print $3; exit}')
701         PACKAGE_VERSION=$(rpm_dump | awk '$2 == "PACKAGE_VERSION" { print $3; exit}')
702         PACKAGE_RELEASE=$(rpm_dump | awk '$2 == "PACKAGE_RELEASE" { print $3; exit}')
703
704         if [ "$PACKAGE_NAME" != "$ASSUMED_NAME" ]; then
705                 echo >&2 "WARNING! Spec name ($ASSUMED_NAME) does not agree with package name ($PACKAGE_NAME)"
706         fi
707
708         if [ -n "$BE_VERBOSE" ]; then
709                 echo "- Sources :  `nourl $SOURCES`"
710                 if [ -n "$PATCHES" ]; then
711                         echo "- Patches :  `nourl $PATCHES`"
712                 else
713                         echo "- Patches :  *no patches needed*"
714                 fi
715                 if [ -n "$ICONS" ]; then
716                         echo "- Icon    :  `nourl $ICONS`"
717                 else
718                         echo "- Icon    :  *no package icon*"
719                 fi
720                 echo "- Name    : $PACKAGE_NAME"
721                 echo "- Version : $PACKAGE_VERSION"
722                 echo "- Release : $PACKAGE_RELEASE"
723         fi
724
725         update_shell_title "parse_spec: OK!"
726 }
727
728 Exit_error() {
729         if [ -n "$DEBUG" ]; then
730                 set -x
731                 set -v
732         fi
733
734         cd "$__PWD"
735
736         case "$1" in
737                 "err_no_spec_in_cmdl" )
738                         remove_build_requires
739                         echo >&2 "ERROR: spec file name not specified."
740                         exit 2 ;;
741                 "err_invalid_cmdline" )
742                         echo >&2 "ERROR: invalid command line arg ($2)."
743                         exit 2 ;;
744                 "err_no_spec_in_repo" )
745                         remove_build_requires
746                         echo >&2 "Error: spec file not stored in PLD repo."
747                         exit 3 ;;
748                 "err_no_source_in_repo" )
749                         remove_build_requires
750                         echo >&2 "Error: some source, patch or icon files not stored in PLD repo. ($2)"
751                         exit 4 ;;
752                 "err_cvs_add_failed" )
753                         echo >&2 "Error: failed to add package to PLD repo."
754                         exit 4 ;;
755                 "err_build_fail" )
756                         remove_build_requires
757                         echo >&2 "Error: package build failed. (${2:-no more info})"
758                         exit 5 ;;
759                 "err_no_package_data" )
760                         remove_build_requires
761                         echo >&2 "Error: couldn't get out package name/version/release from spec file."
762                         exit 6 ;;
763                 "err_tag_exists" )
764                         remove_build_requires
765                         echo >&2 "Tag ${2} already exists"
766                         exit 9 ;;
767                 "err_fract_rel" )
768                         remove_build_requires
769                         echo >&2 "Release ${2} not integer and not a snapshot."
770                         exit 10 ;;
771                 "err_branch_exists" )
772                         remove_build_requires
773                         echo >&2 "Tree branch already exists (${2})."
774                         exit 11 ;;
775                 "err_acl_deny" )
776                         remove_build_requires
777                         echo >&2 "Error: conditions reject building this spec (${2})."
778                         exit 12 ;;
779                 "err_remote_problem" )
780                         remove_build_requires
781                         echo >&2 "Error: problem with remote (${2})"
782                         exit 13 ;;
783                 "err_not_implemented" )
784                         remove_build_requires
785                         echo >&2 "Error: functionality not yet imlemented"
786                         exit 110 ;;
787         esac
788         echo >&2 "Unknown error."
789         exit 100
790 }
791
792 init_builder() {
793         if [ -n "$DEBUG" ]; then
794                 set -x
795                 set -v
796         fi
797
798         if [ "$NOINIT" != "yes" ] ; then
799                 TOP_DIR=$(eval $RPM $RPMOPTS --eval '%{_topdir}')
800
801                 local macros_ver=$(rpm -E %?rpm_build_macros)
802                 if [ -z "$macros_ver" ]; then
803                         REPO_DIR=$TOP_DIR/packages
804                         PACKAGE_DIR=$TOP_DIR/packages/$ASSUMED_NAME
805                 else
806                         if awk "BEGIN{exit($macros_ver>=$RPM_MACROS_VER)}"; then
807                                 echo >&2 "builder requires rpm-build-macros >= $RPM_MACROS_VER"
808                                 exit 1
809                         fi
810                         REPO_DIR=$TOP_DIR
811                         PACKAGE_DIR=$REPO_DIR/$ASSUMED_NAME
812                 fi
813         else
814                 REPO_DIR="."
815                 PACKAGE_DIR="."
816         fi
817         export GIT_WORK_TREE=$PACKAGE_DIR
818         export GIT_DIR=$PACKAGE_DIR/.git
819
820         if [ -d "$GIT_DIR" ] && [ -z "$CVSTAG" ]; then
821                 if CVSTAG=$(GIT_DIR=$GIT_DIR git symbolic-ref HEAD) 2>/dev/null; then
822                         CVSTAG=${CVSTAG#refs/heads/}
823                         if [ "$CVSTAG" != "master" ]; then
824                                 echo >&2 "builder: Active branch $CVSTAG. Use -r BRANCHNAME to override"
825                         fi
826                 else
827                         echo >&2 "On detached HEAD. Use -r BRANCHNAME to override"
828                         HEAD_DETACHED="yes"
829                 fi
830         elif [ "$CVSTAG" = "HEAD" ]; then
831                 # assume -r HEAD is same as -A
832                 CVSTAG="master"
833         fi
834
835         __PWD=$(pwd)
836 }
837
838 create_git_repo() {
839         update_shell_title "add_package"
840
841         if [ -n "$DEBUG" ]; then
842                 set -x
843                 set -v
844         fi
845
846         cd "$REPO_DIR"
847         SPECFILE=$(basename $SPECFILE)
848         if [ ! -f "$ASSUMED_NAME/$SPECFILE" ]; then
849                 echo "ERROR: No package to add ($ASSUMED_NAME/$SPECFILE)" >&2
850                 exit 101
851         fi
852         [ -d "$ASSUMED_NAME/.git" ] || NEW_REPO=yes
853         # ssh $GIT_SERVER create ${ASSUMED_NAME} || Exit_error err_cvs_add_failed
854         git init
855         git remote add $REMOTE_PLD ${GIT_SERVER}/${PACKAGES_DIR}/${ASSUMED_NAME}.git && \
856                 git remote set-url --push  $REMOTE_PLD ssh://${GIT_PUSH}/${PACKAGES_DIR}/${ASSUMED_NAME} \
857                 || Exit_error err_remote_problem $REMOTE_PLD
858 }
859
860 get_spec() {
861
862         update_shell_title "get_spec"
863
864         if [ -n "$DEBUG" ]; then
865                 set -x
866                 set -v
867         fi
868
869         cd "$REPO_DIR"
870         if [ ! -f "$ASSUMED_NAME/$SPECFILE" ]; then
871                 # XXX: still needed?
872                 SPECFILE=$(basename $SPECFILE)
873         fi
874
875         if [ "$NOCVSSPEC" != "yes" ]; then
876                 if [ -z "$DEPTH" ]; then
877                         if [ -d "$ASSUMED_NAME/.git" ]; then
878                                 git fetch $REMOTE_PLD || Exit_error err_no_spec_in_repo
879                         elif [ "$ADD_PACKAGE_CVS" = "yes" ]; then
880                                 if [ ! -r "$ASSUMED_NAME/$SPECFILE" ]; then
881                                         echo "ERROR: No package to add ($ASSUMED_NAME/$SPECFILE)" >&2
882                                         exit 101
883                                 fi
884                                 Exit_error err_not_implemented
885                         else
886                                 (
887                                         unset GIT_WORK_TREE
888                                         git clone  -o $REMOTE_PLD ${GIT_SERVER}/${PACKAGES_DIR}/${ASSUMED_NAME}.git || {
889                                                 # softfail if new package, i.e not yet added to PLD rep
890                                                 [ ! -f "$ASSUMED_NAME/$SPECFILE" ] && Exit_error err_no_spec_in_repo
891                                                 echo "Warning: package not in CVS - assuming new package"
892                                                 NOCVSSPEC="yes"
893                                         }
894                                         git remote set-url --push  $REMOTE_PLD ssh://${GIT_PUSH}/${PACKAGES_DIR}/${ASSUMED_NAME}
895                                 )
896                         fi
897                 else
898                         if [ ! -d "$ASSUMED_NAME/.git" ]; then
899                                 if [ ! -d "$ASSUMED_NAME" ]; then
900                                         mkdir $ASSUMED_NAME
901                                 fi
902                                 git init
903                                 git remote add $REMOTE_PLD ${GIT_SERVER}:${PACKAGES_DIR}/${ASSUMED_NAME}.git
904                                 CVSTAG=${CVSTAG:-"master"}
905                         fi
906                         local refs=''
907                         if [ -z "$ALL_BRANCHES" ]; then
908                                 refs="${CVSTAG}:remotes/${REMOTE_PLD}/${CVSTAG}"
909                         fi
910                         git fetch $DEPTH $REMOTE_PLD $refs || {
911                                 echo >&2 "Error: branch $CVSTAG does not exist"
912                                 exit 3
913                         }
914                 fi
915                 git fetch $REMOTE_PLD 'refs/notes/*:refs/notes/*'
916
917                 cvsignore_df .gitignore
918
919                 # add default log format to .gitignore if it is relative to package dir
920                 if [ -n "$LOGFILE" -a "$LOGFILE" = "${LOGFILE##*/}" ]; then
921                         # substitute known "macros" to glob
922                         local logfile=$(echo "$LOGFILE" | sed -e 's,\$\(PACKAGE_NAME\|DATE\),*,g')
923                         if [ "$logfile" ]; then
924                                 cvsignore_df "$logfile"
925                         fi
926                 fi
927
928                 # create symlinks for tools
929                 if [ "$SYMLINK_TOOLS" != "no" ]; then
930                         for a in dropin md5 adapter builder {relup,compile,repackage,pearize}.sh pldnotify.awk; do
931                                 # skip tools that don't exist in top dir
932                                 [ -f $a ] || continue
933                                 # skip tools that already exist
934                                 [ -f $ASSUMED_NAME/$a ] && continue
935                                 ln -s ../$a $ASSUMED_NAME
936                                 cvsignore_df $a
937                         done
938                 fi
939         fi
940
941         if [ -n "$CVSTAG" ]; then
942                 git checkout "$CVSTAG" -- 2>/dev/null || git checkout -t "${REMOTE_PLD}/$CVSTAG" > /dev/null || exit
943                 git symbolic-ref -q HEAD > /dev/null &&
944                         git merge '@{u}'
945                 if [ -n "$CVSDATE" ]; then
946                         git checkout $(git rev-list -n1 --before="'$CVSDATE'" $CVSTAG) || exit 1
947                 fi
948         fi
949
950         if [ ! -f "$ASSUMED_NAME/$SPECFILE" ]; then
951                 Exit_error err_no_spec_in_repo
952         fi
953
954         if [ "$CHMOD" = "yes" -a -n "$SPECFILE" ]; then
955                 chmod $CHMOD_MODE $ASSUMED_NAME/$SPECFILE
956         fi
957         unset OPTIONS
958         [ -n "$DONT_PRINT_REVISION" ] || grep -E -m 1 "^#.*Revision:.*Date" $ASSUMED_NAME/$SPECFILE
959
960         set_spec_target
961 }
962
963 find_mirror() {
964         cd "$REPO_DIR"
965         local url="$1"
966         if [ ! -f "mirrors"  ] ; then
967                 ln -s scripts/mirrors .
968         fi
969
970         IFS="|"
971         local origin mirror name rest ol prefix
972         while read origin mirror name rest; do
973                 # skip comments and empty lines
974                 if [ -z "$origin" ] || [ "${origin#\#}" != "$origin" ]; then
975                         continue
976                 fi
977                 ol=$(echo -n "$origin" | wc -c)
978                 prefix=$(echo -n "$url" | head -c $ol)
979                 if [ "$prefix" = "$origin" ] ; then
980                         suffix=$(echo "$url" | cut -b $((ol+1))-)
981                         echo -n "$mirror$suffix"
982                         return 0
983                 fi
984         done < mirrors
985         echo "$url"
986 }
987
988 # Warning: unpredictable results if same URL used twice
989 src_no() {
990         local file="$1"
991         # escape some regexp characters if part of file name
992         file=$(echo "$file" | sed -e 's#\([\+\*\.\&\#\?]\)#\\\1#g')
993         cd $PACKAGE_DIR
994         rpm_dump | \
995         grep -E "(SOURCE|PATCH)URL[0-9]*[       ]*${file}""[    ]*$" | \
996         sed -e 's/.*\(SOURCE\|PATCH\)URL\([0-9][0-9]*\).*/\1\2/' | \
997         head -n 1 | tr OURCEATH ourceath | xargs
998 }
999
1000 src_md5() {
1001         [ "$NO5" = "yes" ] && return
1002         no=$(src_no "$1")
1003         [ -z "$no" ] && return
1004         cd $PACKAGE_DIR
1005         local md5
1006
1007         if [ -f additional-md5sums ]; then
1008                 md5=$(grep -s -v '^#' additional-md5sums | \
1009                 grep -E "[      ]$(basename "$1")([     ,]|\$)" | \
1010                 sed -e 's/^\([0-9a-f]\{32\}\).*/\1/' | \
1011                 grep -E '^[0-9a-f]{32}$')
1012
1013                 if [ "$md5" ]; then
1014                         if [ $(echo "$md5" | wc -l) != 1 ] ; then
1015                                 echo "$SPECFILE: more then one entry in additional-md5sums for $1" 1>&2
1016                         fi
1017                         echo "$md5" | tail -n 1
1018                         return
1019                 fi
1020         fi
1021
1022         source_md5=$(grep -iE "^#[      ]*(No)?$no-md5[         ]*:" $SPECFILE | sed -e 's/.*://')
1023         if [ -n "$source_md5" ]; then
1024                 echo $source_md5
1025         else
1026                 source_md5=`grep -i "BuildRequires:[    ]*digest(%SOURCE$no)[   ]*=" $SPECFILE | sed -e 's/.*=//'`
1027                 if [ -n "$source_md5" ]; then
1028                         echo $source_md5
1029                 else
1030                         # we have empty SourceX-md5, but it is still possible
1031                         # that we have NoSourceX-md5 AND NoSource: X
1032                         nosource_md5=`grep -i "^#[       ]*No$no-md5[    ]*:" $SPECFILE | sed -e 's/.*://'`
1033                         if [ -n "$nosource_md5" -a -n "`grep -i "^NoSource:[     ]*$no$" $SPECFILE`" ] ; then
1034                                 echo $nosource_md5
1035                         fi
1036                 fi
1037         fi
1038 }
1039
1040 distfiles_path() {
1041         echo "by-md5/$(src_md5 "$1" | sed -e 's|^\(.\)\(.\)|\1/\2/&|')/$(basename "$1")"
1042 }
1043
1044 distfiles_url() {
1045         echo "$PROTOCOL$DISTFILES_SERVER/distfiles/$(distfiles_path "$1")"
1046 }
1047
1048 distfiles_attic_url() {
1049         echo "$PROTOCOL$ATTICDISTFILES_SERVER/distfiles/Attic/$(distfiles_path "$1")"
1050 }
1051
1052 good_md5() {
1053         md5=$(src_md5 "$1")
1054         [ "$md5" = "" ] || \
1055         [ "$md5" = "$(md5sum $(nourl "$1") 2> /dev/null | sed -e 's/ .*//')" ]
1056 }
1057
1058 good_size() {
1059         size=$(find $(nourl "$1") -printf "%s" 2>/dev/null)
1060         [ -n "$size" -a "$size" -gt 0 ]
1061 }
1062
1063 cvsignore_df() {
1064         if [ "$CVSIGNORE_DF" != "yes" ]; then
1065                 return
1066         fi
1067         cvsignore=${PACKAGE_DIR}/.gitignore
1068
1069         # add only if not yet there
1070         if ! awk -vf="$1" -vc=1 '$0 == f { c = 0 } END { exit c }' $cvsignore 2>/dev/null; then
1071                 echo "$1" >> $cvsignore
1072         fi
1073 }
1074
1075 # returns true if "$1" is ftp, http or https protocol url
1076 is_url() {
1077         case "$1" in
1078         ftp://*|http://*|https://*)
1079                 return 0
1080         ;;
1081         esac
1082         return 1
1083 }
1084
1085 update_md5() {
1086         if [ $# -eq 0 ]; then
1087                 return
1088         fi
1089
1090         update_shell_title "update md5"
1091         if [ -n "$DEBUG" ]; then
1092                 set -x
1093                 set -v
1094         fi
1095
1096         cd "$PACKAGE_DIR"
1097
1098         # pass 1: check files to be fetched
1099         local todo
1100         local need_files
1101         for i in "$@"; do
1102                 local fp=$(nourl "$i")
1103                 local srcno=$(src_no "$i")
1104                 if [ -n "$ADD5" ]; then
1105                         [ "$fp" = "$i" ] && continue # FIXME what is this check doing?
1106                         grep -qiE '^#[  ]*'$srcno'-md5[         ]*:' $PACKAGE_DIR/$SPECFILE && continue
1107                         grep -qiE '^BuildRequires:[     ]*digest[(]%SOURCE'$srcno'[)][  ]*=' $PACKAGE_DIR/$SPECFILE && continue
1108                 else
1109                         grep -qiE '^#[  ]*'$srcno'-md5[         ]*:' $PACKAGE_DIR/$SPECFILE || grep -qiE '^BuildRequires:[      ]*digest[(]%SOURCE'$srcno'[)][  ]*=' $PACKAGE_DIR/$SPECFILE || continue
1110                 fi
1111                 if [ ! -f "$fp" ] || [ $ALWAYS_CVSUP = "yes" ]; then
1112                         need_files="$need_files $i"
1113                 fi
1114         done
1115
1116         # pass 1a: get needed files
1117         if [ "$need_files" ]; then
1118                 get_files $need_files
1119         fi
1120
1121         # pass 2: proceed with md5 adding or updating
1122         for i in "$@"; do
1123                 local fp=$(nourl "$i")
1124                 local srcno=$(src_no "$i")
1125                 local md5=$(grep -iE '^#[       ]*(No)?'$srcno'-md5[    ]*:' $PACKAGE_DIR/$SPECFILE )
1126                 if [ -z "$md5" ]; then
1127                         md5=$(grep -iE '^[      ]*BuildRequires:[       ]*digest[(]%SOURCE'$srcno'[)][  ]*=' $PACKAGE_DIR/$SPECFILE )
1128                 fi
1129                 if [ -n "$ADD5" ] && is_url $i || [ -n "$md5" ]; then
1130                         local tag="# $srcno-md5:\t"
1131                         if [[ "$md5" == *NoSource* ]]; then
1132                                 tag="# No$srcno-md5:\t"
1133                         elif [ -n "$USEDIGEST" ]; then
1134                                 tag="BuildRequires:\tdigest(%SOURCE$srcno) = "
1135                         fi
1136                         md5=$(md5sum "$fp" | cut -f1 -d' ')
1137                         echo "Updating $srcno ($md5: $fp)."
1138                         perl -i -ne '
1139                                 print unless (/^\s*#\s*(No)?'$srcno'-md5\s*:/i or /^\s*BuildRequires:\s*digest\(%SOURCE'$srcno'\)/i);
1140                                 print "'"$tag$md5"'\n" if /^'$srcno'\s*:\s+/i;
1141                         ' \
1142                         $PACKAGE_DIR/$SPECFILE
1143                 fi
1144         done
1145 }
1146
1147 check_md5() {
1148         local bad
1149         [ "$NO5" = "yes" ] && return
1150
1151         update_shell_title "check md5"
1152
1153         for i in "$@"; do
1154                 bad=0
1155                 if ! good_md5 "$i"; then
1156                         echo -n "MD5 sum mismatch."
1157                         bad=1
1158                 fi
1159                 if ! good_size "$i"; then
1160                         echo -n "0 sized file."
1161                         bad=1
1162                 fi
1163
1164                 if [ $bad -eq 1 ]; then
1165                         echo " Use -U to refetch sources,"
1166                         echo "or -5 to update md5 sums, if you're sure files are correct."
1167                         Exit_error err_no_source_in_repo $i
1168                 fi
1169         done
1170 }
1171
1172 get_files() {
1173         update_shell_title "get_files"
1174
1175         if [ -n "$DEBUG" ]; then
1176                 set -x
1177                 set -v
1178         fi
1179
1180         if [ $# -gt 0 ]; then
1181                 cd "$PACKAGE_DIR"
1182
1183                 local nc=0
1184                 local get_files_cvs=""
1185                 for i in "$@"; do
1186                         nc=$((nc + 1))
1187                         local cvsup=0
1188                         SHELL_TITLE_PREFIX="get_files[$nc/$#]"
1189                         update_shell_title "$i"
1190                         local fp=`nourl "$i"`
1191                         if [ "$SKIP_EXISTING_FILES" = "yes" ] && [ -f "$fp" ]; then
1192                                 continue
1193                         fi
1194
1195                         FROM_DISTFILES=0
1196                         local srcmd5=$(src_md5 "$i")
1197
1198                         # we know if source/patch is present in cvs/distfiles
1199                         # - has md5 (in distfiles)
1200                         # - in cvs... ideas?
1201
1202                         # CHECK: local file didn't exist or always cvs up (first) requested.
1203                         if [ ! -f "$fp" ] || [ $ALWAYS_CVSUP = "yes" ]; then
1204                                 if echo $i | grep -vE '(http|ftp|https|cvs|svn)://' | grep -qE '\.(gz|bz2)$']; then
1205                                         echo "Warning: no URL given for $i"
1206                                 fi
1207                                 target="$fp"
1208
1209                                 if [ -z "$NODIST" ] && [ -n "$srcmd5" ]; then
1210                                         if good_md5 "$i" && good_size "$i"; then
1211                                                 echo "$fp having proper md5sum already exists"
1212                                                 continue
1213                                         fi
1214
1215                                         # optionally prefer mirror over distfiles if there's mirror
1216                                         # TODO: build url list and then try each url from the list
1217                                         if [ -n "$PREFMIRRORS" ] && [ -z "$NOMIRRORS" ] && im=$(find_mirror "$i") && [ "$im" != "$i" ]; then
1218                                                 url="$im"
1219                                         else
1220                                                 url=$(distfiles_url "$i")
1221                                         fi
1222
1223                                         url_attic=$(distfiles_attic_url "$i")
1224                                         FROM_DISTFILES=1
1225                                         # is $url local file?
1226                                         if [[ "$url" = [./]* ]]; then
1227                                                 update_shell_title "${GETLOCAL%% *}: $url"
1228                                                 ${GETLOCAL} $url $target
1229                                         else
1230                                                 if [ -z "$NOMIRRORS" ]; then
1231                                                         url=$(find_mirror "$url")
1232                                                 fi
1233
1234                                                 local uri=${url}
1235                                                 # make shorter message for distfiles urls
1236                                                 if [[ "$uri" = ${PROTOCOL}${DISTFILES_SERVER}* ]] || [[ "$uri" = ${PROTOCOL}${ATTICDISTFILES_SERVER}* ]]; then
1237                                                         uri=${uri#${PROTOCOL}${DISTFILES_SERVER}/distfiles/by-md5/?/?/*/}
1238                                                         uri=${uri#${PROTOCOL}${ATTICDISTFILES_SERVER}/distfiles/by-md5/?/?/*/}
1239                                                         uri="df: $uri"
1240                                                 fi
1241                                                 update_shell_title "${GETURI%% *}: $uri"
1242                                                 ${GETURI} ${OUTFILEOPT} "$target" "$url" || \
1243                                                 if [ "`echo $url | grep -E 'ftp://'`" ]; then
1244                                                         update_shell_title "${GETURI2%% *}: $url"
1245                                                         ${GETURI2} ${OUTFILEOPT} "$target" "$url"
1246                                                 fi
1247                                         fi
1248
1249                                         # is it empty file?
1250                                         if [ ! -s "$target" ]; then
1251                                                 rm -f "$target"
1252                                                 if [ `echo $url_attic | grep -E '^(\.|/)'` ]; then
1253                                                         update_shell_title "${GETLOCAL%% *}: $url_attic"
1254                                                         ${GETLOCAL} $url_attic $target
1255                                                 else
1256                                                         if [ -z "$NOMIRRORS" ]; then
1257                                                                 url_attic=$(find_mirror "$url_attic")
1258                                                         fi
1259                                                         update_shell_title "${GETURI%% *}: $url_attic"
1260                                                         ${GETURI} ${OUTFILEOPT} "$target" "$url_attic" || \
1261                                                         if [ "`echo $url_attic | grep -E 'ftp://'`" ]; then
1262                                                                 update_shell_title "${GETURI2%% *}: $url_attic"
1263                                                                 ${GETURI2} ${OUTFILEOPT} "$target" "$url_attic"
1264                                                         fi
1265                                                         test -s "$target" || rm -f "$target"
1266                                                 fi
1267                                         fi
1268
1269                                         if [ -s "$target" ]; then
1270                                                 cvsignore_df $target
1271                                         else
1272                                                 rm -f "$target"
1273                                                 FROM_DISTFILES=0
1274                                         fi
1275                                 fi
1276
1277                                 if [ -z "$NOURLS" ] && [ ! -f "$fp" -o -n "$UPDATE" ] && [ "`echo $i | grep -E 'ftp://|http://|https://'`" ]; then
1278                                         if [ -z "$NOMIRRORS" ]; then
1279                                                 im=$(find_mirror "$i")
1280                                         else
1281                                                 im="$i"
1282                                         fi
1283                                         update_shell_title "${GETURI%% *}: $im"
1284                                         ${GETURI} ${OUTFILEOPT} "$target" "$im" || \
1285                                         if [ "`echo $im | grep -E 'ftp://'`" ]; then
1286                                                 update_shell_title "${GETURI2%% *}: $im"
1287                                                 ${GETURI2} ${OUTFILEOPT} "$target" "$im"
1288                                         fi
1289                                         test -s "$target" || rm -f "$target"
1290                                 fi
1291
1292                                 if [ "$cvsup" = 1 ]; then
1293                                         continue
1294                                 fi
1295
1296                         fi
1297
1298                         # the md5 check must be moved elsewhere as if we've called from update_md5 the md5 is wrong.
1299                         if [ ! -f "$fp" -a "$FAIL_IF_NO_SOURCES" != "no" ]; then
1300                                 Exit_error err_no_source_in_repo $i
1301                         fi
1302
1303                         # we check md5 here just only to refetch immediately
1304                         if good_md5 "$i" && good_size "$i"; then
1305                                 :
1306                         elif [ "$FROM_DISTFILES" = 1 ]; then
1307                                 # wrong md5 from distfiles: remove the file and try again
1308                                 # but only once ...
1309                                 echo "MD5 sum mismatch. Trying full fetch."
1310                                 FROM_DISTFILES=2
1311                                 rm -f $target
1312                                 update_shell_title "${GETURI%% *}: $url"
1313                                 ${GETURI} ${OUTFILEOPT} "$target" "$url" || \
1314                                 if [ "`echo $url | grep -E 'ftp://'`" ]; then
1315                                         update_shell_title "${GETURI2%% *}: $url"
1316                                         ${GETURI2} ${OUTFILEOPT} "$target" "$url"
1317                                 fi
1318                                 if [ ! -s "$target" ]; then
1319                                         rm -f "$target"
1320                                         update_shell_title "${GETURI%% *}: $url_attic"
1321                                         ${GETURI} ${OUTFILEOPT} "$target" "$url_attic" || \
1322                                         if [ "`echo $url_attic | grep -E 'ftp://'`" ]; then
1323                                                 update_shell_title "${GETURI2%% *}: $url_attic"
1324                                                 ${GETURI2} ${OUTFILEOPT} "$target" "$url_attic"
1325                                         fi
1326                                 fi
1327                                 test -s "$target" || rm -f "$target"
1328                         fi
1329                 done
1330                 SHELL_TITLE_PREFIX=""
1331
1332
1333                 if [ "$CHMOD" = "yes" ]; then
1334                         CHMOD_FILES=$(nourl "$@")
1335                         if [ -n "$CHMOD_FILES" ]; then
1336                                 chmod $CHMOD_MODE $CHMOD_FILES
1337                         fi
1338                 fi
1339         fi
1340 }
1341
1342 tag_exist() {
1343         local _tag="$1"
1344         echo "Searching for tag $_tag..."
1345         if [ -n "$DEPTH" ]; then
1346                 local ref=`git ls-remote $REMOTE_PLD "refs/tags/$_tag"`
1347                 [ -n  "$ref" ] && echo "$ref" && Exit_error err_tag_exists "$_tag"
1348         else
1349                 git show-ref "refs/tags/$_tag" && Exit_error err_tag_exists "$_tag"
1350         fi
1351 }
1352
1353 make_tagver() {
1354         if [ -n "$DEBUG" ]; then
1355                 set -x
1356                 set -v
1357         fi
1358
1359         # Check whether first character of PACKAGE_NAME is legal for tag name
1360         if [ -z "${PACKAGE_NAME##[_0-9]*}" -a -z "$TAG_PREFIX" ]; then
1361                 TAG_PREFIX=tag_
1362         fi
1363
1364         # NOTE: CVS tags may must not contain the characters `$,.:;@'
1365         TAGVER=$(echo $TAG_PREFIX$PACKAGE_NAME-$PACKAGE_VERSION-$PACKAGE_RELEASE)
1366
1367         # Remove @kernel.version_release from TAGVER because tagging sources
1368         # could occur with different kernel-headers than kernel-headers used at build time.
1369         # besides, %{_kernel_ver_str} is not expanded.
1370
1371         # TAGVER=auto-ac-madwifi-ng-0-0_20070225_1@%{_kernel_ver_str}
1372         # TAGVER=auto-ac-madwifi-ng-0-0_20070225_1
1373
1374         TAGVER=${TAGVER%@*}
1375         echo -n "$TAGVER"
1376 }
1377
1378 tag_files() {
1379         TAG_FILES="$@"
1380
1381         if [ -n "$DEBUG" ]; then
1382                 set -x
1383                 set -v
1384         fi
1385
1386         echo "Version: $PACKAGE_VERSION"
1387         echo "Release: $PACKAGE_RELEASE"
1388
1389         local TAGVER
1390         if [ "$TAG_VERSION" = "yes" ]; then
1391                 TAGVER=`make_tagver`
1392                 echo "tag: $TAGVER"
1393         fi
1394         if [ -n "$TAG" ]; then
1395                 echo "tag: $TAG"
1396         fi
1397
1398         local OPTIONS="tag $CVS_FORCE"
1399
1400         local _tag=$TAG
1401         if [ "$TAG_VERSION" = "yes" ]; then
1402                 _tag=$TAGVER
1403         fi;
1404
1405         cd "$PACKAGE_DIR"
1406
1407         if [ "$TAG_VERSION" = "yes" ]; then
1408                 update_shell_title "tag sources: $TAGVER"
1409                 git $OPTIONS $TAGVER || exit
1410                 git push $CVS_FORCE $REMOTE_PLD tag $TAGVER || Exit_error err_remote_problem $REMOTE_PLD
1411         fi
1412         if [ -n "$TAG" ]; then
1413                 update_shell_title "tag sources: $TAG"
1414                 git $OPTIONS $TAG $chunk || exit
1415                 git push $CVS_FORCE $REMOTE_PLD tag $TAG || Exit_error err_remote_problem $REMOTE_PLD
1416         fi
1417 }
1418
1419 branch_files() {
1420         TAG=$1
1421         echo "Git branch: $TAG"
1422         shift
1423
1424         if [ -n "$DEBUG" ]; then
1425                 set -x
1426                 set -v
1427         fi
1428
1429         local OPTIONS="branch $CVS_FORCE"
1430
1431         cd "$PACKAGE_DIR"
1432         git $OPTIONS $TAG || exit
1433 }
1434
1435
1436 # this function should exit early if package can't be built for this arch
1437 # this avoids unneccessary BR filling.
1438 check_buildarch() {
1439         local out ret
1440         out=$(minirpm --short-circuit -bp --define "'prep exit 0'" --nodeps $SPECFILE 2>&1)
1441         ret=$?
1442         if [ $ret -ne 0 ]; then
1443                 echo >&2 "$out"
1444                 exit $ret
1445         fi
1446 }
1447
1448 # from relup.sh
1449 set_release() {
1450         local specfile="$1"
1451         local rel="$2"
1452         local newrel="$3"
1453         sed -i -e "
1454                 s/^\(%define[ \t]\+_\?rel[ \t]\+\)$rel\$/\1$newrel/
1455                 s/^\(Release:[ \t]\+\)$rel\$/\1$newrel/
1456         " $specfile
1457 }
1458
1459 set_version() {
1460         local specfile="$1"
1461         local ver="$2" subver=$ver
1462         local newver="$3" newsubver=$newver
1463
1464         # try handling subver, everything that's not numeric-dotted in version
1465         if grep -Eq '%define\s+subver' $specfile; then
1466                 subver=$(echo "$ver" | sed -re 's,^[0-9.]+,,')
1467                 ver=${ver%$subver}
1468                 newsubver=$(echo "$newver" | sed -re 's,^[0-9.]+,,')
1469                 newver=${newver%$newsubver}
1470         fi
1471         sed -i -e "
1472                 s/^\(%define[ \t]\+_\?ver[ \t]\+\)$ver\$/\1$newver/
1473                 s/^\(%define[ \t]\+subver[ \t]\+\)$subver\$/\1$newsubver/
1474                 s/^\(Version:[ \t]\+\)$ver\$/\1$newver/
1475         " $specfile
1476 }
1477
1478 try_upgrade() {
1479         if [ -n "$TRY_UPGRADE" ]; then
1480                 local TNOTIFY TNEWVER TOLDVER
1481                 update_shell_title "build_package: try_upgrade"
1482
1483                 cd "$PACKAGE_DIR"
1484                 
1485                 if [ "$UPGRADE_VERSION" ]; then
1486                         TNEWVER=$UPGRADE_VERSION
1487                 else
1488                         if [ -n "$FLOAT_VERSION" ]; then
1489                                 TNOTIFY=$($APPDIR/pldnotify.awk ${BE_VERBOSE:+-vDEBUG=1} $SPECFILE -n) || exit 1
1490                         else
1491                                 TNOTIFY=$($APPDIR/pldnotify.awk ${BE_VERBOSE:+-vDEBUG=1} $SPECFILE) || exit 1
1492                         fi
1493
1494                         # pldnotify.awk does not set exit codes, but it has match for ERROR
1495                         # in output which means so.
1496                         if [[ "$TNOTIFY" = *ERROR* ]]; then
1497                                 echo >&2 "$TNOTIFY"
1498                                 exit 1
1499                         fi
1500
1501                         TNEWVER=$(echo $TNOTIFY | awk '{ match($4,/\[NEW\]/); print $5 }')
1502                 fi
1503
1504                 if [ -n "$TNEWVER" ]; then
1505                         TOLDVER=`echo $TNOTIFY | awk '{ print $3; }'`
1506                         echo "New version found, updating spec file from $TOLDVER to version $TNEWVER"
1507                         if [ "$REVERT_BROKEN_UPGRADE" = "yes" ]; then
1508                                 cp -f $SPECFILE $SPECFILE.bak
1509                         fi
1510                         chmod +w $SPECFILE
1511                         set_release $SPECFILE $PACKAGE_RELEASE 1
1512                         set_version $SPECFILE $PACKAGE_VERSION $TNEWVER
1513                         parse_spec
1514                         if [ "$PACKAGE_VERSION" != "$TNEWVER" ]; then
1515                                 echo >&2 "Upgrading version failed, you need to update spec yourself"
1516                                 exit 1
1517                         fi
1518                         return 1
1519                 fi
1520         fi
1521         return 0
1522 }
1523
1524 build_package() {
1525         update_shell_title "build_package"
1526         if [ -n "$DEBUG" ]; then
1527                 set -x
1528                 set -v
1529         fi
1530
1531         cd "$PACKAGE_DIR"
1532
1533         case "$COMMAND" in
1534                 build )
1535                         BUILD_SWITCH="-ba" ;;
1536                 build-binary )
1537                         BUILD_SWITCH="-bb" ;;
1538                 build-source )
1539                         BUILD_SWITCH="-bs --nodeps" ;;
1540                 build-prep )
1541                         BUILD_SWITCH="-bp --nodeps" ;;
1542                 build-build )
1543                         BUILD_SWITCH="-bc" ;;
1544                 build-install )
1545                         BUILD_SWITCH="-bi" ;;
1546                 build-list )
1547                         BUILD_SWITCH="-bl" ;;
1548
1549         esac
1550
1551         update_shell_title "build_package: $COMMAND"
1552         if [ -n "$LOGFILE" ]; then
1553                 LOG=`eval echo $LOGFILE`
1554                 if [ -d "$LOG" ]; then
1555                         echo "Log file $LOG is a directory."
1556                         echo "Parse error in the spec?"
1557                         Exit_error err_build_fail
1558                 fi
1559                 if [ -n "$LASTLOG_FILE" ]; then
1560                         echo "LASTLOG=$LOG" > $LASTLOG_FILE
1561                 fi
1562                 RES_FILE=$(tempfile)
1563                 local specdir=$(insert_gitlog $SPECFILE)
1564
1565                 (time eval ${NICE_COMMAND} $RPMBUILD $TARGET_SWITCH $BUILD_SWITCH -v $QUIET $CLEAN $RPMOPTS $RPMBUILDOPTS $BCOND --define \'_specdir $PACKAGE_DIR\' --define \'_sourcedir $PACKAGE_DIR\' $specdir/$SPECFILE; echo $? > $RES_FILE) 2>&1 |tee $LOG
1566                 RETVAL=`cat $RES_FILE`
1567                 rm -r $RES_FILE $specdir
1568                 if [ -n "$LOGDIROK" ] && [ -n "$LOGDIRFAIL" ]; then
1569                         if [ "$RETVAL" -eq "0" ]; then
1570                                 mv $LOG $LOGDIROK
1571                         else
1572                                 mv $LOG $LOGDIRFAIL
1573                         fi
1574                 fi
1575         else
1576                 local specdir=$(insert_gitlog $SPECFILE)
1577                 eval ${NICE_COMMAND} $RPMBUILD $TARGET_SWITCH $BUILD_SWITCH -v $QUIET $CLEAN $RPMOPTS $RPMBUILDOPTS $BCOND --define \'_specdir $PACKAGE_DIR\' --define \'_sourcedir $PACKAGE_DIR\' $specdir/$SPECFILE
1578                 RETVAL=$?
1579                 rm -r $specdir
1580         fi
1581         if [ "$RETVAL" -ne "0" ]; then
1582                 if [ -n "$TRY_UPGRADE" ]; then
1583                         echo "\nUpgrade package to new version failed."
1584                         if [ "$REVERT_BROKEN_UPGRADE" = "yes" ]; then
1585                                 echo "Restoring old spec file."
1586                                 mv -f $SPECFILE.bak $SPECFILE
1587                         fi
1588                         echo ""
1589                 fi
1590                 Exit_error err_build_fail
1591         fi
1592         unset BUILD_SWITCH
1593 }
1594
1595 nourl() {
1596         echo "$@" | sed 's#\<\(ftp\|http\|https\|cvs\|svn\)://[^ ]*/##g'
1597 }
1598
1599 install_required_packages() {
1600         run_poldek -vi $1
1601         return $?
1602 }
1603
1604 find_spec_bcond() { # originally from /usr/lib/rpm/find-spec-bcond
1605         local SPEC="$1"
1606         awk -F"\n" '
1607         /^%changelog/ { exit }
1608         /^%bcond_with/{
1609                 match($0, /bcond_with(out)?[ \t]+[_a-zA-Z0-9]+/);
1610                 bcond = substr($0, RSTART + 6, RLENGTH - 6);
1611                 gsub(/[ \t]+/, "_", bcond);
1612                 print bcond
1613         }' $SPEC | LC_ALL=C sort -u
1614 }
1615
1616 process_bcondrc() {
1617         # expand bconds from ~/.bcondrc
1618         # The file structure is like gentoo's package.use:
1619         # ---
1620         # * -selinux
1621         # samba -mysql -pgsql
1622         # w32codec-installer license_agreement
1623         # php +mysqli
1624         # ---
1625         if [ -f $HOME/.bcondrc ] || ([ -n $HOME_ETC ] && [ -f $HOME_ETC/.bcondrc ]); then
1626                 :
1627         else
1628                 return
1629         fi
1630
1631         SN=${SPECFILE%%\.spec}
1632
1633         local bcondrc=$HOME/.bcondrc
1634         [ -n $HOME_ETC ] && [ -f $HOME_ETC/.bcondrc ] && bcondrc=$HOME_ETC/.bcondrc
1635
1636         local bcond_avail=$(find_spec_bcond $SPECFILE)
1637
1638         while read pkg flags; do
1639                 # ignore comments
1640                 [[ "$pkg" == \#* ]] && continue
1641
1642                 # any package or current package?
1643                 if [ "$pkg" = "*" ] || [ "$pkg" = "$PACKAGE_NAME" ] || [ "$pkg" = "$SN" ]; then
1644                         for flag in $flags; do
1645                                 local opt=${flag#[+-]}
1646
1647                                 # use only flags which are in this package.
1648                                 if [[ $bcond_avail = *${opt}* ]]; then
1649                                         if [[ $flag = -* ]]; then
1650                                                 if [[ $BCOND != *--with?${opt}* ]]; then
1651                                                         BCOND="$BCOND --without $opt"
1652                                                 fi
1653                                         else
1654                                                 if [[ $BCOND != *--without?${opt}* ]]; then
1655                                                         BCOND="$BCOND --with $opt"
1656                                                 fi
1657                                         fi
1658                                 fi
1659                         done
1660                 fi
1661         done < $bcondrc
1662         update_shell_title "parse ~/.bcondrc: DONE!"
1663 }
1664
1665 set_bconds_values() {
1666         update_shell_title "set bcond values"
1667
1668         AVAIL_BCONDS_WITHOUT=""
1669         AVAIL_BCONDS_WITH=""
1670
1671         if grep -Eq '^# *_with' ${SPECFILE}; then
1672                 echo >&2 "ERROR: This spec has old style bconds."
1673                 exit 1
1674         fi
1675
1676         if ! grep -q '^%bcond' ${SPECFILE}; then
1677                 return
1678         fi
1679
1680         local bcond_avail=$(find_spec_bcond $SPECFILE)
1681         process_bcondrc "$SPECFILE"
1682
1683         update_shell_title "parse bconds"
1684
1685         local opt bcond
1686         for opt in $bcond_avail; do
1687                 case "$opt" in
1688                 without_*)
1689                         bcond=${opt#without_}
1690                         case "$BCOND" in
1691                         *--without?${bcond}*)
1692                                 AVAIL_BCONDS_WITHOUT="$AVAIL_BCONDS_WITHOUT <$bcond>"
1693                                 ;;
1694                         *)
1695                                 AVAIL_BCONDS_WITHOUT="$AVAIL_BCONDS_WITHOUT $bcond"
1696                                 ;;
1697                         esac
1698                         ;;
1699                 with_*)
1700                         bcond=${opt#with_}
1701                         case "$BCOND" in
1702                         *--with?${bcond}*)
1703                                 AVAIL_BCONDS_WITH="$AVAIL_BCONDS_WITH <$bcond>"
1704                                 ;;
1705                         *)
1706                                 AVAIL_BCONDS_WITH="$AVAIL_BCONDS_WITH $bcond"
1707                                 ;;
1708                         esac
1709                         ;;
1710                 *)
1711                         echo >&2 "ERROR: unexpected '$opt' in set_bconds_values"
1712                         exit 1
1713                         ;;
1714                 esac
1715         done
1716 }
1717
1718 run_sub_builder() {
1719         package_name="${1}"
1720         update_shell_title "run_sub_builder $package_name"
1721         #
1722         # No i tutaj bym chcia³ zrobiæ sztuczn± inteligencjê, która spróbuje tego
1723         # pakieta zbudowaæ. Aktualnie niewiele dziala, bo generalnie nie widze do
1724         # konca algorytmu... Ale damy rade. :) Na razie po prostu sie wyjebie tak samo
1725         # jakby nie bylo tego kawalka kodu.
1726         #
1727         # Update: Poprawi³em parê rzeczy i zaczê³o generowaæ pakiety spoza zadanej listy.
1728         #         Jednym s³owem budowanie niespoldkowanych zale¿no¶ci dzia³a w paru przypadkach.
1729         #
1730         #
1731         # y0shi.
1732         # kurwa. translate that ^^^^
1733
1734         parent_spec_name=''
1735
1736         # Istnieje taki spec? ${package}.spec
1737         if [ -f "${PACKAGE_DIR}/${package}.spec" ]; then
1738                 parent_spec_name=${package}.spec
1739         elif [ -f "${PACKAGE_DIR}/$(echo ${package_name} | sed -e s,-devel.*,,g -e s,-static,,g).spec" ]; then
1740                 parent_spec_name="$(echo ${package_name} | sed -e s,-devel.*,,g -e s,-static,,g).spec"
1741         else
1742                 for provides_line in $(grep -r ^Provides:.*$package ${PACKAGE_DIR}); do
1743                         echo $provides_line
1744                 done
1745         fi
1746
1747         if [ "${parent_spec_name}" != "" ]; then
1748                 spawn_sub_builder $parent_spec_name
1749         fi
1750         NOT_INSTALLED_PACKAGES="$NOT_INSTALLED_PACKAGES $package_name"
1751 }
1752
1753 spawn_sub_builder() {
1754         package_name="${1}"
1755         update_shell_title "spawn_sub_builder $package_name"
1756
1757         sub_builder_opts=''
1758         if [ "${FETCH_BUILD_REQUIRES}" = "yes" ]; then
1759                 sub_builder_opts="${sub_builder_opts} -R"
1760         fi
1761         if [ "${REMOVE_BUILD_REQUIRES}" = "nice" ]; then
1762                 sub_builder_opts="${sub_builder_opts} -RB"
1763         elif [ "${REMOVE_BUILD_REQUIRES}" = "force" ]; then
1764                 sub_builder_opts="${sub_builder_opts} -FRB"
1765         fi
1766         if [ "${UPDATE_POLDEK_INDEXES}" = "yes" ]; then
1767                 sub_builder_opts="${sub_builder_opts} -Upi"
1768         fi
1769
1770         cd "${PACKAGE_DIR}"
1771         ./builder ${sub_builder_opts} "$@"
1772 }
1773
1774 remove_build_requires() {
1775         if [ "$INSTALLED_PACKAGES" != "" ]; then
1776                 case "$REMOVE_BUILD_REQUIRES" in
1777                         "force")
1778                                 run_poldek --noask -ve $INSTALLED_PACKAGES
1779                                 ;;
1780                         "nice")
1781                                 run_poldek --ask -ve $INSTALLED_PACKAGES
1782                                 ;;
1783                         *)
1784                                 echo You may want to manually remove following BuildRequires fetched:
1785                                 echo $INSTALLED_PACKAGES
1786                                 echo "Try poldek -e \`cat $(pwd)/.${SPECFILE}_INSTALLED_PACKAGES\`"
1787                                 ;;
1788                 esac
1789         fi
1790 }
1791
1792 display_bconds() {
1793         if [ "$AVAIL_BCONDS_WITH" -o "$AVAIL_BCONDS_WITHOUT" ]; then
1794                 if [ "$BCOND" ]; then
1795                         echo ""
1796                         echo "Building $SPECFILE with the following conditional flags:"
1797                         echo -n "$BCOND"
1798                 else
1799                         echo ""
1800                         echo "No conditional flags passed"
1801                 fi
1802                 echo ""
1803                 echo "from available:"
1804                 echo "--with   :\t$AVAIL_BCONDS_WITH"
1805                 echo "--without:\t$AVAIL_BCONDS_WITHOUT"
1806                 echo ""
1807         fi
1808 }
1809
1810 display_branches() {
1811         echo -n "Available branches: "
1812         git branch -r | grep "^  ${REMOTE_PLD}" | grep -v ${REMOTE_PLD}/HEAD | sed "s#^ *${REMOTE_PLD}/##" | xargs
1813 }
1814
1815 # checks a given list of packages/files/provides agains current rpmdb.
1816 # outputs all dependencies which current rpmdb doesn't satisfy.
1817 # input can be either STDIN or parameters
1818 _rpm_prov_check() {
1819         local DEPS
1820
1821         if [ $# -gt 0 ]; then
1822                 DEPS="$@"
1823         else
1824                 DEPS=$(cat)
1825         fi
1826
1827         DEPS=$(LANG=C rpm -q --whatprovides $DEPS 2>&1 | awk '/^(error:|no package provides)/ { print }')
1828
1829         # packages
1830         echo "$DEPS" | awk '/^no package provides/ { print $NF }'
1831
1832         # other deps (files)
1833         echo "$DEPS" | awk -F: '/^error:.*No such file/{o = $2; gsub("^ file ", "", o); print o}'
1834 }
1835
1836 # checks if given package/files/provides exists in rpmdb.
1837 # input can be either stdin or parameters
1838 # returns packages which are present in the rpmdb
1839 _rpm_cnfl_check() {
1840         local DEPS
1841
1842         if [ $# -gt 0 ]; then
1843                 DEPS="$@"
1844         else
1845                 DEPS=$(cat)
1846         fi
1847
1848         LANG=C rpm -q --whatprovides $DEPS 2>/dev/null | awk '!/no package provides/ { print }'
1849 }
1850
1851 # install deps via information from 'rpm-getdeps' or 'rpm --specsrpm'
1852 install_build_requires_rpmdeps() {
1853         if [ "$FETCH_BUILD_REQUIRES_RPMGETDEPS" = "yes" ]; then
1854                 # TODO: Conflicts list doesn't check versions
1855                 local CNFL=$(rpm-getdeps $BCOND $SPECFILE 2> /dev/null | awk '/^\-/ { print $3 } ' | _rpm_cnfl_check | xargs)
1856                 local DEPS=$(rpm-getdeps $BCOND $SPECFILE 2> /dev/null | awk '/^\+/ { print $3 } ' | _rpm_prov_check | xargs)
1857         fi
1858         if [ "$FETCH_BUILD_REQUIRES_RPMSPECSRPM" = "yes" ]; then
1859                 local CNFL=$(rpm -q --specsrpm --conflicts $BCOND $SPECFILE | awk '{print $1}' | _rpm_cnfl_check | xargs)
1860                 local DEPS=$(rpm -q --specsrpm --requires $BCOND $SPECFILE | awk '{print $1}' | _rpm_prov_check | xargs)
1861         fi
1862
1863         if [ -n "$CNFL" ] || [ -n "$DEPS" ]; then
1864                 echo "fetch BuildRequires: install [$DEPS]; remove [$CNFL]"
1865                 update_shell_title "poldek: install [$DEPS]; remove [$CNFL]"
1866                 $SU_SUDO /usr/bin/poldek -q --update || $SU_SUDO /usr/bin/poldek -q --upa
1867         fi
1868         if [ -n "$CNFL" ]; then
1869                 update_shell_title "uninstall conflicting packages: $CNFL"
1870                 echo "Trying to uninstall conflicting packages ($CNFL):"
1871                 $SU_SUDO /usr/bin/poldek --noask --nofollow -ev $CNFL
1872         fi
1873
1874         while [ "$DEPS" ]; do
1875                         update_shell_title "install deps: $DEPS"
1876                         echo "Trying to install dependencies ($DEPS):"
1877                         local log=.${SPECFILE}_poldek.log
1878                         LANG=C $SU_SUDO /usr/bin/poldek --noask --caplookup -uGqQ $DEPS | tee $log
1879                         failed=$(awk '/^error:/{a=$2; sub(/^error: /, "", a); sub(/:$/, "", a); print a}' $log)
1880                         rm -f $log
1881                         local ok
1882                         if [ -n "$failed" ]; then
1883                                 for package in $failed; do
1884                                         spawn_sub_builder -bb $(depspecname $package) && ok="$ok $package"
1885                                 done
1886                                 DEPS="$ok"
1887                         else
1888                                 DEPS=""
1889                         fi
1890         done
1891 }
1892
1893 fetch_build_requires()
1894 {
1895         if [ "${FETCH_BUILD_REQUIRES}" != "yes" ]; then
1896                 return
1897         fi
1898
1899         update_shell_title "fetch build requires"
1900         if [ "$FETCH_BUILD_REQUIRES_RPMGETDEPS" = "yes" ] || [ "$FETCH_BUILD_REQUIRES_RPMSPECSRPM" = "yes" ]; then
1901                 install_build_requires_rpmdeps
1902                 return
1903         fi
1904
1905                 # XXX is this ugliest code written in human history still needed?
1906                 echo "All packages installed by fetch_build_requires() are written to:"
1907                 echo "`pwd`/.${SPECFILE}_INSTALLED_PACKAGES"
1908                 echo ""
1909                 echo "If anything fails, you may get rid of them by executing:"
1910                 echo "poldek -e \`cat `pwd`/.${SPECFILE}_INSTALLED_PACKAGES\`"
1911                 echo ""
1912                 echo > `pwd`/.${SPECFILE}_INSTALLED_PACKAGES
1913                 for package_item in $(cat $SPECFILE | grep -B100000 ^%changelog|grep -v ^#|grep BuildRequires|grep -v ^-|sed -e "s/^.*BuildRequires://g"|awk '{print $1}'|sed -e s,perl\(,perl-,g -e s,::,-,g -e s,\(.*\),,g -e s,%{,,g -e s,},,g|grep -v OpenGL-devel|sed -e s,sh-utils,coreutils,g -e s,fileutils,coreutils,g -e s,textutils,coreutils,g -e s,kgcc_package,gcc,g -e s,\),,g)
1914                 do
1915                         package_item=$(echo $package_item|sed -e s,rpmbuild,rpm-build,g |sed -e s,__perl,perl,g |sed -e s,gasp,binutils-gasp,g -e s,binutils-binutils,binutils,g -e s,apxs,apache,g|sed -e s,apache\(EAPI\)-devel,apache-devel,g -e s,kernel-headers\(netfilter\),kernel-headers,g -e s,awk,mawk,g -e s,mmawk,mawk,g -e s,motif,openmotif,g -e s,openopenmotif,openmotif,g)
1916                         GO="yes"
1917                         package=$(basename "$package_item"|sed -e "s/}$//g")
1918                         COND_ARCH_TST=$(cat $SPECFILE|grep -B1 BuildRequires|grep -B1 $package|grep ifarch|sed -e "s/^.*ifarch//g")
1919                         mach=$(uname -m)
1920
1921                         COND_TST=`cat $SPECFILE|grep BuildRequires|grep "$package"`
1922                         if `echo $COND_TST|grep -q '^BuildRequires:'`; then
1923                                 if [ "$COND_ARCH_TST" != "" ] && [ "`echo $COND_ARCH_TST|sed -e "s/i.86/ix86/g"`" != "`echo $mach|sed -e "s/i.86/ix86/g"`" ]; then
1924                                         GO="yes"
1925                                 fi
1926                         # bcond:
1927                         else
1928                                 COND_NAME=`echo $COND_TST|sed -e s,:BuildRequires:.*$,,g`
1929                                 GO=""
1930                                 # %{without}
1931                                 if `echo $COND_TST|grep -q 'without_'`; then
1932                                         COND_NAME=`echo $COND_NAME|sed -e s,^.*without_,,g`
1933                                         if `echo $COND_TST|grep -q !`; then
1934                                                 COND_STATE="with"
1935                                         else
1936                                                 COND_STATE="wout"
1937                                         fi
1938                                         COND_WITH=`echo $AVAIL_BCONDS_WITH|grep "<$COND_NAME>"`
1939                                         COND_WITHOUT=`echo $AVAIL_BCONDS_WITHOUT|grep "<$COND_NAME>"`
1940                                         if [ -n "$COND_WITHOUT" ] || [ -z "$COND_WITH" ]; then
1941                                                 COND_ARGV="wout"
1942                                         else
1943                                                 COND_ARGV="with"
1944                                         fi
1945                                 # %{with}
1946                                 elif `echo $COND_TST|grep -q 'with_'`; then
1947                                         COND_NAME=`echo $COND_NAME|sed -e s,^.*with_,,g`
1948                                         if `echo $COND_TST|grep -q !`; then
1949                                                 COND_STATE="wout"
1950                                         else
1951                                                 COND_STATE="with"
1952                                         fi
1953                                         COND_WITH=`echo $AVAIL_BCONDS_WITH|grep "<$COND_NAME>"`
1954                                         COND_WITHOUT=`echo $AVAIL_BCONDS_WITHOUT|grep "<$COND_NAME>"`
1955                                         if [ -n "$COND_WITH" ] || [ -z "$COND_WITHOUT" ]; then
1956                                                 COND_ARGV="with"
1957                                         else
1958                                                 COND_ARGV="wout"
1959                                         fi
1960                                 fi
1961                                 RESULT="${COND_STATE}-${COND_ARGV}"
1962                                 case "$RESULT" in
1963                                         "with-wout" | "wout-with" )
1964                                                 GO=""
1965                                                 ;;
1966                                         "wout-wout" | "with-with" )
1967                                                 GO="yes"
1968                                                 ;;
1969                                         * )
1970                                                 echo "Action '$RESULT' was not defined for package '$package_item'"
1971                                                 GO="yes"
1972                                                 ;;
1973                                 esac
1974                         fi
1975
1976                         if [ "$GO" = "yes" ]; then
1977                                 if [ "`rpm -q $package|sed -e "s/$package.*/$package/g"`" != "$package" ]; then
1978                                         echo "Testing if $package has subrequirements..."
1979                                         run_poldek -t -i $package --dumpn=".$package-req.txt"
1980                                         if [ -f ".$package-req.txt" ]; then
1981                                                 for package_name in `cat ".$package-req.txt"|grep -v ^#`
1982                                                 do
1983                                                         if [ "$package_name" = "$package" ]; then
1984                                                                 echo "Installing BuildRequired package:\t$package_name"
1985                                                                 update_shell_title "Installing BuildRequired package: ${package_name}"
1986                                                                 install_required_packages $package
1987                                                         else
1988                                                                 echo "Installing (sub)Required package:\t$package_name"
1989                                                                 update_shell_title "Installing (sub)Required package: ${package_name}"
1990                                                                 install_required_packages $package_name
1991                                                         fi
1992                                                         case $? in
1993                                                                 0)
1994                                                                         INSTALLED_PACKAGES="$package_name $INSTALLED_PACKAGES"
1995                                                                         echo $package_name >> `pwd`/.${SPECFILE}_INSTALLED_PACKAGES
1996                                                                         ;;
1997                                                                 *)
1998                                                                         echo "Attempting to run spawn sub - builder..."
1999                                                                         echo "Package installation failed:\t$package_name"
2000                                                                         run_sub_builder $package_name
2001                                                                         if [ $? -eq 0 ]; then
2002                                                                                 install_required_packages $package_name
2003                                                                                 case $? in
2004                                                                                         0)
2005                                                                                                 INSTALLED_PACKAGES="$package_name $INSTALLED_PACKAGES"
2006                                                                                                 echo $package_name >> `pwd`/.${SPECFILE}_INSTALLED_PACKAGES
2007                                                                                                 ;;
2008                                                                                         *)
2009                                                                                                 NOT_INSTALLED_PACKAGES="$package_name $NOT_INSTALLED_PACKAGES"
2010                                                                                                 ;;
2011                                                                                 esac
2012                                                                         fi
2013                                                                         ;;
2014                                                         esac
2015                                                 done
2016                                                 rm -f ".$package-req.txt"
2017                                         else
2018                                                 echo "Attempting to run spawn sub - builder..."
2019                                                 echo "Package installation failed:\t$package"
2020                                                 run_sub_builder $package
2021                                                 if [ $? -eq 0 ]; then
2022                                                         install_required_packages $package
2023                                                         case $? in
2024                                                                 0)
2025                                                                         INSTALLED_PACKAGES="$package_name $INSTALLED_PACKAGES"
2026                                                                         echo $package_name >> `pwd`/.${SPECFILE}_INSTALLED_PACKAGES
2027                                                                         ;;
2028                                                                 *)
2029                                                                         NOT_INSTALLED_PACKAGES="$package_name $NOT_INSTALLED_PACKAGES"
2030                                                                         ;;
2031                                                         esac
2032                                                 fi
2033                                         fi
2034                                 else
2035                                         echo "Package $package is already installed. BuildRequirement satisfied."
2036                                 fi
2037                         fi
2038                 done
2039                 if [ "$NOT_INSTALLED_PACKAGES" != "" ]; then
2040                         echo >&2 "Unable to install following packages and their dependencies:"
2041                         for pkg in "$NOT_INSTALLED_PACKAGES"
2042                         do
2043                                 echo $pkg
2044                         done
2045                         remove_build_requires
2046                         exit 8
2047                 fi
2048 }
2049
2050 init_rpm_dir() {
2051         local TOP_DIR=$(eval $RPM $RPMOPTS --eval '%{_topdir}')
2052         local rpmdir=$(eval $RPM $RPMOPTS --eval '%{_rpmdir}')
2053         local buildir=$(eval $RPM $RPMOPTS --eval '%{_builddir}')
2054         local srpmdir=$(eval $RPM $RPMOPTS --eval '%{_srcrpmdir}')
2055         local tmp
2056
2057         echo "Initializing rpm directories to $TOP_DIR from $GIT_SERVER"
2058         mkdir -p $TOP_DIR $rpmdir $buildir $srpmdir
2059
2060         cd "$TOP_DIR"
2061         if [ ! -e ../scripts ]; then
2062                 git clone  ${GIT_SERVER}/${PACKAGES_DIR}/scripts.git ../scripts
2063         fi
2064         for a in adapter builder; do
2065                 ln -s ../scripts/${a}.sh $a
2066         done
2067         init_builder
2068 }
2069
2070 mr_proper() {
2071         init_builder
2072         NOCVSSPEC="yes"
2073         DONT_PRINT_REVISION="yes"
2074
2075         # remove spec and sources
2076         $RPMBUILD --clean --rmsource --rmspec --nodeps --define "_specdir $PACKAGE_DIR" --define "_sourcedir $PACKAGE_DIR" --define "_builddir $builddir" $PACKAGE_DIR/$SPECFILE
2077         rm -rf $PACKAGE_DIR/{.git,.gitignore}
2078         rmdir --ignore-fail-on-non-empty $PACKAGE_DIR
2079 }
2080
2081 #---------------------------------------------
2082 # main()
2083
2084 if [ $# = 0 ]; then
2085         usage
2086         exit 1
2087 fi
2088
2089 while [ $# -gt 0 ]; do
2090         case "${1}" in
2091                 -4|-6)
2092                         # NOTE: we should be fetcher specific, like fille WGET_OPTS, but
2093                         # unfortunately $GETURI is already formed
2094                         GETURI="$GETURI $1"
2095                         shift
2096                         ;;
2097                 -5 | --update-md5)
2098                         COMMAND="update_md5"
2099                         NODIST="yes"
2100                         NOCVSSPEC="yes"
2101                         shift ;;
2102                 -a5 | --add-md5 )
2103                         COMMAND="update_md5"
2104                         NODIST="yes"
2105                         NOCVSSPEC="yes"
2106                         ADD5="yes"
2107                         shift ;;
2108                 -n5 | --no-md5 )
2109                         NO5="yes"
2110                         shift ;;
2111                 -D | --debug )
2112                         DEBUG="yes"; shift ;;
2113                 -V | --version )
2114                         COMMAND="version"; shift ;;
2115                 --short-version )
2116                         COMMAND="short-version"; shift ;;
2117                 -a | --add_cvs)
2118                         COMMAND="add_cvs";
2119                         shift ;;
2120                 --all-branches )
2121                         ALL_BRANCHES="yes"
2122                         shift ;;
2123                 -b | -ba | --build )
2124                         COMMAND="build"; shift ;;
2125                 -bb | --build-binary )
2126                         COMMAND="build-binary"; shift ;;
2127                 -bc )
2128                         COMMAND="build-build"; shift ;;
2129                 -bi )
2130                         COMMAND="build-install"; shift ;;
2131                 -bl )
2132                         COMMAND="build-list"; shift ;;
2133                 -bp | --build-prep )
2134                         COMMAND="build-prep"; shift ;;
2135                 -bs | --build-source )
2136                         COMMAND="build-source"; shift ;;
2137                 -B | --branch )
2138                         COMMAND="branch"; shift; TAG="${1}"; shift;;
2139                 -c | --clean )
2140                         CLEAN="--clean"; shift ;;
2141                 -cf | --cvs-force )
2142                         CVS_FORCE="-f"; shift;;
2143                 --depth )
2144                         DEPTH="--depth=$2"
2145                         shift 2
2146                         ;;
2147                 -g | --get )
2148                         COMMAND="get"; shift ;;
2149                 -h | --help )
2150                         COMMAND="usage"; shift ;;
2151                 --ftp )
2152                         PROTOCOL="ftp"; shift ;;
2153                 --http )
2154                         PROTOCOL="http"; shift ;;
2155                 -j)
2156                         RPMOPTS="${RPMOPTS} --define \"_smp_mflags -j$2\""
2157                         shift 2
2158                         ;;
2159                 -j[0-9]*)
2160                         RPMOPTS="${RPMOPTS} --define \"_smp_mflags $1\""
2161                         shift
2162                         ;;
2163                 -p)
2164                         PARALLEL_DOWNLOADS=$2
2165                         shift 2
2166                         ;;
2167                 -p[0-9])
2168                         PARALLEL_DOWNLOADS=${1#-p}
2169                         shift
2170                         ;;
2171                 -l | --logtofile )
2172                         shift; LOGFILE="${1}"; shift ;;
2173                 -ni| --nice )
2174                         shift; DEF_NICE_LEVEL=${1}; shift ;;
2175                 -ske | --skip-existing-files)
2176                         SKIP_EXISTING_FILES="yes"; shift ;;
2177                 -m | --mr-proper )
2178                         COMMAND="mr-proper"; shift ;;
2179                 -ncs | --no-cvs-specs )
2180                         NOCVSSPEC="yes"; shift ;;
2181                 -nd | --no-distfiles )
2182                         NODIST="yes"; shift ;;
2183                 -nm | --no-mirrors )
2184                         NOMIRRORS="yes"; shift ;;
2185                 -nu | --no-urls )
2186                         NOURLS="yes"; shift ;;
2187                 -ns | --no-srcs )
2188                         NOSRCS="yes"; shift ;;
2189                 -ns0 | --no-source0 )
2190                         NOSOURCE0="yes"; shift ;;
2191                 -nn | --no-net )
2192                         NOCVSSPEC="yes"
2193                         NODIST="yes"
2194                         NOMIRRORS="yes"
2195                         NOURLS="yes"
2196                         NOSRCS="yes"
2197                         ALWAYS_CVSUP="no"
2198                         shift;;
2199                 -pm | --prefer-mirrors )
2200                         PREFMIRRORS="yes"
2201                         shift;;
2202                 --no-init )
2203                         NOINIT="yes"
2204                         shift;;
2205                 --opts )
2206                         shift; RPMOPTS="${RPMOPTS} ${1}"; shift ;;
2207                 --nopatch | -np )
2208                         shift; RPMOPTS="${RPMOPTS} --define \"patch${1} : ignoring patch${1}; exit 1; \""; shift ;;
2209                 --skip-patch | -sp )
2210                         shift; RPMOPTS="${RPMOPTS} --define \"patch${1} : skiping patch${1}\""; shift ;;
2211                 --topdir)
2212                         RPMOPTS="${RPMOPTS} --define \"_topdir $2\""
2213                         shift 2
2214                         ;;
2215                 --with | --without )
2216                         case $GROUP_BCONDS in
2217                                 "yes")
2218                                         COND=${1}
2219                                         shift
2220                                         # XXX: broken: ./builder -bb ucspi-tcp.spec --without mysql
2221                                         while ! `echo ${1}|grep -qE '(^-|spec)'`
2222                                         do
2223                                                 BCOND="$BCOND $COND $1"
2224                                                 shift
2225                                         done;;
2226                                 "no")
2227                                         if [[ "$2" = *,* ]]; then
2228                                                 for a in $(echo "$2" | tr , ' '); do
2229                                                         BCOND="$BCOND $1 $a"
2230                                                 done
2231                                         else
2232                                                 BCOND="$BCOND $1 $2"
2233                                         fi
2234                                         shift 2 ;;
2235                         esac
2236                         ;;
2237                 --target )
2238                         shift; TARGET="${1}"; shift ;;
2239                 --target=* )
2240                         TARGET=$(echo "${1}" | sed 's/^--target=//'); shift ;;
2241                 -q | --quiet )
2242                         QUIET="--quiet"; shift ;;
2243                 --date )
2244                         CVSDATE="${2}"; shift 2
2245                         date -d "$CVSDATE" > /dev/null 2>&1 || { echo >&2 "No valid date specified"; exit 3; }
2246                         ;;
2247                 -r | --cvstag )
2248                         CVSTAG="$2"
2249                         shift 2
2250                         ;;
2251                 -A)
2252                         shift
2253                         CVSTAG="master"
2254                         ;;
2255                 -R | --fetch-build-requires)
2256                         FETCH_BUILD_REQUIRES="yes"
2257                         NOT_INSTALLED_PACKAGES=
2258                         shift ;;
2259                 -RB | --remove-build-requires)
2260                         REMOVE_BUILD_REQUIRES="nice"
2261                         shift ;;
2262                 -FRB | --force-remove-build-requires)
2263                         REMOVE_BUILD_REQUIRES="force"
2264                         shift ;;
2265                 -sc | --source-cvs)
2266                         COMMAND="list-sources-cvs"
2267                         shift ;;
2268                 -sd | --source-distfiles)
2269                         COMMAND="list-sources-distfiles"
2270                         shift ;;
2271                 -sdp | --source-distfiles-paths)
2272                         COMMAND="list-sources-distfiles-paths"
2273                         shift ;;
2274                 -sf | --source-files)
2275                         COMMAND="list-sources-files"
2276                         shift ;;
2277                 -lsp | --source-paths)
2278                         COMMAND="list-sources-local-paths"
2279                         shift ;;
2280                 -su | --source-urls)
2281                         COMMAND="list-sources-urls"
2282                         shift ;;
2283                 -Tvs | --tag-version-stable )
2284                         COMMAND="tag"
2285                         TAG="STABLE"
2286                         TAG_VERSION="yes"
2287                         shift;;
2288                 -Ts | --tag-stable )
2289                         COMMAND="tag"
2290                         TAG="STABLE"
2291                         TAG_VERSION="no"
2292                         shift;;
2293                 -Tv | --tag-version )
2294                         COMMAND="tag"
2295                         TAG=""
2296                         TAG_VERSION="yes"
2297                         shift;;
2298                 -Tp | --tag-prefix )
2299                         TAG_PREFIX="$2"
2300                         shift 2;;
2301                 -tt | --test-tag )
2302                         TEST_TAG="yes"
2303                         shift;;
2304                 -T | --tag )
2305                         COMMAND="tag"
2306                         shift
2307                         TAG="$1"
2308                         TAG_VERSION="no"
2309                         shift;;
2310                 -ir | --integer-release-only )
2311                         INTEGER_RELEASE="yes"
2312                         shift;;
2313                 -U | --update )
2314                         COMMAND="update_md5"
2315                         UPDATE="yes"
2316                         NOCVSSPEC="yes"
2317                         NODIST="yes"
2318                         shift ;;
2319                 -Upi | --update-poldek-indexes )
2320                         UPDATE_POLDEK_INDEXES="yes"
2321                         shift ;;
2322                 --init-rpm-dir)
2323                         COMMAND="init_rpm_dir"
2324                         shift ;;
2325                 -u | --try-upgrade )
2326                         TRY_UPGRADE="1"; shift ;;
2327                 --upgrade-version )
2328                         shift; UPGRADE_VERSION="$1"; shift;;
2329                 -un | --try-upgrade-with-float-version )
2330                         TRY_UPGRADE="1"; FLOAT_VERSION="1"; shift ;;
2331                 -v | --verbose )
2332                         BE_VERBOSE="1"; shift ;;
2333                 --define)
2334                         shift
2335                         MACRO="${1}"
2336                         shift
2337                         if echo "${MACRO}" | grep -q '\W'; then
2338                                 RPMOPTS="${RPMOPTS} --define \"${MACRO}\""
2339                         else
2340                                 VALUE="${1}"
2341                                 shift
2342                                 RPMOPTS="${RPMOPTS} --define \"${MACRO} ${VALUE}\""
2343                         fi
2344                         ;;
2345                 --alt_kernel)
2346                         shift
2347                         RPMOPTS="${RPMOPTS} --define \"alt_kernel $1\""
2348                         shift
2349                         ;;
2350                 --short-circuit)
2351                         RPMBUILDOPTS="${RPMBUILDOPTS} --short-circuit"
2352                         shift
2353                         ;;
2354                 --show-bconds | -show-bconds | -print-bconds | --print-bconds | -display-bconds | --display-bconds )
2355                         COMMAND="show_bconds"
2356                         shift
2357                         ;;
2358                 --show-bcond-args)
2359                         COMMAND="show_bcond_args"
2360                         shift
2361                         ;;
2362                 --show-avail-bconds)
2363                         COMMAND="show_avail_bconds"
2364                         shift
2365                         ;;
2366                 --nodeps)
2367                         shift
2368                         RPMOPTS="${RPMOPTS} --nodeps"
2369                         ;;
2370                 -debug)
2371                         RPMBUILDOPTS="${RPMBUILDOPTS} -debug"; shift
2372                         ;;
2373                 --git-pld)
2374                         shift
2375                         GIT_SERVER=${PLD_GIT_SERVER}
2376                         GIT_PUSH=${PLD_GIT_PUSH}
2377                         PACKAGES_DIR=${PLD_PACKAGES_DIR}
2378                         DISTFILES_SERVER=${PLD_DISTFILES_SERVER}
2379                         ATTICDISTFILES_SERVER=${PLD_ATTICDISTFILES_SERVER}
2380                         ;;
2381                 --git-tld)
2382                         shift
2383                         GIT_SERVER=${TLD_GIT_SERVER}
2384                         GIT_PUSH=${TLD_GIT_PUSH}
2385                         PACKAGES_DIR=${TLD_PACKAGES_DIR}
2386                         DISTFILES_SERVER=${TLD_DISTFILES_SERVER}
2387                         ATTICDISTFILES_SERVER=${TLD_ATTICDISTFILES_SERVER}
2388                         ;;
2389                 -*)
2390                         Exit_error err_invalid_cmdline "$1"
2391                         ;;
2392                 *)
2393                         SPECFILE=${1%/}; shift
2394                         # check if specname was passed as specname:cvstag
2395                         if [ "${SPECFILE##*:}" != "${SPECFILE}" ]; then
2396                                 CVSTAG="${SPECFILE##*:}"
2397                                 SPECFILE="${SPECFILE%%:*}"
2398                         fi
2399                         # always have SPECFILE ending with .spec extension
2400                         SPECFILE=${SPECFILE%%.spec}.spec
2401                         ASSUMED_NAME=$(basename ${SPECFILE%%.spec})
2402         esac
2403 done
2404
2405 # Check if given package exists in TLD git
2406 if ! git ls-remote --heads ${GIT_SERVER}/${PACKAGES_DIR}/${ASSUMED_NAME} 1>/dev/null 2>&1; then
2407         # Nope, we don't have it in TLD, switch for PLD repositories
2408         GIT_SERVER=${PLD_GIT_SERVER}
2409         GIT_PUSH=${PLD_GIT_PUSH}
2410         PACKAGES_DIR=${PLD_PACKAGES_DIR}
2411         DISTFILES_SERVER=${PLD_DISTFILES_SERVER}
2412         ATTICDISTFILES_SERVER=${PLD_ATTICDISTFILES_SERVER}
2413 fi
2414
2415 if [ "$CVSTAG" ]; then
2416         # pass $CVSTAG used by builder to rpmbuild too, so specs could use it
2417         RPMOPTS="$RPMOPTS --define \"_cvstag $CVSTAG\""
2418 fi
2419
2420 if [ -n "$ALL_BRANCHES" -a -z "$DEPTH" ]; then
2421         echo >&2 "--all branches requires --depth <number>"
2422         Exit_error err_invalid_cmdline
2423 fi
2424
2425 if [ -n "$DEBUG" ]; then
2426         set -x
2427         set -v
2428 fi
2429
2430 if [ -n "$TARGET" ]; then
2431         case "$RPMBUILD" in
2432                 "rpmbuild")
2433                         TARGET_SWITCH="--target $TARGET" ;;
2434                 "rpm")
2435                         TARGET_SWITCH="--target=$TARGET" ;;
2436         esac
2437 fi
2438
2439 if [ "$SCHEDTOOL" != "no" ]; then
2440         NICE_COMMAND="$SCHEDTOOL"
2441 else
2442         NICE_COMMAND="nice -n ${DEF_NICE_LEVEL}"
2443 fi
2444
2445 update_shell_title "$COMMAND"
2446 case "$COMMAND" in
2447         "show_bconds")
2448                 init_builder
2449                 if [ -z "$SPECFILE" ]; then
2450                         Exit_error err_no_spec_in_cmdl
2451                 fi
2452                 get_spec > /dev/null
2453                 parse_spec
2454                 set_bconds_values
2455                 display_bconds
2456                 ;;
2457         "show_bcond_args")
2458                 init_builder
2459                 if [ -z "$SPECFILE" ]; then
2460                         Exit_error err_no_spec_in_cmdl
2461                 fi
2462                 get_spec > /dev/null
2463                 parse_spec
2464                 set_bconds_values
2465                 echo "$BCOND"
2466                 ;;
2467         "show_avail_bconds")
2468                 init_builder
2469                 if [ -z "$SPECFILE" ]; then
2470                         Exit_error err_no_spec_in_cmdl
2471                 fi
2472
2473                 get_spec > /dev/null
2474                 parse_spec
2475                 local bcond_avail=$(find_spec_bcond $SPECFILE)
2476                 local opt bcond bconds
2477                 for opt in $bcond_avail; do
2478                         case "$opt" in
2479                         without_*)
2480                                 bcond=${opt#without_}
2481                                 bconds="$bconds $bcond"
2482                                 ;;
2483                         with_*)
2484                                 bcond=${opt#with_}
2485                                 bconds="$bconds $bcond"
2486                                 ;;
2487                         *)
2488                                 echo >&2 "ERROR: unexpected '$opt' in show_avail_bconds"
2489                                 exit 1
2490                                 ;;
2491                         esac
2492                 done
2493                 echo $bconds
2494
2495                 ;;
2496         "build" | "build-binary" | "build-source" | "build-prep" | "build-build" | "build-install" | "build-list")
2497                 init_builder
2498                 if [ -z "$SPECFILE" ]; then
2499                         Exit_error err_no_spec_in_cmdl
2500                 fi
2501
2502                 # display SMP make flags if set
2503                 smp_mflags=$(rpm -E %{?_smp_mflags})
2504                 if [ "$smp_mflags" ]; then
2505                         echo "builder: SMP make flags are set to $smp_mflags"
2506                 fi
2507
2508                 get_spec
2509                 parse_spec
2510                 set_bconds_values
2511                 display_bconds
2512                 display_branches
2513                 if [ "$COMMAND" != "build-source" ]; then
2514                         check_buildarch
2515                 fi
2516                 fetch_build_requires
2517                 if [ "$INTEGER_RELEASE" = "yes" ]; then
2518                         echo "Checking release $PACKAGE_RELEASE..."
2519                         if echo $PACKAGE_RELEASE | grep -q '^[^.]*\.[^.]*$' 2>/dev/null ; then
2520                                 Exit_error err_fract_rel "$PACKAGE_RELEASE"
2521                         fi
2522                 fi
2523
2524                 # ./builder -bs test.spec -r AC-branch -Tp auto-ac- -tt
2525                 if [ -n "$TEST_TAG" ]; then
2526                         local TAGVER=`make_tagver`
2527                         tag_exist $TAGVER
2528                         # check also tags created in CVS
2529                         tag_exist $(echo $TAGVER | tr '[.@]' '[_#]')
2530                         # - do not allow to build from HEAD when XX-branch exists
2531                         TREE_PREFIX=$(echo "$TAG_PREFIX" | sed -e 's#^auto/\([a-zA-Z]\+\)/.*#\1#g')
2532                         if [ "$TREE_PREFIX" != "$TAG_PREFIX" ]; then
2533                                 TAG_BRANCH="${TREE_PREFIX}-branch"
2534                                 if [ -n "$DEPTH" ]; then
2535                                         cmd_branches="git ls-remote --heads"
2536                                         ref_prefix=refs/heads
2537                                 else
2538                                         cmd_branches="git show-ref"
2539                                         ref_prefix=refs/remotes/${REMOTE_PLD}
2540                                 fi
2541                                 TAG_STATUS=$($cmd_branches | grep -i "${ref_prefix}/$TAG_BRANCH$")
2542                                 if [ -n "$TAG_STATUS" -a "$TAG_STATUS" != "$CVSTAG" ]; then
2543                                         Exit_error err_branch_exists "$TAG_STATUS"
2544                                 fi
2545                         fi
2546
2547                 fi
2548
2549                 if [ -n "$NOSOURCE0" ] ; then
2550                         SOURCES=`echo $SOURCES | xargs | sed -e 's/[^ ]*//'`
2551                 fi
2552                 try_upgrade
2553                 case $? in
2554                         0)
2555                                 get_files $SOURCES $PATCHES
2556                                 check_md5 $SOURCES
2557                                 ;;
2558                         *)
2559                                 NODIST="yes" get_files $SOURCES $PATCHES
2560                                 update_md5 $SOURCES $PATCHES
2561                                 ;;
2562                 esac
2563                 build_package
2564                 if [ "$UPDATE_POLDEK_INDEXES" = "yes" ] && [ "$COMMAND" = "build" -o "$COMMAND" = "build-binary" ]; then
2565                         run_poldek --sdir="${POLDEK_INDEX_DIR}" ${UPDATE_POLDEK_INDEXES_OPTS} --mkidxz
2566                 fi
2567                 remove_build_requires
2568                 ;;
2569         "branch" )
2570                 init_builder
2571                 if [ -z "$SPECFILE" ]; then
2572                         Exit_error err_no_spec_in_cmdl
2573                 fi
2574
2575                 get_spec
2576                 parse_spec
2577                 branch_files $TAG
2578                 ;;
2579         "add_cvs" )
2580                 init_builder
2581                 if [ -z "$SPECFILE" ]; then
2582                         Exit_error err_no_spec_in_cmdl
2583                 fi
2584
2585                 create_git_repo
2586                 if [ -n "$NEW_REPO" ]; then
2587                         parse_spec
2588                         local file
2589                         for file in $SOURCES $PATCHES; do
2590                                 if [ -z $(src_md5 "$file") ]; then
2591                                         git add $file || Exit_error err_no_source_in_repo $file
2592                                 else
2593                                         cvsignore_df `nourl $file`
2594                                 fi
2595                         done
2596                         git add $SPECFILE
2597                         git commit -m 'Initial commit'
2598                         git push --dry-run $REMOTE_PLD master || Exit_error err_cvs_add_failed
2599                 else
2600                         echo "You had already git repository. Push chosen branches to remote: ${REMOTE_PLD}"
2601                 fi
2602                 ;;
2603         "get" )
2604                 init_builder
2605                 if [ -z "$SPECFILE" ]; then
2606                         Exit_error err_no_spec_in_cmdl
2607                 fi
2608
2609                 get_spec
2610                 parse_spec
2611
2612                 if [ -n "$NOSOURCE0" ] ; then
2613                         SOURCES=`echo $SOURCES | xargs | sed -e 's/[^ ]*//'`
2614                 fi
2615                 get_files $SOURCES $PATCHES
2616                 check_md5 $SOURCES
2617                 ;;
2618         "update_md5" )
2619                 init_builder
2620                 if [ -z "$SPECFILE" ]; then
2621                         Exit_error err_no_spec_in_cmdl
2622                 fi
2623
2624                 get_spec
2625                 parse_spec
2626
2627                 if [ -n "$NOSOURCE0" ] ; then
2628                         SOURCES=`echo $SOURCES | xargs | sed -e 's/[^ ]*//'`
2629                 fi
2630                 update_md5 $SOURCES $PATCHES
2631                 ;;
2632         "tag" )
2633                 NOURLS=1
2634                 NODIST="yes"
2635                 init_builder
2636                 if [ -z "$SPECFILE" ]; then
2637                         Exit_error err_no_spec_in_cmdl
2638                 fi
2639
2640                 parse_spec
2641                 if  [ ! -d .git ]; then
2642                         echo "No git reposiotory" >&2
2643                         exit 101
2644                 fi
2645                 tag_files
2646                 ;;
2647         "mr-proper" )
2648                 mr_proper
2649                 ;;
2650         "list-sources-files" )
2651                 init_builder
2652                 NOCVSSPEC="yes"
2653                 DONT_PRINT_REVISION="yes"
2654                 get_spec
2655                 parse_spec
2656                 for SAP in $SOURCES $PATCHES; do
2657                         echo $SAP | awk '{gsub(/.*\//,"") ; print}'
2658                 done
2659                 ;;
2660         "list-sources-urls" )
2661                 init_builder
2662                 NOCVSSPEC="yes"
2663                 DONT_PRINT_REVISION="yes"
2664                 get_spec
2665                 parse_spec
2666                 SAPS="$SOURCES $PATCHES"
2667                 for SAP in $SAPS ; do
2668                         echo $SAP
2669                 done
2670                 ;;
2671         "list-sources-local-paths" )
2672                 init_builder
2673                 NOCVSSPEC="yes"
2674                 DONT_PRINT_REVISION="yes"
2675                 get_spec
2676                 parse_spec
2677                 for SAP in $SOURCES $PATCHES; do
2678                         echo $PACKAGE_DIR/$(echo $SAP | awk '{gsub(/.*\//,"") ; print }')
2679                 done
2680                 ;;
2681         "list-sources-distfiles-paths" )
2682                 init_builder
2683                 NOCVSSPEC="yes"
2684                 DONT_PRINT_REVISION="yes"
2685                 get_spec
2686                 parse_spec
2687                 for SAP in $SOURCES $PATCHES; do
2688                         if [ -n "$(src_md5 "$SAP")" ]; then
2689                                 distfiles_path "$SAP"
2690                         fi
2691                 done
2692                 ;;
2693         "list-sources-distfiles" )
2694                 init_builder
2695                 NOCVSSPEC="yes"
2696                 DONT_PRINT_REVISION="yes"
2697                 get_spec
2698                 parse_spec
2699                 for SAP in $SOURCES $PATCHES; do
2700                         if [ -n "$(src_md5 "$SAP")" ]; then
2701                                 distfiles_url "$SAP"
2702                         fi
2703                 done
2704                 ;;
2705         "list-sources-cvs" )
2706                 init_builder
2707 #               NOCVSSPEC="yes"
2708                 DONT_PRINT_REVISION="yes"
2709                 get_spec
2710                 parse_spec
2711                 for SAP in $SOURCES $PATCHES; do
2712                         if [ -z "$(src_md5 "$SAP")" ]; then
2713                                 echo $SAP | awk '{gsub(/.*\//,"") ; print}'
2714                         fi
2715                 done
2716                 ;;
2717         "init_rpm_dir")
2718                 init_rpm_dir
2719                 ;;
2720         "usage" )
2721                 usage
2722                 ;;
2723         "short-version" )
2724                 echo "$VERSION"
2725                 ;;
2726         "version" )
2727                 echo "$VERSIONSTRING"
2728                 ;;
2729 esac
2730 if [ -f "`pwd`/.${SPECFILE}_INSTALLED_PACKAGES" -a "$REMOVE_BUILD_REQUIRES" != "" ]; then
2731         rm "`pwd`/.${SPECFILE}_INSTALLED_PACKAGES"
2732 fi
2733 cd "$__PWD"
2734
2735 # vi:syntax=sh:ts=4:sw=4:noet