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