Project

General

Profile

Download (225 KB) Statistics
| Branch: | Tag: | Revision:
1
#!/bin/sh
2
#
3
# Copyright 2013 iXsystems (Kris Moore)
4
# All rights reserved
5
#
6
# Redistribution and use in source and binary forms, with or without
7
# modification, are permitted providing that the following conditions
8
# are met:
9
# 1. Redistributions of source code must retain the above copyright
10
#    notice, this list of conditions and the following disclaimer.
11
# 2. Redistributions in binary form must reproduce the above copyright
12
#    notice, this list of conditions and the following disclaimer in the
13
#    documentation and/or other materials provided with the distribution.
14
#
15
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
19
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
23
# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
24
# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25
# POSSIBILITY OF SUCH DAMAGE.
26

    
27
usage_add_pbi() {
28
        cat <<EOF
29
usage: `basename $0` [options] pbi
30

    
31
Options:
32
  -e             -- Extract Only
33
  -f             -- Force install, overwriting existing installation
34
  -g             -- Get and show path to icon / images for gui installer
35
  -i             -- Display information about this PBI
36
  -l             -- Display LICENSE text
37
  -o outdir      -- Extract to target directory 
38
  -r 	         -- Fetch and install PBI
39
  -R 	         -- Fetch install file and save to disk (Do not install)
40
  -v             -- Enable verbose output
41
  --checkscript  -- Display any custom install / removal scripts
42
  --licagree     -- Agree to LICENSE terms for installation
43
  --meta         -- Display any custom meta-file supplied with the PBI
44
  --no-checksum  -- Skip the checksum verification during installation
45
  --no-checksig  -- Ignore signature verification and force install
46
  --no-hash      -- Disable using shared hash folder for PBI
47
  --rArch arch   -- Used with -r to specify the specific PBI machine type
48
  --rVer ver     -- Used with -r to specify the specific PBI version
49
  --repo repoid  -- Used with -r to specify the specific repo to pull from
50

    
51
EOF
52
        exit_trap
53
}
54

    
55
usage_autob_pbi() {
56
        cat <<EOF
57
usage: `basename $0` [options]
58

    
59
Options:
60
  -c confdir   -- Directory to traverse looking for meta-data modules <required>
61
  -d portdir   -- Use different ports dir (Default: /usr/ports)
62
  -h script    -- Call the following helper script after each build
63
  -o outdir    -- Where to place the finished PBI file(s) <required>
64
  -p <num>     -- Number of PBI builds to run concurrently (Defaults to 1)
65
  -32          -- Build i386 PBIs on amd64 host
66
  -32fallback  -- On amd64 host, build 32bit PBIs if only i386 can be built
67
  --genpatch   -- Generate patch files (*.pbp) from archived PBIs to current
68
  --keep <num> -- Keep <num> old versions in archive folder for each built PBI
69
  --prune      -- Remove files from 'outdir' that no longer have a module
70
  --pkgbuild   -- Build the PBIs using packages from PKGNG
71
  --tmpfs      -- Use TMPFS for port WRKDIRPREFIX
72
  --sign key   -- Sign the PBI(s) with specified openssl key
73

    
74
EOF
75
        exit_trap
76
}
77

    
78

    
79
usage_create_pbi() {
80
        cat <<EOF
81
usage: `basename $0` [options] pbidir
82

    
83
Options:
84
  -a author    -- Application Author
85
  -b 	       -- Make a backup of an already installed PBI
86
  -c confdir   -- PBI configuration meta-data directory
87
  -d portdir   -- Use different ports dir (Default: /usr/ports)
88
  -i icon      -- Application Icon, relative to pbidir/
89
  -n name      -- Application Name
90
  -o outdir    -- Output directory for finished .pbi file
91
  -p port      -- Pull name / version from FreeBSD Port
92
  -r version   -- Application Version
93
  -w url       -- Application Website
94
  --meta file  -- Include the specified <file> inside the PBI header
95
		  for display with "pbi_add --meta"
96
  --no-hash    -- Disable using shared hash folder for PBI
97
  --sign key   -- Sign the PBI with specified openssl key
98

    
99
EOF
100
        exit_trap
101
}
102

    
103
usage_delete_pbi() {
104
        cat <<EOF
105
usage: `basename $0` [options] pbi
106

    
107
Options:
108
  -v             -- Enable verbose output
109
  --clean-hdir   -- Perform a full cleaning of hash dir (Does not remove any PBIs)
110

    
111
EOF
112
        exit_trap
113
}
114

    
115
usage_make_pbi() {
116
        cat <<EOF
117
usage: `basename $0` [options] port
118

    
119
Options:
120
  -B 	       -- Build-only, do not run pbi_create when finished
121
  -c confdir   -- PBI configuration meta-data directory
122
  -d portdir   -- Use different ports dir (Default: /usr/ports)
123
  -k           -- Keep build files, don't delete when finished
124
  -o outdir    -- Where to place the finished PBI file
125
  -p prefix    -- Specify alternate PBI Compile PREFIX
126
  -32          -- Build i386 PBI on amd64 host
127
  --delbuild   -- Delete existing build dirs if they exist
128
  --meta file  -- Include the specified meta file in the PBI header
129
  --mkdebug    -- Drop to debug shell if port make fails
130
  --pkgbuild   -- Build PBI from PKGNG package repo
131
  --tmpfs      -- Use TMPFS for port WRKDIRPREFIX
132
  --no-prune   -- Do not prune non REQUIREDBY ports
133
  --sign key   -- Sign the PBI with specified openssl key
134

    
135
EOF
136
        exit_trap
137
}
138

    
139
usage_icon_pbi() {
140
        cat <<EOF
141
usage: `basename $0` [options] pbi
142

    
143
Options:
144
  add-desktop          -- Add desktop icons
145
  add-menu             -- Add menu icons
146
  add-mime             -- Add mime registration
147
  add-pathlnk          -- Add PATH links
148
  del-desktop          -- Remove desktop icons
149
  del-menu             -- Remove menu icons
150
  del-mime             -- Remove mime registration
151
  del-pathlnk          -- Remove PATH links
152

    
153
EOF
154
        exit_trap
155
}
156

    
157
usage_info_pbi() {
158
        cat <<EOF
159
usage: `basename $0` [options] pbi
160

    
161
Options:
162
  -a             -- Show all installed PBIs
163
  -v             -- Enable verbose output
164

    
165
EOF
166
        exit_trap
167
}
168

    
169
usage_makepatch_pbi() {
170
        cat <<EOF
171
usage: `basename $0` [options] oldpbi newpbi
172
                
173
Options:
174
  -o outdir      -- Save the .PBP file to outdir
175
  --tmpfs        -- Use TMPFS for extracting PBIs 
176
  --sign key     -- Sign the PBI with specified openssl key
177
  --no-checksig  -- Ignore signature verification and force install
178

    
179

    
180
EOF
181
        exit_trap
182
}
183

    
184
usage_addrepo_pbi() {
185
        cat <<EOF
186
usage: `basename $0` <Repo File>
187
                
188
EOF
189
        exit_trap
190
}
191

    
192
usage_deleterepo_pbi() {
193
        cat <<EOF
194
usage: `basename $0` <Repo ID>
195
                
196
EOF
197
        exit_trap
198
}
199

    
200
usage_mt_add() {
201
        cat <<EOF
202
usage: `basename $0` add [options] metafile
203
                
204
Options:
205
  --cat		-- Adding a new category metadata
206
  --app		-- Adding a new application metadata
207
  -a author   	-- Application author
208
  -c category  	-- Application category
209
  -d desc   	-- Description for application / category (Required)
210
  -i icon   	-- URL pointing to 64x64 PNG application / category icon (Required)
211
  -k keywords  	-- Application keywords for searching
212
  -l license  	-- Application license type
213
		   Example: BSD, GPL, Commercial
214
  -m email   	-- Port / Application Maintainer
215
  -n name   	-- Application / category name (Required)
216
  -t type  	-- Application interface type
217
		   Example; Graphical, Text, Service
218
  -u url 	-- Application homepage URL
219
  -r	 	-- Application must be installed as root
220
  -s shortdesc 	-- Short description for application
221

    
222
EOF
223
	exit_trap
224
}
225

    
226
usage_it_add() {
227
        cat <<EOF
228
usage: `basename $0` add [options] indexfile
229
                
230
Options:
231
  -b vers   	-- Mark previous versions as having binary diff patches available
232
		   I.E. (2.7.3,2.8.1,2.8.2)
233
  -f pbifile   	-- The PBI file we are adding to the index (Required)
234
  -k num   	-- The number of previous versions of this PBI to keep in the index
235
  -u fileurl   	-- The URL to this PBI on the mirror server(s) (Required)
236

    
237
EOF
238
	exit_trap
239
}
240

    
241
usage_mt_rem() {
242
        cat <<EOF
243
usage: `basename $0` rem [options] metafile
244
                
245
Options:
246
  --cat		-- Removing category metadata
247
  --app		-- Removing application metadata
248
  -n name   	-- The name we are removing from the metafile (Required)
249

    
250
EOF
251
	exit_trap
252
}
253

    
254
usage_mt_syncpbi() {
255
        cat <<EOF
256
usage: `basename $0` syncpbi pbifile metafile
257

    
258
This command will sync the meta-data from a PBI into the repo metafile
259
                
260
EOF
261
	exit_trap
262
}
263

    
264
usage_it_rem() {
265
        cat <<EOF
266
usage: `basename $0` rem [options] indexfile
267
                
268
Options:
269
  -m arch   	-- The PBI architecture to remove (Required)
270
		   I.E. (i386,amd64,etc)
271
  -n pbiname   	-- The PBI name we are removing from the index (Required)
272
  -v version   	-- The version of the PBI to remove (Required) 
273

    
274
EOF
275
	exit_trap
276
}
277

    
278
usage_mt_unknown() {
279
        cat <<EOF
280
usage: `basename $0` [options] metafile
281
                
282
Options:
283
  add   	-- Add a new entry to the specified metafile
284
  rem    	-- Remove an entry in the metafile
285
  syncpbi    	-- Sync meta-data from a PBI file
286

    
287
EOF
288
	exit_trap
289
}
290

    
291
usage_it_unknown() {
292
        cat <<EOF
293
usage: `basename $0` [options] indexfile
294
                
295
Options:
296
  add   	-- Add a new entry to the specified indexfile
297
  rem    	-- Remove an entry in the indexfile
298

    
299
EOF
300
	exit_trap
301
}
302

    
303
usage_browse_pbi() {
304
        cat <<EOF
305
usage: `basename $0` [options] [repoid]
306
                
307
Options:
308
  -c category  	-- List PBIs from the specified category
309
  -s search 	-- Search for the specified string
310
  --listcats  	-- List the available categories in this repository
311

    
312
EOF
313
        exit_trap
314
}
315

    
316
usage_listrepo_pbi() {
317
        cat <<EOF
318
usage: `basename $0` [options] [repoid]
319
                
320
Options:
321
  --down   	-- Move the specified repoid down in priority
322
  --mirror url 	-- Change the target repoid's mirror url
323
  --up  	-- Move the specified repoid up in priority
324

    
325
EOF
326
        exit_trap
327
}
328

    
329
usage_makerepo_pbi() {
330
        cat <<EOF
331
usage: `basename $0` [options] [outdir]
332
                
333
Options:
334
  --desc description   	-- Description for this new repo
335
  --key key    		-- Path to the public key file for this repo
336
  --url url    		-- Base URL for fetching the INDEX files
337
  --mirror mirrorurl 	-- Mirror url(s) for fetching PBIs, use ',' as 
338
			   seperator for multiple
339

    
340
EOF
341
        exit_trap
342
}
343

    
344
usage_patch_pbi() {
345
        cat <<EOF
346
usage: `basename $0` [options] pbp
347
                
348
Options:
349
  -e             -- Extract Only
350
  -g             -- Get and show path to icon / images for gui installer
351
  -i             -- Display information about this PBI
352
  -o outdir      -- Extract to target directory
353
  --checkscript  -- Display any custom install / removal scripts
354
  --no-checksig  -- Ignore signature verification and force install
355
  --no-hash      -- Disable using shared hash folder for PBI
356

    
357
EOF
358
        exit_trap
359
}
360

    
361
# update usage
362
usage_update_pbi() {
363
        cat <<EOF
364
usage: `basename $0` [options] pbi
365

    
366
Options:
367
  -c              -- Check-only, do not update target PBI
368
  --check-all     -- Perform a full check of all PBIs for updates
369
  --disable-auto  -- Disable auto-updating for the target PBI
370
  --enable-auto   -- Enable auto-updating for the target PBI
371
  --update-all    -- Update all PBIs to latest versions
372

    
373
EOF
374
        exit_trap
375
}
376

    
377
# Parse the command line for info
378
parse_delete_pbi_cmdline() {
379
        while [ $# -gt 0 ]; do
380
                case "$1" in
381
                -v)     PBI_VERBOSE="YES" 
382
                        ;;
383
      --clean-hdir)     pbi_clean_hashdir
384
			exit_trap
385
			;;
386
                 *)     if [ $# -gt 1 ]; then usage_delete_pbi; fi
387
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
388
				find_pbi_namematch "$1"
389
				if [ -z "$PBI_NAMEMATCH" ] ; then
390
                                	exit_err "can't find installed pbi (${1})"
391
				fi
392
                        	PBI_DELETENAME="$PBI_NAMEMATCH"
393
			else
394
                        	PBI_DELETENAME="$1"
395
                        fi
396
                        ;;
397
                esac
398
                shift
399
        done
400
	if [ -z "${PBI_DELETENAME}" ];then usage_delete_pbi; fi
401
}
402

    
403
find_pbi_namematch()
404
{
405
	_fLow="`echo ${1} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
406
	PBI_NAMEMATCH=""
407
	for i in `ls -d ${PBI_DBAPPDIR}/* 2>/dev/null`
408
	do
409
		if [ ! -e "$i/pbi_name" ] ; then continue ; fi
410
		_tLow="`cat $i/pbi_name | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
411
		if [ "$_tLow" = "$_fLow" ] ; then 
412
			PBI_NAMEMATCH="`basename ${i}`"
413
			break
414
		fi
415
	done
416
}
417

    
418
# Parse the command line for icon
419
parse_icon_pbi_cmdline() {
420
        while [ $# -gt 0 ]; do
421
                case "$1" in
422
                add-desktop)	PBI_DESKADD="YES" ;;
423
                add-menu)	PBI_MENUADD="YES" ;;
424
                add-mime)	PBI_MIMEADD="YES" ;;
425
                add-pathlnk)	PBI_PATHADD="YES" ;;
426
                del-desktop)	PBI_DESKDEL="YES" ;;
427
                del-menu)	PBI_MENUDEL="YES" ;;
428
                del-mime)	PBI_MIMEDEL="YES" ;;
429
                del-pathlnk)	PBI_PATHDEL="YES" ;;
430
                 *)
431
                        if [ $# -gt 1 ]; then usage_icon_pbi; fi
432
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
433
				find_pbi_namematch "$1"
434
				if [ -z "$PBI_NAMEMATCH" ] ; then
435
                                	exit_err "can't find installed pbi (${1})"
436
				fi
437
                        	PBI_ICONTARGETAPP="${PBI_NAMEMATCH}"
438
			else
439
                        	PBI_ICONTARGETAPP="$1"
440
                        fi
441
                        ;;
442
                esac
443
                shift
444
        done
445
	if [ -z "${PBI_ICONTARGETAPP}" ] ; then 
446
		usage_icon_pbi
447
	fi
448
}
449

    
450
# Parse the command line for pbid
451
parse_pbid_cmdline() {
452
        while [ $# -gt 0 ]; do
453
                case "$1" in
454
                -v)     PBI_VERBOSE="YES" 
455
                        ;;
456
         --refresh)     # Schedule us to refresh the index
457
			echo "Your meta and index files will begin refreshing in a moment..."
458
			echo "Details available in /var/log/pbid.log"
459
			rm ${PBI_DBINDEXDIR}/*.time >/dev/null 2>/dev/null
460
			if [ -e "${PROGBASE}/etc/rc.d/pbid" ]; then
461
			   ${PROGBASE}/etc/rc.d/pbid restart >/dev/null 2>/dev/null
462
			fi
463
			exit 0
464
                        ;;
465
		esac
466
		shift
467
	done
468
}
469

    
470
# Parse the command line for info
471
parse_info_pbi_cmdline() {
472
        while [ $# -gt 0 ]; do
473
                case "$1" in
474
                -a)     PBI_INFONAME="--ALL--"
475
                        ;;
476
		-i) 	PBI_INFOINDEX="YES"	
477
			;;
478
                -v)     PBI_VERBOSE="YES" 
479
                        ;;
480
                 *)
481
                        if [ $# -gt 1 ]; then usage_info_pbi; fi
482
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
483
				find_pbi_namematch "$1"
484
				if [ -z "$PBI_NAMEMATCH" ] ; then
485
                                	exit_err "can't find installed pbi (${1})"
486
				fi
487
                        	PBI_INFONAME="$PBI_NAMEMATCH"
488
			else
489
                        	PBI_INFONAME="$1"
490
                        fi
491
                        ;;
492
                esac
493
                shift
494
        done
495
	if [ -z "${PBI_INFONAME}" ] ; then 
496
		PBI_INFONAME="--ALL--" 
497
	fi
498
}
499

    
500
# Parse the command line for patching
501
parse_makepatch_pbi_cmdline() {
502
        while [ $# -gt 0 ]; do
503
                case "$1" in
504
                -o)     if [ $# -eq 1 ]; then usage_makepatch_pbi; fi
505
                        shift; PBI_PATCHOUTDIR="$1"
506
                        ;;
507
            --sign)     if [ $# -eq 1 ]; then usage_makepatch_pbi; fi
508
                        shift; PBI_SSLPRIVKEY="$1"
509
                        ;;
510
           --tmpfs)     PBI_MP_TMPFS="YES" 
511
                        ;;
512
     --no-checksig)     PBI_SKIPSIGVERIFY="YES" ;;
513
                 *)	if [ $# -gt 2  ]; then usage_makepatch_pbi; fi
514
                       	PBI_OLDFILENAME="$1"
515
			shift
516
                       	PBI_FILENAME="$1"
517
                        ;;
518
                esac
519
                shift
520
        done
521

    
522
        if [ -z "${PBI_FILENAME}" ]; then usage_makepatch_pbi ; fi
523
        if [ -z "${PBI_OLDFILENAME}" ]; then usage_makepatch_pbi ; fi
524
        if [ -z "${PBI_PATCHOUTDIR}" ]; then PBI_PATCHOUTDIR=`pwd` ; fi
525

    
526
        # Load all the information about this PBI / PBP
527
        load_info_from_header
528
}
529

    
530
# Parse the command line for editing a meta file
531
parse_mt_pbi_cmdline() {
532

    
533
	case $1 in
534
      	syncpbi) PBI_MT_MODE="SYNCPBI" ; shift ; 
535
		PBI_MT_PBIFILE="$1"
536
		PBI_MT_METAFILE="$2"
537
		if [ -z "${PBI_MT_PBIFILE}" ] ; then usage_mt_syncpbi ; fi
538
		if [ -z "${PBI_MT_METAFILE}" ] ; then usage_mt_syncpbi ; fi
539
		return
540
		;;
541
  	   add)	PBI_MT_MODE="ADD" ; shift ; 
542
		while [ $# -gt 0 ]; do
543
                	case "$1" in
544
            	      --cat) PBI_MT_TYPE="CAT" ;;
545
            	      --app) PBI_MT_TYPE="APP" ;;
546
			-m) if [ $# -eq 1  ]; then usage_mt_add; fi
547
			    shift; PBI_MT_MAINTAINER="$1"
548
			    ;;
549
          		-n) if [ $# -eq 1  ]; then usage_mt_add; fi
550
                       	    shift; PBI_MT_ADDNAME="$1"
551
			    ;;
552
          		-i) if [ $# -eq 1  ]; then usage_mt_add; fi
553
                       	    shift; PBI_MT_ADDICON="$1"
554
			    ;;
555
          		-d) if [ $# -eq 1  ]; then usage_mt_add; fi
556
                       	    shift; PBI_MT_ADDDESC="$1"
557
			    ;;
558
			-s) if [ $# -eq 1  ]; then usage_mt_add; fi
559
			    shift; PBI_MT_ADDSHORTDESC="$1"
560
			    ;;
561
          		-c) if [ $# -eq 1  ]; then usage_mt_add; fi
562
                       	    shift; PBI_MT_ADDCAT="$1"
563
			    ;;
564
          		-a) if [ $# -eq 1  ]; then usage_mt_add; fi
565
                       	    shift; PBI_MT_ADDAUTHOR="$1"
566
			    ;;
567
          		-u) if [ $# -eq 1  ]; then usage_mt_add; fi
568
                       	    shift; PBI_MT_ADDURL="$1"
569
			    ;;
570
          		-l) if [ $# -eq 1  ]; then usage_mt_add; fi
571
                       	    shift; PBI_MT_ADDLIC="$1"
572
			    ;;
573
          		-t) if [ $# -eq 1  ]; then usage_mt_add; fi
574
                       	    shift; PBI_MT_ADDTYPE="$1"
575
			    ;;
576
          		-k) if [ $# -eq 1  ]; then usage_mt_add; fi
577
                       	    shift; PBI_MT_ADDKEYWORDS="$1"
578
			    ;;
579
          		-r) PBI_MT_REQUIRESROOT="YES"
580
			    ;;
581
                         *) if [ $# -gt 1  ]; then usage_mt_add; fi
582
                       	    PBI_MT_METAFILE="$1"
583
                            ;;
584
                	esac
585
                	shift
586
 	       	done
587
		if [ -z "${PBI_MT_METAFILE}" ] ; then usage_mt_add ; fi
588
	  	;;
589
  	   rem)	PBI_MT_MODE="REM" ; shift ; 
590
		while [ $# -gt 0 ]; do
591
                	case "$1" in
592
            	      --cat) PBI_MT_TYPE="CAT" ;;
593
            	      --app) PBI_MT_TYPE="APP" ;;
594
          		-n) if [ $# -eq 1  ]; then usage_mt_rem; fi
595
                       	    shift; PBI_MT_REMNAME="$1"
596
			    ;;
597
                         *) if [ $# -gt 1  ]; then usage_mt_rem; fi
598
                       	    PBI_MT_METAFILE="$1"
599
                            ;;
600
			esac
601
			shift
602
		done
603
		if [ -z "${PBI_MT_METAFILE}" ] ; then usage_mt_rem ; fi
604
		;;
605
  	     *) usage_mt_unknown ;;
606
	esac
607

    
608
 	if [ ! -f "${PBI_MT_METAFILE}" ] ; then 
609
		exit_err "No such file ${PBI_MT_METAFILE}"
610
        fi
611

    
612
	# Sanity check the values
613
	case ${PBI_MT_MODE} in
614
		ADD) # Check the common values 
615
		     if [ -z "${PBI_MT_ADDNAME}" ] ; then usage_mt_add ; fi
616
		     if [ -z "${PBI_MT_ADDDESC}" ] ; then usage_mt_add ; fi
617
		     if [ -z "${PBI_MT_ADDICON}" ] ; then usage_mt_add ; fi
618

    
619
	 	     if [ "$PBI_MT_TYPE" = "CAT" ]; then	      
620
		     elif [ "$PBI_MT_TYPE" = "APP" ]; then
621
		     	if [ -z "${PBI_MT_ADDCAT}" ]; then usage_mt_add ; fi
622
		     	if [ -z "${PBI_MT_ADDAUTHOR}" ]; then usage_mt_add ; fi
623
		     	if [ -z "${PBI_MT_ADDURL}" ]; then usage_mt_add ; fi
624
		     	if [ -z "${PBI_MT_ADDLIC}" ]; then usage_mt_add ; fi
625
		     	if [ -z "${PBI_MT_ADDTYPE}" ]; then usage_mt_add ; fi
626
		     else
627
		       usage_mt_add
628
		     fi
629
		;;
630
		REM) if [ "$PBI_MT_TYPE" != "CAT" -a "$PBI_MT_TYPE" != "APP" ]
631
		     then
632
		        usage_mt_rem
633
		     fi
634
		     if [ -z "${PBI_MT_REMNAME}" ] ; then usage_mt_rem ; fi
635
		;;
636
	esac
637

    
638
}
639

    
640
# Parse the command line for editing a index file
641
parse_it_pbi_cmdline() {
642

    
643
	case $1 in
644
  	   add)	PBI_IT_MODE="ADD" ; shift ; 
645
		while [ $# -gt 0 ]; do
646
                	case "$1" in
647
          		-b) if [ $# -eq 1  ]; then usage_it_add; fi
648
                       	    shift; PBI_IT_ADDBPVERS="$1"
649
			    ;;
650
          		-f) if [ $# -eq 1  ]; then usage_it_add; fi
651
                       	    shift; PBI_IT_ADDFILE="$1"
652
			    ;;
653
          		-k) if [ $# -eq 1  ]; then usage_it_add; fi
654
                       	    shift; PBI_IT_ADDKEEP="$1"
655
			    ;;
656
          		-u) if [ $# -eq 1  ]; then usage_it_add; fi
657
                       	    shift; PBI_IT_ADDURL="$1"
658
			    ;;
659
                         *) if [ $# -gt 1  ]; then usage_it_add; fi
660
                       	    PBI_IT_ADDINDEX="$1"
661
                            ;;
662
                	esac
663
                	shift
664
 	       	done
665
	  	;;
666
  	   rem)	PBI_IT_MODE="REM" ; shift ; 
667
		while [ $# -gt 0 ]; do
668
                	case "$1" in
669
          		-m) if [ $# -eq 1  ]; then usage_it_rem; fi
670
                       	    shift; PBI_IT_REMARCH="$1"
671
			    ;;
672
          		-n) if [ $# -eq 1  ]; then usage_it_rem; fi
673
                       	    shift; PBI_IT_REMNAME="$1"
674
			    ;;
675
          		-v) if [ $# -eq 1  ]; then usage_it_rem; fi
676
                       	    shift; PBI_IT_REMVER="$1"
677
			    ;;
678
                         *) if [ $# -gt 1  ]; then usage_it_rem; fi
679
                       	    PBI_IT_REMINDEX="$1"
680
                            ;;
681
			esac
682
			shift
683
		done
684
		;;
685
  	     *) usage_it_unknown ;;
686
	esac
687

    
688
	# Sanity check the values
689
	case ${PBI_IT_MODE} in
690
		ADD) if [ -z "${PBI_IT_ADDFILE}" ] ; then usage_it_add ; fi
691
		     if [ -z "${PBI_IT_ADDURL}" ] ; then usage_it_add ; fi
692
		     if [ -z "${PBI_IT_ADDINDEX}" ] ; then usage_it_add ; fi
693
		     if [ ! -f "${PBI_IT_ADDFILE}" ] ; then 
694
			exit_err "No such file ${PBI_IT_ADDFILE}"
695
		     fi
696
		     if [ ! -f "${PBI_IT_ADDINDEX}" ] ; then 
697
			exit_err "No such file ${PBI_IT_ADDINDEX}"
698
		     fi
699
		     if [ -n "${PBI_IT_ADDKEEP}" ] ; then 
700
			expr ${PBI_IT_ADDKEEP} + 1 >/dev/null 2>/dev/null
701
			if [ "$?" != "0" ] ; then
702
				exit_err "-k option must be a integer!"
703
			fi
704
		     fi
705
		;;
706
		REM) if [ -z "${PBI_IT_REMNAME}" ] ; then usage_it_rem ; fi
707
		     if [ -z "${PBI_IT_REMVER}" ] ; then usage_it_rem ; fi
708
		     if [ -z "${PBI_IT_REMARCH}" ] ; then usage_it_rem ; fi
709
		     if [ -z "${PBI_IT_REMINDEX}" ] ; then usage_it_rem ; fi
710
		;;
711
	esac
712

    
713
}
714

    
715
# Parse the command line for browsing a repo
716
parse_browse_pbi_cmdline() {
717
        while [ $# -gt 0 ]; do
718
                case "$1" in
719
        --listcats)     PBI_BROWSE_LISTCATS="YES" ;; 
720
         --viewall)     PBI_BROWSE_LISTALLPBI="YES" ;; 
721
                -c)	if [ $# -eq 1  ]; then usage_browse_pbi; fi
722
                       	shift; PBI_BROWSE_CAT="$1"
723
			;;
724
                -s)	if [ $# -eq 1  ]; then usage_browse_pbi; fi
725
                       	shift; PBI_BROWSE_SEARCH="$1"
726
			;;
727
                 *)	if [ $# -gt 1  ]; then usage_browse_pbi; fi
728
                       	PBI_BROWSE_RID="$1"
729
                        ;;
730
                esac
731
                shift
732
        done
733

    
734
	# Get / check the repoid
735
	if [ -n "${PBI_BROWSE_RID}" ] ; then
736
		ls ${PBI_DBREPODIR}/${PBI_BROWSE_RID}.* >/dev/null 2>/dev/null
737
		if [ "$?" != "0" ] ; then
738
			exit_err "The specified repoid ${PBI_BROWSE_RID} does not exist!"
739
		fi
740
	else
741
		for _repo in `ls ${PBI_DBREPODIR} 2>/dev/null`
742
		do
743
			PBI_BROWSE_RID=`echo $_repo | cut -d '.' -f 1`
744
			break;
745
		done
746
		if [ -z "$PBI_BROWSE_RID" ] ; then exit_err "No available repos!" ; fi
747
	fi
748

    
749
	PBI_BROWSE_REPOMD5=`ls ${PBI_DBREPODIR}/${PBI_BROWSE_RID}.* 2>/dev/null | cut -d '.' -f 2`
750
	PBI_BROWSE_METAFILE=`ls ${PBI_DBINDEXDIR}/${PBI_BROWSE_REPOMD5}*meta 2>/dev/null`
751
	if [ -z "${PBI_BROWSE_METAFILE}" ] ; then
752
		exit_err "The specified repo has no meta-file."
753
	fi
754

    
755
}
756

    
757
# Parse the command line for listing repos
758
parse_listrepo_pbi_cmdline() {
759
        while [ $# -gt 0 ]; do
760
                case "$1" in
761
              --up)     PBI_LISTREPO_UP="YES" ;; 
762
            --down)     PBI_LISTREPO_DOWN="YES" ;; 
763
          --mirror)	if [ $# -eq 1  ]; then usage_listrepo_pbi; fi
764
                       	shift; PBI_LISTREPO_MIRROR="$1"
765
			;;
766
                 *)	if [ $# -gt 1  ]; then usage_listrepo_pbi; fi
767
                       	PBI_LISTREPO_ID="$1"
768
                        ;;
769
                esac
770
                shift
771
        done
772

    
773
	if [ "${PBI_LISTREPO_UP}" = "YES" -a "${PBI_LISTREPO_DOWN}" = "YES" ]; then
774
		exit_err "Options --up and --down can't both be used at once!"
775
	fi
776
	if [ "${PBI_LISTREPO_UP}" = "YES" -a -z "${PBI_LISTREPO_ID}" ]; then
777
		exit_err "Missing Repo ID to move up in priority."
778
	fi
779
	if [ "${PBI_LISTREPO_DOWN}" = "YES" -a -z "${PBI_LISTREPO_ID}" ]; then
780
		exit_err "Missing Repo ID to move down in priority."
781
	fi
782
	if [ -n "${PBI_LISTREPO_MIRROR}" -a -z "${PBI_LISTREPO_ID}" ]; then
783
		exit_err "Missing Repo ID to change a specific mirror URL."
784
	fi
785

    
786
	if [ -n "${PBI_LISTREPO_ID}" ] ; then
787
		ls ${PBI_DBREPODIR}/${PBI_LISTREPO_ID}.* >/dev/null 2>/dev/null
788
		if [ "$?" != "0" ] ; then
789
			exit_err "The specified repoid ${PBI_LISTREPO_ID} does not exist!"
790
		fi
791
	fi
792
}
793

    
794
# Parse the command line for adding a new repo file
795
parse_addrepo_pbi_cmdline() {
796
        while [ $# -gt 0 ]; do
797
                case "$1" in
798
                 *)	if [ $# -gt 1  ]; then usage_addrepo_pbi; fi
799
                       	PBI_ADDREPO_FILE="$1"
800
                        ;;
801
                esac
802
                shift
803
        done
804

    
805
	if [ -z "$PBI_ADDREPO_FILE" ] ; then 
806
		usage_addrepo_pbi
807
	fi
808
	if [ ! -f "$PBI_ADDREPO_FILE" ] ; then 
809
		exit_err "Repo file ${PBI_ADDREPO_FILE} does not exist!"
810
	fi
811
}
812

    
813
# Parse the command line for deleting a repo
814
parse_deleterepo_pbi_cmdline() {
815
        while [ $# -gt 0 ]; do
816
                case "$1" in
817
                 *)	if [ $# -gt 1  ]; then usage_deleterepo_pbi; fi
818
                       	PBI_DELREPO_ID="$1"
819
                        ;;
820
                esac
821
                shift
822
        done
823

    
824
	if [ -z "$PBI_DELREPO_ID" ] ; then 
825
		usage_deleterepo_pbi
826
	fi
827
}
828

    
829

    
830
# Parse the command line for making a new repo file
831
parse_makerepo_pbi_cmdline() {
832
        while [ $# -gt 0 ]; do
833
                case "$1" in
834
             --key)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
835
                        shift; PBI_MKREPO_KEY="$1"
836
                        ;;
837
             --url)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
838
                        shift; PBI_MKREPO_URL="$1"
839
                        ;;
840
            --desc)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
841
                        shift; PBI_MKREPO_DESC="$1"
842
                        ;;
843
          --mirror)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
844
                        shift; PBI_MKREPO_MIRROR="$1"
845
                        ;;
846
                 *)	if [ $# -gt 1  ]; then usage_makerepo_pbi; fi
847
                       	PBI_MKREPO_OUTDIR="$1"
848
                        ;;
849
                esac
850
                shift
851
        done
852

    
853
        if [ -z "${PBI_MKREPO_DESC}" ]; then usage_makerepo_pbi ; fi
854
        if [ -z "${PBI_MKREPO_KEY}" ]; then usage_makerepo_pbi ; fi
855
        if [ -z "${PBI_MKREPO_MIRROR}" ]; then usage_makerepo_pbi ; fi
856
        if [ -z "${PBI_MKREPO_URL}" ]; then usage_makerepo_pbi ; fi
857
        if [ -z "${PBI_MKREPO_OUTDIR}" ]; then PBI_MKREPO_OUTDIR="${HOME}"; fi
858
        if [ ! -f "${PBI_MKREPO_KEY}" ]; then exit_err "The key file ${PBI_MKREPO_KEY} does not exist." ; fi
859
	
860
	# Make sure we have a valid URL format
861
        echo "${PBI_MKREPO_URL}" | grep -q -e "^http://" -e "^https://" -e "^ftp://"
862
	if [ $? -ne 0 ] ; then
863
		exit_err "Repo URL must begin with http://, https://, or ftp://"
864
	fi
865
	
866

    
867
}
868

    
869
# Parse the command line for patching
870
parse_patch_pbi_cmdline() {
871
        while [ $# -gt 0 ]; do
872
                case "$1" in
873
                -e)     PBI_EXTRACTONLY="YES"
874
                        ;;
875
                -g)     PBI_ADD_GUIDISPLAY="YES" 
876
                        ;;
877
                -i)     PBI_ADD_INFODISPLAY="YES" 
878
                        ;;
879
                -o)
880
                        if [ $# -eq 1 ]; then usage_patch_pbi; fi
881
                        shift; PBI_ALTEXTRACT_DIR="$1"
882
                        ;;
883
     --checkscript)     PBI_CHECKSCRIPTS="YES" ;;
884
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
885
     --no-checksum)     PBI_SKIPCHECKSUM="YES" ;;
886
     --no-checksig)     PBI_SKIPSIGVERIFY="YES" ;;
887
                 *)	if [ $# -gt 1 ]; then usage_patch_pbi; fi
888
                        PBI_FILENAME="$1"
889
                        ;;
890
                esac
891
                shift
892
        done
893

    
894
        if [ -z "${PBI_FILENAME}" ]; then usage_patch_pbi ; fi
895

    
896
	# Get the absolute patch to the file
897
        get_abspath "$PBI_FILENAME"
898
	PBI_FILENAME="$_ABSPATH"
899

    
900
        if [ ! -e "${PBI_FILENAME}" ]; then usage_patch_pbi ; fi
901

    
902
        # Load all the information about this PBI / PBP
903
        load_info_from_header
904

    
905
	# Make sure this isn't a patch file
906
	is_pbi_patch
907
	if [ "$?" = "1" ] ; then
908
		exit_err "This is not a PBP patch file"
909
	fi
910

    
911
        if [ -z "${PBI_ORIGPROGDIRPATH}" ]; then usage_patch_pbi ; fi
912

    
913
        # Lastly set PBI_PROGDIRNAME
914
        PBI_PROGDIRNAME="`echo ${PBI_ORIGPROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
915
                        
916
        if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then
917
                # If extracting to a alt-outdir, set it now
918
                PBI_PROGDIRPATH="`pwd`/${PBI_PROGDIRNAME}"
919
        
920
                if [ -n "${PBI_ALTEXTRACT_DIR}" ]; then
921
                        PBI_PROGDIRPATH="${PBI_ALTEXTRACT_DIR}/${PBI_PROGDIRNAME}"
922
                fi      
923
        else
924
                # Set the extraction dir
925
                PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}-patch"
926
        fi
927
}
928

    
929
# Parse the command line for adding
930
parse_add_pbi_cmdline() {
931
        while [ $# -gt 0 ]; do
932
                case "$1" in
933
                -e)     PBI_EXTRACTONLY="YES"
934
                        ;;
935
                -f)     PBI_FORCEADD="YES"
936
                        ;;
937
                -g)     PBI_ADD_GUIDISPLAY="YES" 
938
                        ;;
939
                -i)     PBI_ADD_INFODISPLAY="YES" 
940
                        ;;
941
            --meta)     PBI_ADD_METADISPLAY="YES" 
942
                        ;;
943
                -l)     PBI_ADD_LICDISPLAY="YES" 
944
                        ;;
945
                -o)     if [ $# -eq 1 ]; then usage_add_pbi; fi
946
                        shift; PBI_ALTEXTRACT_DIR="$1"
947
                        ;;
948
                -r)     PBI_REMOTEFETCH="YES" 
949
			;;
950
                -R)     PBI_REMOTEFETCH="YES" 
951
			PBI_REMOTEFETCHONLY="YES"
952
			;;
953
                -v)     PBI_VERBOSE="YES" 
954
                        ;;
955
           --rArch)     
956
                        if [ $# -eq 1 ]; then usage_add_pbi; fi
957
                        shift; PBI_ADD_ALTARCH="$1"
958
                        ;;
959
           --rVer)     
960
                        if [ $# -eq 1 ]; then usage_add_pbi; fi
961
                        shift; PBI_ADD_ALTVER="$1"
962
                        ;;
963
     --checkscript)     PBI_CHECKSCRIPTS="YES" ;;
964
        --licagree)     PBI_LICAGREE="YES" ;;
965
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
966
     --no-checksum)     PBI_SKIPCHECKSUM="YES" ;;
967
     --no-checksig)     PBI_SKIPSIGVERIFY="YES" ;;
968
            --repo)     if [ $# -eq 1 ]; then usage_add_pbi; fi
969
                        shift; PBI_ADDREPO_ID="$1"
970
                        ;;
971
                 *)
972
                        if [ $# -gt 1 ]; then usage_add_pbi; fi
973
			# If there is no file, try fetching from repo
974
                        if [ ! -e "${1}" ] ; then PBI_REMOTEFETCH="YES"; fi
975
                        PBI_FILENAME="$1"
976
                        ;;
977
                esac
978
                shift
979
        done
980

    
981
        if [ -z "${PBI_FILENAME}" ]; then usage_add_pbi ; fi
982

    
983
	# If we are doing a remote fetch / install then do it now
984
	if [ "$PBI_REMOTEFETCH" = "YES" ] ; then
985
		if [ -z "${PBI_ADDREPO_ID}" ] ; then
986
			PBI_ADDREPO_ID="AUTO"
987
		else
988
			ls ${PBI_DBREPODIR}/${PBI_ADDREPO_ID}.* >/dev/null 2>/dev/null
989
			if [ "$?" != "0" ] ; then
990
				exit_err "No such repo ID: ${PBI_DELREPO_ID}"
991
			fi
992
		fi
993

    
994
		# Start fetching file
995
		pbi_add_fetch_remote
996
	
997
	fi
998

    
999
        # Load all the information about this PBI
1000
        load_info_from_header
1001

    
1002
        if [ -z "${PBI_ORIGPROGDIRPATH}" ]; then usage_add_pbi ; fi
1003

    
1004
	# Make sure this isn't a patch file
1005
	is_pbi_patch
1006
	if [ "$?" = "0" ] ; then
1007
		exit_err "This is a PBP patch file, use 'pbi_patch' instead"
1008
	fi
1009

    
1010
        # Lastly set PBI_PROGDIRNAME
1011
        PBI_PROGDIRNAME="`echo ${PBI_ORIGPROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
1012

    
1013

    
1014
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then
1015
		# If extracting to a alt-outdir, set it now
1016
		PBI_PROGDIRPATH="`pwd`/${PBI_PROGDIRNAME}"
1017

    
1018
		if [ -n "${PBI_ALTEXTRACT_DIR}" ]; then
1019
			PBI_PROGDIRPATH="${PBI_ALTEXTRACT_DIR}/${PBI_PROGDIRNAME}"
1020
		fi
1021
	else
1022
		# Set the installation dir
1023
		PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}"
1024
	fi
1025
}
1026

    
1027
# Parse the command line
1028
parse_autob_pbi_cmdline() {
1029
        while [ $# -gt 0 ]; do
1030
                case "$1" in
1031
                -c)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
1032
                        if [ -n "${PBI_AB_CONFDIR}" ]; then usage_autob_pbi; fi
1033
                        shift
1034
                        get_abspath "$1"
1035
                        PBI_AB_CONFDIR="$_ABSPATH"
1036
                        if [ ! -d "${PBI_AB_CONFDIR}" ] ; then
1037
                                exit_err "Invalid confdir (${PBI_AB_CONFDIR})"
1038
                        fi
1039
                        ;;
1040
                -d)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
1041
                        shift
1042
                        get_abspath "$1"
1043
                        PORTSDIR="$_ABSPATH"
1044
                        ;;
1045
                -o)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
1046
                        shift
1047
                        get_abspath "$1"
1048
                        PBI_AB_OUTDIR="$_ABSPATH"
1049
                        ;;
1050
                -p)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
1051
                        shift
1052
                        PBI_AB_BUILDERS="$1"
1053
			if [ ! $(is_num "$PBI_AB_BUILDERS") ] ; then 
1054
				exit_err "Invalid process number specifed!"
1055
			fi
1056
                        ;;
1057
                -h)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
1058
                        shift
1059
                        get_abspath "$1"
1060
                        PBI_AB_HELPS="$_ABSPATH"
1061
                        ;;
1062
                -32)    if [ "$REALARCH" != "amd64" ] ; then 
1063
				exit_err "-32 can only be used on amd64 host"
1064
			fi	
1065
			PBI_AB32="YES"
1066
			ARCH=i386
1067
                        ;;
1068
        -32fallback)    if [ "$REALARCH" != "amd64" ] ; then 
1069
				exit_err "-32fallback can only be used on amd64 host"
1070
			fi	
1071
			PBI_ABFB32="YES"
1072
                        ;;
1073

    
1074
        --genpatch)     PBI_AB_GENPATCH="YES" 
1075
                        ;;
1076
        --pkgbuild)     PBI_AB_PKGBUILD="YES" 
1077
                        ;;
1078
            --keep)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
1079
                        shift; PBI_AB_ARCHIVENUM="$1"
1080
			expr $PBI_AB_ARCHIVENUM + 1 >/dev/null 2>/dev/null
1081
			if [ $? != 0 ] ; then usage_autob_pbi; fi
1082
                        ;;
1083
           --prune)     PBI_AB_PRUNE="YES" 
1084
                        ;;
1085
           --tmpfs)     PBI_AB_TMPFS="YES" 
1086
                        ;;
1087
            --sign)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
1088
                        shift; PBI_AB_SSLPRIVKEY="$1"
1089
                        ;;
1090
                 *)     usage_autob_pbi ;;
1091
                esac
1092
                shift
1093
        done
1094

    
1095
	if [ -z "$PBI_AB_OUTDIR" ] ; then usage_autob_pbi ; fi
1096
	if [ -z "$PBI_AB_CONFDIR" ] ; then usage_autob_pbi ; fi
1097
}
1098

    
1099

    
1100
# Parse the command line
1101
parse_create_pbi_cmdline() {
1102
        while [ $# -gt 0 ]; do
1103
                case "$1" in
1104
                -a)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1105
                        shift; PBI_CAUTHOR="$1"
1106
                        ;;
1107
                -b)     PBI_CBACKUP="YES"
1108
                        ;;
1109
                -c)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1110
                        shift; 
1111
			get_abspath "$1"
1112
			PBI_CONFDIR="$_ABSPATH"
1113
			if [ ! -d "${PBI_CONFDIR}" ] ; then
1114
				exit_err "Invalid confdir (${PBI_CONFDIR})"
1115
			fi
1116
			load_pbi_conffile
1117
                        ;;
1118
                -d)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1119
                        shift; PORTSDIR="$1"
1120
                        ;;
1121
               --meta)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1122
                        shift; PBI_CREATE_USERMETA="$1"
1123
			if [ ! -e "$PBI_CREATE_USERMETA" ] ; then
1124
				exit_err "No such file: $PBI_CREATE_USERMETA"
1125
			fi
1126
                        ;;
1127
                -i)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1128
                        shift; PBI_CICON="$1"
1129
                        ;;
1130
                -n)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1131
                        shift; PBI_CNAME="$1"
1132
                        ;;
1133
                -o)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1134
                        shift; PBI_CREATE_OUTDIR="$1"
1135
                        ;;
1136
                -p)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1137
                        shift; PBI_MAKEPORT="$1"
1138
                        ;;
1139
                -r)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1140
                        shift; PBI_CVERSION="$1"
1141
                        ;;
1142
                -w)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1143
                        shift; PBI_CWEB="$1"
1144
                        ;;
1145
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
1146
            --sign)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1147
                        shift; PBI_SSLPRIVKEY="$1"
1148
                        ;;
1149
                 *)
1150
                        if [ $# -gt 1 ]; then usage_create_pbi; fi
1151
			if [ "$PBI_CBACKUP" = "YES" ] ; then
1152
				if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
1153
					find_pbi_namematch "$1"
1154
					if [ -z "$PBI_NAMEMATCH" ] ; then
1155
                                		exit_err "can't find installed pbi (${1})"
1156
					fi
1157
					PBI_CBACKUPTARGET="${PBI_NAMEMATCH}"
1158
					PBI_PROGDIRPATH="${PBI_NAMEMATCH}"
1159
				else
1160
					PBI_CBACKUPTARGET="${1}"
1161
					PBI_PROGDIRPATH="${1}"
1162
                        	fi
1163
			else
1164
				get_abspath "$1"
1165
				PBI_PROGDIRPATH="$_ABSPATH"
1166
                        	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then
1167
                                	exit_err "Invalid pbidir (${1})"
1168
                          	fi
1169
			fi
1170
                        ;;
1171
                esac
1172
                shift
1173
        done
1174

    
1175
	# Make sure this port exists
1176
        if [ -n "${PBI_MAKEPORT}" -a ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ]; then
1177
		exit_err "No port (${PORTSDIR}/${PBI_MAKEPORT})"
1178
	fi
1179

    
1180
	# Load the name / version from specified port
1181
        if [ -n "${PBI_MAKEPORT}" ]; then
1182
		get_pbi_progversion
1183
		get_pbi_progname
1184
        fi
1185

    
1186
        if [ -z "${PBI_PROGDIRPATH}" ]; then usage_create_pbi ; fi
1187

    
1188
	# Remove any trailing '/' from PBI_MAKEPORT
1189
	echo $PBI_MAKEPORT | grep -q "/$"
1190
	if [ $? -eq 0 ] ; then
1191
		PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
1192
	fi
1193

    
1194
	# Lastly set PBI_PROGDIRNAME
1195
	PBI_PROGDIRNAME="`echo ${PBI_PROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
1196
}
1197

    
1198
# Override any pbi.conf values with passed command-line values
1199
parse_cmdline_overrides() {
1200
	if [ -n "${PBI_CNAME}" ] ; then PBI_PROGNAME="${PBI_CNAME}" ; fi
1201
	if [ -n "${PBI_CVERSION}" ] ; then PBI_PROGVERSION="${PBI_CVERSION}" ; fi
1202
	if [ -n "${PBI_CWEB}" ] ; then PBI_PROGWEB="${PBI_CWEB}" ; fi
1203
	if [ -n "${PBI_CAUTHOR}" ] ; then PBI_PROGAUTHOR="${PBI_CAUTHOR}" ; fi
1204
	if [ -n "${PBI_CICON}" ] ; then PBI_PROGICON="${PBI_CICON}" ; fi
1205
}
1206

    
1207
# Parse the command line
1208
parse_make_pbi_cmdline() {
1209
        while [ $# -gt 0 ]; do
1210
                case "$1" in
1211
                -B)	PBI_BUILDONLY="YES"
1212
                        ;;
1213
                -c)
1214
                        if [ $# -eq 1 ]; then usage_make_pbi; fi
1215
                        if [ -n "${PBI_CONFDIR}" ]; then usage_make_pbi; fi
1216
                        shift
1217
			get_abspath "$1"
1218
			PBI_CONFDIR="$_ABSPATH"
1219
                        ;;
1220
                -d)
1221
                        if [ $# -eq 1 ]; then usage_make_pbi; fi
1222
                        shift; PORTSDIR="$1" ; export PORTSDIR
1223
                        ;;
1224

    
1225
                -32)    if [ "$REALARCH" != "amd64" -a "`basename $0`" != "pbi_makeport_chroot" ] ; then 
1226
				exit_err "-32 can only be used on amd64 host"
1227
			fi	
1228
			ARCH=i386
1229
                        ;;
1230

    
1231
                -k)	PBI_KEEPBUILDFILES="YES"
1232
                        ;;
1233

    
1234
                --delbuild)	MKDELBUILD="YES"
1235
                        ;;
1236
                --no-prune)	PBI_PRUNEBUILDPORTS="NO"
1237
                        ;;
1238
                --mkdebug)	MKDEBUG="YES"
1239
                        ;;
1240
                --pkgbuild)	PBI_PKGNGBUILD="YES"
1241
                        ;;
1242
                --tmpfs)	MKTMPFS="YES"
1243
                        ;;
1244
               --meta)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1245
                        shift; PBI_CREATE_USERMETA="$1"
1246

    
1247
			# If running the chroot portion, reset the location
1248
			if [ "`basename $0`" = "pbi_makeport_chroot" ] ; then
1249
				PBI_CREATE_USERMETA="/user-meta"
1250
			fi
1251

    
1252
			# Check to ensure it exists
1253
			if [ ! -e "$PBI_CREATE_USERMETA" ] ; then
1254
				exit_err "No such file: $PBI_CREATE_USERMETA"
1255
			fi
1256
                        ;;
1257
                -o)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1258
                        shift
1259
			get_abspath "$1"
1260
			PBI_CREATE_OUTDIR="$_ABSPATH"
1261
                        ;;
1262
                -p)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1263
                        if [ -n "${PBI_MAKEPREFIX}" ]; then usage_make_pbi; fi
1264
                        shift; PBI_MAKEPREFIX="$1"
1265
                        ;;
1266
            --sign)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1267
			shift
1268
			get_abspath "$1"
1269
			PBI_SSLPRIVKEY="$_ABSPATH"
1270
                        ;;
1271
                 *)
1272
                        if [ $# -gt 1 ]; then usage_make_pbi; fi
1273
                        PBI_MAKEPORT="$1"
1274
                        ;;
1275
                esac
1276
                shift
1277
        done
1278

    
1279
	# Override some locations if working in chroot environment
1280
	if [ "`basename $0`" = "pbi_makeport_chroot" ] ; then 
1281
		if [ -n "${PBI_CONFDIR}" ] ; then PBI_CONFDIR="/pbimodule" ; fi
1282
		if [ -n "${PBI_SSLPRIVKEY}" ] ; then PBI_SSLPRIVKEY="/privkey.pem" ; fi
1283
		if [ -n "${PBI_CREATE_OUTDIR}" ] ; then PBI_CREATE_OUTDIR="/pbiout" ; fi
1284
		if [ -n "${PORTSDIR}" ] ; then PORTSDIR="/usr/ports" ; fi
1285
	fi
1286

    
1287

    
1288
	# Make sure this port exists
1289
	if [ ! -d "${PORTSDIR}/${PBI_MAKEPORT}" -a "$PBI_PKGNGBUILD" != "YES" ] ; then
1290
		exit_err "No port (${PORTSDIR}/${PBI_MAKEPORT})"
1291
	fi
1292

    
1293
	# Remove any trailing '/' from PBI_MAKEPORT
1294
	echo $PBI_MAKEPORT | grep -q "/$"
1295
	if [ $? -eq 0 ] ; then
1296
		PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
1297
	fi
1298

    
1299
	# Make sure we have a valid PBI_CONFDIR
1300
	if [ -n "${PBI_CONFDIR}" -a ! -d "${PBI_CONFDIR}" ] ; then
1301
		exit_err "Invalid confdir (${PBI_CONFDIR})"
1302
	fi
1303

    
1304
	# Source the config file
1305
	if [ -n "${PBI_CONFDIR}" ]; then load_pbi_conffile ; fi
1306

    
1307
        if [ -z "${PBI_MAKEPORT}" ]; then
1308
                usage_make_pbi
1309
        fi
1310
}
1311

    
1312
# Parse the update command line
1313
parse_update_pbi_cmdline() {
1314
        while [ $# -gt 0 ]; do
1315
                case "$1" in
1316
                -c)	PBI_UPCHECK="YES" ;; 
1317
       --check-all)	PBI_UPCHECK="ALL" ;; 
1318
    --disable-auto)	PBI_UPENABLEAUTO="NO" ;; 
1319
     --enable-auto)	PBI_UPENABLEAUTO="YES" ;; 
1320
      --update-all)	PBI_UPDATEAPP="ALL" ;; 
1321
                 *)     if [ $# -gt 1 ]; then usage_update_pbi; fi
1322
			if [ -n "$PBI_UPDATEAPP" ] ; then usage_update_pbi ; fi
1323
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
1324
				find_pbi_namematch "$1"
1325
				if [ -z "$PBI_NAMEMATCH" ] ; then
1326
                               		exit_err "can't find installed pbi (${1})"
1327
				fi
1328
                        	PBI_UPDATEAPP="$PBI_NAMEMATCH"
1329
			else
1330
                        	PBI_UPDATEAPP="$1"
1331
                        fi
1332
                        ;;
1333
                esac
1334
                shift
1335
        done
1336

    
1337
	if [ "${PBI_UPDATEAPP}" = "ALL" -a -n "${PBI_UPCHECK}" ] ; then
1338
                usage_update_pbi
1339
        fi
1340

    
1341
	# Make sure we aren't trying to enable auto-updating for ALL
1342
	if [ "${PBI_UPDATEAPP}" = "ALL" -a -n "${PBI_UPENABLEAUTO}" ] ; then
1343
                usage_update_pbi
1344
        fi
1345
	if [ -z "${PBI_UPDATEAPP}" -a -n "${PBI_UPENABLEAUTO}" ] ; then
1346
                usage_update_pbi
1347
        fi
1348

    
1349
        if [ -z "${PBI_UPDATEAPP}" -a "${PBI_UPCHECK}" != "ALL" ]; then
1350
                usage_update_pbi
1351
        fi
1352
}
1353

    
1354
# Make some of our required PBI dirs
1355
mk_required_dirs() {
1356
	if [ ! -d "${PBI_APPDIR}" ] ; then mkdir -p ${PBI_APPDIR} >/dev/null 2>/dev/null ; fi
1357
	if [ ! -d "${PBI_XDGCFGDIR}" ] ; then mkdir -p ${PBI_XDGCFGDIR} >/dev/null 2>/dev/null ; fi
1358
	if [ ! -d "${PBI_XDGAPPDIR}" ] ; then mkdir -p ${PBI_XDGAPPDIR} >/dev/null 2>/dev/null ; fi
1359
	if [ ! -d "${PBI_XDGDIRDIR}" ] ; then mkdir -p ${PBI_XDGDIRDIR} >/dev/null 2>/dev/null ; fi
1360
	if [ ! -d "${PBI_XDGICONDIR}" ] ; then mkdir -p ${PBI_XDGICONDIR} >/dev/null 2>/dev/null ; fi
1361
	if [ ! -d "${PBI_XDGMIMEDIR}" ] ; then mkdir -p ${PBI_XDGMIMEDIR} >/dev/null 2>/dev/null ; fi
1362
	if [ ! -d "${PBI_RCDIR}" ] ; then mkdir -p ${PBI_RCDIR} >/dev/null 2>/dev/null ; fi
1363
	if [ ! -d "${PBI_BINDIR}" ] ; then mkdir -p ${PBI_BINDIR} >/dev/null 2>/dev/null ; fi
1364
	if [ ! -d "${PBI_MANDIR}" ] ; then mkdir -p ${PBI_MANDIR} >/dev/null 2>/dev/null ; fi
1365
	if [ ! -d "${PBI_HASHDIR}" ] ; then mkdir -p ${PBI_HASHDIR} >/dev/null 2>/dev/null ; fi
1366
	if [ ! -d "${PBI_DBAPPDIR}" ] ; then mkdir -p ${PBI_DBAPPDIR} >/dev/null 2>/dev/null ; fi
1367
	if [ ! -d "${PBI_DBKEYDIR}" ] ; then mkdir -p ${PBI_DBKEYDIR} >/dev/null 2>/dev/null ; fi
1368
	if [ ! -d "${PBI_DBMIRRORDIR}" ] ; then mkdir -p ${PBI_DBMIRRORDIR} >/dev/null 2>/dev/null ; fi
1369
	if [ ! -d "${PBI_DBICONDIR}" ] ; then mkdir -p ${PBI_DBICONDIR} >/dev/null 2>/dev/null ; fi
1370
	if [ ! -d "${PBI_DBINDEXDIR}" ] ; then mkdir -p ${PBI_DBINDEXDIR} >/dev/null 2>/dev/null ; fi
1371
	if [ ! -d "${PBI_DBREPODIR}" ] ; then mkdir -p ${PBI_DBREPODIR} >/dev/null 2>/dev/null ; fi
1372
	if [ ! -d "${PBI_DBHASHQUEUEDIR}" ] ; then mkdir -p ${PBI_DBHASHQUEUEDIR} >/dev/null 2>/dev/null ; fi
1373

    
1374
	# Set the permissions for directories if we are running as root
1375
	if [ `id -u` != "0" ] ; then return ; fi
1376

    
1377
	for cDir in $PBI_APPDIR $PBI_DBAPPDIR $PBI_DBHASHQUEUEDIR $PBI_XDGCFGDIR $PBI_XDGAPPDIR $PBI_XDGDIRDIR $PBI_XDGICONDIR $PBI_XDGMIMEDIR
1378
	do	
1379
		chown root:${PBI_INSTALLGROUP} ${cDir}
1380
		chmod 775 ${cDir}
1381
	done
1382

    
1383
	# Make sure the hash-dirty file can be written to by all
1384
	touch ${PBI_DBDIRTYFILE}
1385
	chown root:${PBI_INSTALLGROUP} ${PBI_DBDIRTYFILE}
1386
	chmod 664 ${PBI_DBDIRTYFILE}
1387
}
1388

    
1389
# Get the absolute path of a dir, even a realative dir. 'realpath' doesn't work here
1390
get_abspath() {
1391
	D=`dirname "$1"`
1392
	B=`basename "$1"`
1393
	if [ "$D" = "/" ] ; then
1394
		_ABSPATH="/$B"
1395
	else
1396
		_ABSPATH="`cd \"$D\" 2>/dev/null && pwd || echo \"$D\"`/$B"
1397
	fi
1398
}
1399

    
1400

    
1401
# Initialize some vars
1402
init_vars() {
1403

    
1404
	# Set sys vars
1405
	REALARCH="`uname -m`"
1406
	ARCH="$REALARCH"
1407

    
1408
        # Where is pbi-manager installed?
1409
        PROGBASE=/usr/local
1410
	SYS_LOCALBASE=/usr/local
1411
	PBI_SHARE_DIR="${PROGBASE}/share/pbi-manager"
1412
	if [ -z "${PBI_APPDIR}" -o "`basename $0`" = "pbi_makeport_chroot" ] ; then
1413
		PBI_APPDIR="/usr/pbi"
1414
        fi
1415
	# Set the FreeBSD Major & Release
1416
  	FBSDREL=`uname -r | cut -d "-" -f 1-2`
1417
	FBSDMAJOR=`echo $FBSDREL | cut -d "-" -f 1 | cut -d '.' -f 1`
1418

    
1419
	PBI_WORLDCHROOT="${PBI_APPDIR}/.pbi-world-$ARCH"
1420
	if [ `id -u` = "0" ] ; then 
1421
		PBI_HASHDIR="${PBI_APPDIR}/.hashdir"
1422
	else
1423
		PBI_HASHDIR="${PBI_APPDIR}/.hashdir-`whoami`"
1424
	fi
1425
	PBI_AB_BUILDERS=1
1426
	PBI_XDGCFGDIR="${PBI_APPDIR}/etc/xdg/menus"
1427
	PBI_XDGAPPDIR="${PBI_APPDIR}/share/applications"
1428
	PBI_XDGDIRDIR="${PBI_APPDIR}/share/desktop-directories"
1429
	PBI_XDGICONDIR="${PBI_APPDIR}/share/icons/hicolor"
1430
	PBI_XDGMIMEDIR="${PBI_APPDIR}/share/mime/packages"
1431
	PBI_RCDIR="${PBI_APPDIR}/rc.d"
1432
	PBI_BINDIR="${PBI_APPDIR}/bin"
1433
	PBI_MANDIR="${PBI_APPDIR}/man"
1434
	PBI_ETCCONF="${SYS_LOCALBASE}/etc/pbi.conf"
1435
	PCBSD_ETCCONF="${SYS_LOCALBASE}/etc/pcbsd.conf"
1436
	PBI_DEFAULT_ICON="${PROGBASE}/share/pbi-manager/icons/default.png"
1437
	PBI_DEFAULT_ICON_CHROOT="/default.png"
1438
	PBI_PATCH_ICON="${PROGBASE}/share/pbi-manager/icons/patch.png"
1439
	PBI_LDCONFIGFILE="${PROGBASE}/etc/ldpbiconfig"
1440
	PBI_LDCONFIGRC="${PROGBASE}/etc/rc.d/ldpbiconfig"
1441

    
1442
	# Set the PBI DB dir
1443
	if [ -z "${PBI_DBDIR}" ] ; then
1444
		PBI_DBDIR="/var/db/pbi"
1445
	fi
1446
	PBI_DBKEYDIR="${PBI_DBDIR}/keys"
1447
	PROGVERSION="1.0"
1448

    
1449
	# Load the etc/pbi.conf file
1450
	load_pbi_etcconf
1451

    
1452
	# Overrides from pbi.conf
1453
	if [ -z "$PBIDSLEEP" ] ; then
1454
		PBIDSLEEP="300"	# Amount of time to sleep before waking up pbid
1455
	fi
1456
	if [ -z "$PBI_INDEXREFRESH" ] ; then
1457
		PBI_INDEXREFRESH="24" # Hours to wait until we re-download PBI indexes
1458
	fi
1459
	if [ -n "$PBI_MAJORVERSION" ] ; then
1460
		FBSDMAJOR=${PBI_FBSDMAJOR}
1461
	fi
1462

    
1463
	PBI_LOG_LINES="500"
1464
	PBI_INSTALLGROUP="operator"
1465

    
1466
	# What dirs do we build hash-lists of
1467
	HASH_SEARCH_DIRS="lib share include info man"
1468

    
1469
	# What dbus dirs do we parse for setting up services
1470
	DBUS_SEARCH_DIRS="share/dbus-1 kde4/share/dbus-1 gnome/share/dbus-1"
1471

    
1472
	# Don't modify unless you know what your doing!
1473
	MOD_PREINS="pre-install.sh"
1474
	MOD_POSTINS="post-install.sh"
1475
	MOD_PREREM="pre-remove.sh"
1476
	MOD_XDGDESK_DIR="xdg-desktop"
1477
	MOD_XDGMENU_DIR="xdg-menu"
1478
	MOD_XDGMIME_DIR="xdg-mime"
1479
	MOD_EXTLINKFILE="external-links"
1480
	MOD_AUTOEXTLINKFILE=".auto-external-links"
1481
	PBI_ADD_GUIDISPLAY="NO"
1482
	PBI_ADD_INFODISPLAY="NO"
1483
	PBI_ADD_METADISPLAY="NO"
1484
	PBI_ADD_LICDISPLAY="NO"
1485
	PBI_APPDESK_DIR=".${MOD_XDGDESK_DIR}"
1486
	PBI_APPMENU_DIR=".${MOD_XDGMENU_DIR}"
1487
	PBI_APPMIME_DIR=".${MOD_XDGMIME_DIR}"
1488
	PBI_BUILD_USERS=""
1489
	PBI_BUILD_GROUPS=""
1490
	PBI_INS_USERSFILE=".pbi-uids"
1491
	PBI_INS_GROUPSFILE=".pbi-gids"
1492
	PBI_DESKADD="NO"
1493
	PBI_MENUADD="NO"
1494
	PBI_MIMEADD="NO"
1495
	PBI_PATHADD="NO"
1496
	PBI_DESKDEL="NO"
1497
	PBI_MAKECONF="/etc/pbi-make.conf"
1498
	PBI_MENUDEL="NO"
1499
	PBI_MIMEDEL="NO"
1500
	PBI_PATHDEL="NO"
1501
	PBI_DELETENAME=""
1502
	PBI_FAKEBIN_DIR="bin"
1503
	PBI_FAKERC_DIR="rc.d"
1504
	PBI_FILENAME=""
1505
	PBI_FORCEADD="NO"
1506
	PBI_HASHLIST=".pbi-hash-list"
1507
	PBI_INDEXUPFILE="pbi-index-$FBSDMAJOR"
1508
	PBI_METAUPFILE="pbi-meta-$FBSDMAJOR"
1509
	PBI_INFONAME=""
1510
	PBI_INS_DESKSCRIPT="install-desktop-icons.sh"
1511
	PBI_INS_MENUSCRIPT="install-menu-icons.sh"
1512
	PBI_INS_MIMESCRIPT="install-mime.sh"
1513
	PBI_INS_PATHSCRIPT="install-pathlinks.sh"
1514
	PBI_ICDIR="pbi-shared-icons"
1515
	PBI_LISTREPO_UP=""
1516
	PBI_LISTREPO_DOWN=""
1517
	PBI_LISTREPO_MIRROR=""
1518
	PBI_LICAGREE="NO"
1519
	PBI_LICENSEFILE="LICENSE"
1520
	PBI_USERMETAFILE="metafile"
1521
	PBI_PATCHVERSION=""
1522
	PBI_PATCHTARGET=""
1523
	PBI_REMOTEFETCH=""
1524
	PBI_REMOTEFETCHONLY=""
1525
	PBI_RESOURCE_DIR="resources"
1526
	PBI_SS_ICON="__PBI_ICON__"
1527
	PBI_SS_ARCHIVE="__PBI_ARCHIVE__"
1528
	PBI_SSLPRIVKEY=""
1529
	PBI_TMPDIR="/tmp/.PBI.$$"
1530
	PBI_TMPHASHLIST=""
1531
	PBI_UPCHECK=""
1532
	PBI_UPDATEAPP=""
1533
	PBI_UNINS_DESKSCRIPT="uninstall-desktop-icons.sh"
1534
	PBI_UNINS_MENUSCRIPT="uninstall-menu-icons.sh"
1535
	PBI_UNINS_MIMESCRIPT="uninstall-mime.sh"
1536
	PBI_UNINS_PATHSCRIPT="uninstall-pathlinks.sh"
1537

    
1538
        # User overridable variables
1539
	MKDELBUILD=""
1540
	MKDEBUG=""
1541
	MKTMPFS=""
1542
	PBI_AB_ARCHIVENUM=""
1543
	PBI_AB_CONFDIR=""
1544
	PBI_AB_GENPATCH="NO"
1545
	PBI_AB_HELPS=""
1546
	PBI_AB_OUTDIR=""
1547
	PBI_AB_SSLPRIVKEY=""
1548
	PBI_AB_PRUNE=""
1549
	PBI_AB_TMPFS=""
1550
	PBI_BUILDONLY="NO"
1551
	PBI_CAUTHOR=""
1552
	PBI_CBACKUP=""
1553
	PBI_CBACKUPTARGET=""
1554
	PBI_CHECKSCRIPTS=""
1555
	PBI_CICON=""
1556
	PBI_CNAME=""
1557
        PBI_CONFDIR=""
1558
	PBI_CONFFILE="pbi.conf"
1559
        PBI_CONF_SCRIPTSDIR="scripts/"
1560
	PBI_CREATE_OUTDIR="$HOME"
1561
	PBI_CREATE_HASHLIST="YES"
1562
	PBI_CUPDATE=""
1563
	PBI_CWEB=""
1564
	PBI_DBAPPDIR="${PBI_DBDIR}/installed"
1565
	PBI_DBDIRTYFILE="${PBI_DBDIR}/.hashdirty"
1566
	PBI_DBHASHQUEUEDIR="${PBI_DBDIR}/.hashqueue"
1567
	PBI_DBICONDIR="${PBI_DBDIR}/repo-icons"
1568
	PBI_DBINDEXDIR="${PBI_DBDIR}/index"
1569
	PBI_DBMIRRORDIR="${PBI_DBDIR}/mirrors"
1570
	PBI_DBREPODIR="${PBI_DBDIR}/repos"
1571
	PBI_DISABLEHASHDIR="NO"
1572
	PBI_GUITOPBANNER="gui_banner.png"
1573
	PBI_GUISIDEBANNER="gui_sidebanner.png"
1574
	PBI_KEEPBUILDFILES="NO"
1575
	PBI_MAKEPORT=""
1576
	PBI_MAKEPREFIX=""
1577
	PBI_MAKEOPTS=""
1578
	PBI_MKPORTBEFORE=""
1579
	PBI_MKPORTAFTER=""
1580
	PBI_PORTSDIR=""
1581
	PBI_PROGAUTHOR=""
1582
	PBI_PROGMDATE=""
1583
	PBI_PROGEPOCH=""
1584
	PBI_PROGNAME=""
1585
	PBI_PROGDIRNAME=""
1586
	PBI_PROGDIRPATH=""
1587
	PBI_PROGICON=""
1588
	PBI_PROGREVISION=""
1589
	PBI_PROGVERSION=""
1590
	PBI_PROGWEB=""
1591
	PBI_PRUNEBUILDPORTS="YES"
1592
	PBI_SKIPCHECKSUM=""
1593
	PBI_SKIPSIGVERIFY=""
1594
	PBI_USESYSGL="YES"
1595
	PBI_USESYSFONTS="YES"
1596
	PBI_VERBOSE="NO"
1597
	PORTSDIR="/usr/ports"
1598

    
1599
}
1600

    
1601
detect_pkgng()
1602
{
1603
        export PKG_ADD="pkg add"
1604
        export PKG_DELETE="pkg delete -y -f"
1605
}
1606

    
1607
# Set and export vars used by module scripts
1608
export_script_vars() {
1609
	# Load some initial values
1610
	get_pbi_progdir
1611
	get_pbi_progversion
1612

    
1613
	export PBI_PROGNAME PBI_PROGDIRNAME PBI_PROGDIRPATH PBI_PROGVERSION PBI_RCDIR PBI_MANDIR PBI_BINDIR
1614
	export SYS_LOCALBASE PBI_FAKEBIN_DIR PBI_FAKERC_DIR
1615
}
1616

    
1617
# init tmpdir
1618
init_tmpdir() {
1619
	if [ -d "${PBI_TMPDIR}" ] ; then return; fi
1620
	if [ -z "${PBI_TMPDIR}" ] ; then return ; fi
1621
	if [ "${PBI_TMPDIR}" = "/" ] ; then return ; fi
1622
	if [ -e "${PBI_TMPDIR}" ] ; then rm -rf "${PBI_TMPDIR}" ; fi
1623
	mkdir -p "${PBI_TMPDIR}"
1624
}
1625

    
1626
# rm tmpdir
1627
rm_tmpdir() {
1628
	if [ -z "${PBI_TMPDIR}" -o "${PBI_TMPDIR}" = "/" ] ; then return 0; fi
1629
	if [ -e "${PBI_TMPDIR}" ] ; then rm -rf "${PBI_TMPDIR}" ; fi
1630
}
1631

    
1632
# rm tmpdir
1633
rm_buildfiles() {
1634
	if [ "${PBI_KEEPBUILDFILES}" = "YES" ] ; then return ; fi
1635
	if [ -z "$PBI_CHROOTDIR" ] ; then return ; fi
1636
	chroot_make_cleanup
1637
}
1638

    
1639
# Load PBI conf options
1640
load_pbi_conffile() {
1641
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
1642
  	if [ -e "${PBI_CONFDIR}/${PBI_CONFFILE}" ] ; then
1643
		unset PBI_MAKEPORT PBI_BUILDKEY PBI_REQUIRESROOT PBI_PROGNAME PBI_PROGWEB PBI_PROGAUTHOR PBI_PROGICON PBI_MKPORTBEFORE PBI_MKPORTAFTER PBI_MAKEOPTS PBI_EXCLUDELIST PBI_AB_PRIORITY PBI_HASH_EXCLUDES PBI_AB_NOTMPFS PBI_PROGREVISION PBI_PROGREVISION PBI_AB_NOPKGBUILD
1644
		. ${PBI_CONFDIR}/${PBI_CONFFILE}
1645

    
1646
		# Remove any trailing '/' from PBI_MAKEPORT
1647
		echo $PBI_MAKEPORT | grep -q "/$"
1648
		if [ $? -eq 0 ] ; then
1649
			PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
1650
		fi
1651
	fi
1652
}
1653

    
1654
# Get the PBI_PROGVERSION
1655
get_pbi_progversion() {
1656

    
1657
	if [ -n "${PBI_PROGVERSION}" ] ; then return 0 ; fi
1658

    
1659
	load_pbi_conffile
1660

    
1661
	# If we have PBI_PROGVERSION now set
1662
	if [ -n "${PBI_PROGVERSION}" ] ; then return 0 ; fi
1663

    
1664
  	# Remove any trailing '/'
1665
  	echo $PBI_MAKEPORT | grep -q "/$"
1666
  	if [ $? -eq 0 ] ; then
1667
     		PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
1668
  	fi
1669

    
1670
	# Check first if we have this pkg in PKGNG
1671
	if [ -n "$PBI_PKGNGBUILD" -a -z "$PBI_AB_NOPKGBUILD" ] ; then
1672
		testPkgVer="`pkg-static rquery '%v' ${PBI_MAKEPORT}`"
1673
		if [ -n "$testPkgVer" ] ; then
1674
			PBI_PROGVERSION="$testPkgVer"
1675
			# If we have a REVISION, use it as well
1676
			if [ -n "$PBI_PROGREVISION" ] ; then
1677
				PBI_PROGVERSION="${PBI_PROGVERSION}_${PBI_PROGREVISION}"
1678
			fi
1679
			export PBI_PROGVERSION
1680
			return 0
1681
		fi
1682
		exit_err "Failed to get PBI_PROGVERSION for ${PBI_MAKEPORT}"
1683
	fi
1684

    
1685
	# Get the version from ports
1686
	if [ -z "${PBI_PROGVERSION}" -a -n "${PORTSDIR}" -a -n "${PBI_MAKEPORT}" ] ; then
1687
		PORTVER="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V DISTVERSION PORTSDIR=${PORTSDIR} 2>/dev/null`"
1688

    
1689
  		# Check if we have a portrevision to use in version number
1690
  		PORTREV=""
1691
  		PORTREV="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PORTREVISION PORTSDIR=${PORTSDIR} 2>/dev/null`"
1692
  		if [ -n "${PORTREV}" -a "${PORTREV}" != "0" ]
1693
 		then
1694
			PBI_PROGVERSION="${PORTVER}_${PORTREV}"
1695
		else
1696
			PBI_PROGVERSION="${PORTVER}"
1697
		fi
1698

    
1699
		if [ -z "${PBI_PROGVERSION}" ] ; then
1700
			echo "Warning: Unable to set PBI_PROGVERSION with:"
1701
		        echo "make -C ${PORTSDIR}/${PBI_MAKEPORT} -V DISTVERSION PORTSDIR=${PORTSDIR}"
1702
		fi
1703
	else
1704
		echo "PBI_PROGVERSION - $PBI_PROGVERSION - PORTSDIR - ${PORTSDIR} - $PBI_MAKEPORT - $PBI_MAKE_PORT - pbi - $pbi"
1705
		exit_err "Failed to locate PBI_PROGVERSION"
1706
	fi
1707

    
1708
	# If we have a REVISION, use it as well
1709
	if [ -n "$PBI_PROGREVISION" ] ; then
1710
		PBI_PROGVERSION="${PBI_PROGVERSION}_${PBI_PROGREVISION}"
1711
	fi
1712
}
1713

    
1714

    
1715
# Get the PBI_PROGNAME
1716
get_pbi_progname() {
1717
	if [ -z "${PBI_PROGNAME}" -o "${PBI_PROGNAME}" = " " ] ; then
1718
		load_pbi_conffile
1719
	else
1720
		return 0
1721
	fi
1722

    
1723
	if [ -z "${PBI_PROGNAME}" -a -n "${PORTSDIR}" -a -n "${PBI_MAKEPORT}" ] ; then
1724
		# Get the proper package name from the prefix + name + suffix
1725
		local pkgPrefix="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PKGNAMEPREFIX PORTSDIR=${PORTSDIR}`"
1726
		local pkgName="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PORTNAME PORTSDIR=${PORTSDIR}`"
1727
		local pkgSuffix="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PKGNAMESUFFIX PORTSDIR=${PORTSDIR}`"
1728
		PBI_PROGNAME="${pkgPrefix}${pkgName}${pkgSuffix}"
1729
	else
1730
		exit_err "Failed to locate PBI_PROGNAME"
1731
	fi
1732
}
1733

    
1734
# Get the PBI PROGDIR Name
1735
get_pbi_progdir() {
1736
	if [ -z "${PBI_PROGNAME}" ] ; then
1737
		get_pbi_progname
1738
	fi
1739

    
1740
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]' | sed 's|+||g'`"
1741
	if [ -z "${PBI_PROGDIRNAME}" ] ; then
1742
		PBI_PROGDIRNAME="${tmp}-${ARCH}"
1743
	fi
1744
	if [ -z "${PBI_PROGDIRPATH}" ] ; then
1745
		PBI_PROGDIRPATH="${PBI_APPDIR}/${PBI_PROGDIRNAME}"
1746
	fi
1747
}
1748

    
1749
# Helper function to exit after a error, and do some cleanup
1750
exit_err() {
1751
	echo -e "`basename ${0}`: ${1}"
1752
	rm_tmpdir
1753
	rm_buildfiles
1754
	rm_pbipatchfiles
1755
	chroot_make_cleanup
1756
	clean_remote_dl
1757
	exit 255
1758
}
1759

    
1760
# Check if we need to cleanup patch files
1761
rm_pbipatchfiles() {
1762
	if [ -z "${_pbiNewDir}${_pbiOldDir}${_pbiPatchDir}" ] ; then
1763
		return
1764
	else
1765
		echo "Cleaning up patch data..."
1766
	fi
1767

    
1768
	# If we used tmpfs, unmount the dirs
1769
        if [ "$PBI_MP_TMPFS" = "YES" ] ; then
1770
		umount "${_pbiNewDir}" 2>/dev/null
1771
		umount "${_pbiOldDir}" 2>/dev/null
1772
		umount "${_pbiPatchDir}" 2>/dev/null
1773
	fi
1774

    
1775
	if [ -n "${_pbiNewDir}" -a -d "${_pbiNewDir}" -a "${_pbiNewDir}" != "/" ] ; then
1776
	 	rm -rf "${_pbiNewDir}" >/dev/null 2>/dev/null
1777
	 	chflags -R noschg "${_pbiNewDir}" >/dev/null 2>/dev/null
1778
	 	rm -rf "${_pbiNewDir}" >/dev/null 2>/dev/null
1779
	fi
1780
	if [ -n "${_pbiOldDir}" -a -d "${_pbiOldDir}" -a "${_pbiOldDir}" != "/" ] ; then
1781
	 	rm -rf "${_pbiOldDir}" >/dev/null 2>/dev/null
1782
	 	chflags -R noschg "${_pbiOldDir}" >/dev/null 2>/dev/null
1783
	 	rm -rf "${_pbiOldDir}" >/dev/null 2>/dev/null
1784
	fi
1785
	if [ -n "${_pbiPatchDir}" -a -d "${_pbiPatchDir}" -a "${_pbiPatchDir}" != "/" ] ; then
1786
	 	rm -rf "${_pbiPatchDir}" >/dev/null 2>/dev/null
1787
	 	chflags -R noschg "${_pbiPatchDir}" >/dev/null 2>/dev/null
1788
	 	rm -rf "${_pbiPatchDir}" >/dev/null 2>/dev/null
1789
	fi
1790
}
1791

    
1792
# Check if we need to delete a remotely dl'd file
1793
clean_remote_dl() {
1794
	# If this was a remote fetch, remove dl'd file
1795
	if [ "$PBI_REMOTEFETCH" = "YES" -a -n "$PBI_FILENAME" ]; then 
1796
		rm "$PBI_FILENAME" >/dev/null 2>/dev/null
1797
	fi
1798
}
1799

    
1800
# Set port make options from config
1801
set_make_options() {
1802

    
1803
	local MAKE_CONF="/etc/make.conf"
1804

    
1805
	echo "PACKAGE_BUILDING=yes" >> ${MAKE_CONF}
1806
	echo "BATCH=yes" >> ${MAKE_CONF}
1807
	echo "NO_IGNORE=yes" >> ${MAKE_CONF}
1808
	echo "WITH_PKGNG=yes" >> ${MAKE_CONF}
1809

    
1810
	echo "WRKDIRPREFIX=/usr/wrkdirprefix" >> ${MAKE_CONF}
1811
	echo "DEPENDS_CLEAN=YES" >> ${MAKE_CONF}
1812

    
1813
	if [ -n "$PBI_MAKEOPTS" ] ; then
1814
		# Check if we have custom make opts
1815
		echo "${PBI_MAKEOPTS}" >> ${MAKE_CONF}
1816
	fi
1817

    
1818
	if [ ! -d "/usr/local" ] ; then
1819
		mkdir -p /usr/local
1820
	fi 
1821

    
1822
	# Make sure ldconfig is primed
1823
	/etc/rc.d/ldconfig start
1824

    
1825
	if [ -z "$PBI_PKGNGBUILD" ] ; then
1826
		echo "Building pkgng..."
1827
		cd /usr/ports/ports-mgmt/pkg
1828
		make install clean
1829
		if [ $? -ne 0 ] ; then exit_err "Failed building pkgng!" ; fi 
1830
	fi
1831

    
1832
	# Check if using ccache directory
1833
	if [ -d "/.ccache" ] ; then
1834
		echo "Enabling ccache..."
1835
		cd /usr/ports/devel/ccache 
1836
		make install clean
1837
		if [ $? -eq 0 ] ; then
1838
			# Setup environment variables
1839
			CCACHE_PATH="/usr/bin:/usr/local/bin"
1840
			export CCACHE_PATH
1841
			CCACHE_DIR="/.ccache"
1842
			export CCACHE_DIR
1843
			PATH="/usr/local/libexec/ccache:${PATH}"
1844
			export PATH
1845

    
1846
			# Setup make configuration
1847
			echo ".if !defined(NO_CCACHE)" >> ${MAKE_CONF}
1848
			echo "  CC=/usr/local/libexec/ccache/world/cc" >> ${MAKE_CONF}
1849
			echo "  CXX=/usr/local/libexec/ccache/world/c++" >> ${MAKE_CONF}
1850
			echo ".endif" >> ${MAKE_CONF}
1851
		else
1852
			echo "Failed installing ccache! Continuing without it..."
1853
		fi
1854
	fi
1855

    
1856
	PATH="${PATH}:/usr/local/bin:/usr/local/sbin"
1857
	export PATH
1858

    
1859
	FORCE_PKG_REGISTER="Y"
1860
	export FORCE_PKG_REGISTER
1861

    
1862
}
1863

    
1864
# Confirm we are running as root
1865
require_root() {
1866
  if [ `id -u` != "0" ] ; then
1867
     exit_err "Must be run as root!"
1868
  fi 
1869
}
1870

    
1871
# Confirm we are running as root or the proper group for installation
1872
require_root_or_group() {
1873
  if [ `id -u` = "0" ] ; then return 0 ; fi 
1874
  touch ${PBI_APPDIR}/.ptest.$$ >/dev/null 2>/dev/null
1875
  if [ "$?" = "0" ] ; then 
1876
	rm ${PBI_APPDIR}/.ptest.$$ >/dev/null 2>/dev/null
1877
	return 0
1878
  fi
1879
  exit_err "Must be run as root or a member of the $PBI_INSTALLGROUP group!"
1880
}
1881

    
1882
# Function to get the username from a file
1883
get_username_from_file() {
1884
	if [ -f "${1}" ] ; then 
1885
		FILEUSER=`ls -al ${1} | awk '{print $3}'`
1886
		export FILEUSER
1887
		return 0
1888
	fi
1889
	if [ -d "${1}" ] ; then 
1890
		FILEUSER=`ls -al ${1} | grep -v "total" | head -n 1 | awk '{print $3}'`
1891
		export FILEUSER
1892
		return 0
1893
	fi
1894
	exit_err "Invalid file for usercheck!"
1895
}
1896

    
1897
# Start the make patch process
1898
pbi_makepatch_init() {
1899
  	require_root
1900
	init_tmpdir
1901
	parse_makepatch_pbi_cmdline "$@"
1902

    
1903
	# Create a new patch file from the two PBIs specified
1904
	make_pbi_patchfile "${PBI_FILENAME}" "${PBI_OLDFILENAME}" "${PBI_PATCHOUTDIR}"
1905
}
1906

    
1907
# Remove a repo from the DB
1908
pbi_deleterepo_init() {
1909
  	require_root
1910
	parse_deleterepo_pbi_cmdline "$@"
1911

    
1912
	delete_pbi_repo
1913
}
1914

    
1915
# Do the removal of a PBI repo
1916
delete_pbi_repo() {
1917
	# Make sure this repo exists
1918
	ls ${PBI_DBREPODIR}/${PBI_DELREPO_ID}.* >/dev/null 2>/dev/null
1919
	if [ "$?" != "0" ] ; then
1920
		exit_err "No such repo ID: ${PBI_DELREPO_ID}"
1921
	fi
1922
	
1923
	_md5=`ls ${PBI_DBREPODIR}/${PBI_DELREPO_ID}.* | sed "s|^${PBI_DBREPODIR}/${PBI_DELREPO_ID}.||g"`
1924
	if [ -e "${PBI_DBREPODIR}/${PBI_DELREPO_ID}.${_md5}" ] ; then
1925
		rm "${PBI_DBREPODIR}/${PBI_DELREPO_ID}.${_md5}"
1926
	else
1927
		echo "Warning: ${PBI_DELREPO_ID}.${_md5} does not exist in the database."
1928
	fi
1929
	if [ -e "${PBI_DBKEYDIR}/${_md5}.ssl" ] ; then
1930
		rm "${PBI_DBKEYDIR}/${_md5}.ssl"
1931
	else
1932
		echo "Warning: ${_md5}.ssl does not exist in the keys database."
1933
	fi
1934
	if [ -e "${PBI_DBMIRRORDIR}/${_md5}" ] ; then
1935
		rm "${PBI_DBMIRRORDIR}/${_md5}"
1936
	else
1937
		echo "Warning: ${_md5} does not exist in the mirror database."
1938
	fi
1939
	
1940
	# See if we need to remove a downloaded index file
1941
	if [ -e "${PBI_DBINDEXDIR}/${_md5}-index" ] ; then
1942
		rm "${PBI_DBINDEXDIR}/${_md5}-index"
1943
		rm "${PBI_DBINDEXDIR}/${_md5}-index.time"
1944
	fi
1945

    
1946
	# Make sure we renumber the repos
1947
	renumber_repos
1948

    
1949
	echo "Deleted Repository ${PBI_DELREPO_ID}."
1950

    
1951
}
1952

    
1953
# After deleting a repo, this can be run to renumber the IDs
1954
renumber_repos() {
1955
	_rNum="1"
1956
	for i in `ls ${PBI_DBREPODIR} | sort`
1957
	do
1958
		case `echo ${_rNum} | wc -m | tr -d ' '` in
1959
			2) _rNum="00${_rNum}" ;;
1960
			3) _rNum="0${_rNum}" ;;
1961
			*) ;;
1962
		esac
1963

    
1964
		_md5=`echo ${i} | cut -d '.' -f 2`
1965
		mv "${PBI_DBREPODIR}/${i}" "${PBI_DBREPODIR}/${_rNum}.${_md5}"
1966

    
1967
		_rNum=`expr ${_rNum} + 1`
1968
	done
1969
}
1970

    
1971
# Add a new repo to the db
1972
pbi_addrepo_init() {
1973
  	require_root
1974
	parse_addrepo_pbi_cmdline "$@"
1975

    
1976
	# Create a new repo file
1977
	add_pbi_repo
1978
}
1979

    
1980
# Extract the repo and add it to the DB
1981
add_pbi_repo() {
1982
	init_tmpdir
1983
	tar xf "${PBI_ADDREPO_FILE}" -C ${PBI_TMPDIR} >/dev/null 2>/dev/null
1984
	if [ "$?" != "0" ] ; then
1985
		exit_err "Failed to read ${PBI_ADDREPO_FILE}"
1986
	fi
1987
	if [ ! -f "${PBI_TMPDIR}/repokey.ssl" -o ! -f "${PBI_TMPDIR}/repo-url" -o ! -f "${PBI_TMPDIR}/repo-desc" -o ! -f "${PBI_TMPDIR}/repo-mirror" ] ; then
1988
		exit_err "Improperly packaged repo file!"
1989
	fi
1990

    
1991
	# Make sure we don't have a duplicate repo key
1992
	for tr in ${PBI_PUBKEYS}
1993
	do
1994
		diff -q ${tr} ${PBI_TMPDIR}/repokey.ssl >/dev/null 2>/dev/null
1995
		if [ "$?" = "0" ] ; then
1996
			exit_err "Repo with identical key already registered!"
1997
		fi
1998
	done
1999

    
2000
	# Figure out the next repo number
2001
	get_next_repo_num
2002

    
2003
	_md5=`md5 -q ${PBI_TMPDIR}/repo-url`
2004
	_url=`cat ${PBI_TMPDIR}/repo-url`
2005
	_desc=`cat ${PBI_TMPDIR}/repo-desc`
2006
	echo "URL: ${_url}" > ${PBI_DBREPODIR}/${_rNum}.${_md5}
2007
	echo "Desc: ${_desc}" >> ${PBI_DBREPODIR}/${_rNum}.${_md5}
2008
	cp ${PBI_TMPDIR}/repo-mirror ${PBI_DBMIRRORDIR}/${_md5}
2009
	cp "${PBI_TMPDIR}/repokey.ssl" "${PBI_DBKEYDIR}/${_md5}.ssl"
2010
	chmod 755 "${PBI_DBKEYDIR}/${_md5}.ssl"
2011
	
2012
	rm_tmpdir
2013

    
2014
	echo "Added new repo: \"${_desc}\" to the database."
2015

    
2016
}
2017

    
2018
# Function to do listing of installed repos, and return next available number
2019
get_next_repo_num() {
2020
	_rNum="0"
2021
	for i in `ls ${PBI_DBREPODIR} | sort`
2022
	do
2023
		_rNum=`expr ${_rNum} + 1`
2024
	done
2025

    
2026
	_rNum=`expr ${_rNum} + 1`
2027

    
2028
	case `echo ${_rNum} | wc -m | tr -d ' '` in
2029
		2) _rNum="00${_rNum}" ;;
2030
		3) _rNum="0${_rNum}" ;;
2031
		*) ;;
2032
	esac
2033

    
2034
	export _rNum
2035
}
2036

    
2037
# Start the make patch process
2038
pbi_makerepo_init() {
2039
  	require_root
2040
	parse_makerepo_pbi_cmdline "$@"
2041

    
2042
	# Create a new repo file
2043
	make_pbi_repo
2044
}
2045

    
2046
# Create the repo .rpo file
2047
make_pbi_repo() {
2048
	init_tmpdir
2049

    
2050
	mkdir ${PBI_TMPDIR}/.mkrepo
2051
	cp ${PBI_MKREPO_KEY} ${PBI_TMPDIR}/.mkrepo/repokey.ssl
2052
	echo "${PBI_MKREPO_URL}" >  ${PBI_TMPDIR}/.mkrepo/repo-url
2053
	echo "${PBI_MKREPO_DESC}" >  ${PBI_TMPDIR}/.mkrepo/repo-desc
2054
	echo "${PBI_MKREPO_MIRROR}" | sed 's|,|\
2055
|g' > ${PBI_TMPDIR}/.mkrepo/repo-mirror
2056

    
2057

    
2058
	tar czf ${PBI_MKREPO_OUTDIR}/pbi-repo.rpo -C ${PBI_TMPDIR}/.mkrepo . >/dev/null 2>/dev/null
2059
	echo "New PBI Repo created: ${PBI_MKREPO_OUTDIR}/pbi-repo.rpo"
2060

    
2061
	rm_tmpdir
2062
}
2063

    
2064
do_pbi_mt_syncpbi()
2065
{
2066
	# First load values from the target PBI
2067
	PBI_FILENAME="${PBI_MT_PBIFILE}"
2068
	load_info_from_header
2069

    
2070
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then 
2071
		PBI_MT_REQUIRESROOT="YES"
2072
	fi
2073

    
2074
	PBI_MT_MAINTAINER="${PBI_MAINTAINER}"
2075
	PBI_MT_ADDNAME="$PBI_PROGNAME"
2076
	PBI_MT_ADDDESC="`echo ${PBI_DESC} | sed 's|;||g' | sed 's|\"||g'`"
2077
	PBI_MT_ADDSHORTDESC="`echo ${PBI_SHORTDESC} | sed 's|;||g' | sed 's|\"||g'`"
2078
	PBI_MT_ADDTYPE="$PBI_PROGTYPE"
2079
	PBI_MT_ADDLIC="$PBI_LICENSE"
2080
	PBI_MT_ADDCAT="$PBI_CATEGORY"
2081
	PBI_MT_ADDAUTHOR="$PBI_PROGAUTHOR"
2082
	PBI_MT_ADDURL="$PBI_PROGWEB"
2083
	PBI_MT_ADDKEYWORDS="$PBI_TAGS"
2084
	if [ -n "$PBI_ICONURL" ] ; then
2085
		PBI_MT_ADDICON="$PBI_ICONURL"
2086
	else
2087
		PBI_MT_ADDICON="http://images.pbidir.com/progicons/generic.png"
2088
	fi
2089

    
2090
	do_pbi_mt_add_app
2091
}
2092

    
2093
# Init the metatool
2094
pbi_mt_init() {
2095
	parse_mt_pbi_cmdline "$@"
2096
	case $PBI_MT_MODE in
2097
	    SYNCPBI) do_pbi_mt_syncpbi ;;
2098
		ADD) if [ "$PBI_MT_TYPE" = "CAT" ] ; then
2099
			do_pbi_mt_add_cat
2100
		     else
2101
			do_pbi_mt_add_app
2102
		     fi ;;
2103
		REM) if [ "$PBI_MT_TYPE" = "CAT" ] ; then
2104
			do_pbi_mt_rem_cat "${PBI_MT_REMNAME}" "${PBI_MT_METAFILE}"
2105
		     else
2106
			do_pbi_mt_rem_app "${PBI_MT_REMNAME}" "${PBI_MT_METAFILE}"
2107
		     fi ;;
2108
		  *) ;;
2109
	esac
2110
}
2111

    
2112
do_pbi_mt_add_cat() {
2113
	init_tmpdir
2114

    
2115
	# Remove any duplicate name
2116
	do_pbi_mt_rem_cat "${PBI_MT_ADDNAME}" "${PBI_MT_METAFILE}"
2117

    
2118
	cp ${PBI_MT_METAFILE} ${PBI_TMPDIR}/.meta.$$
2119
	echo "Cat=${PBI_MT_ADDNAME};${PBI_MT_ADDICON};${PBI_MT_ADDDESC};" \
2120
	>> ${PBI_TMPDIR}/.meta.$$
2121
	sort ${PBI_TMPDIR}/.meta.$$ > "${PBI_MT_METAFILE}"
2122
	rm ${PBI_TMPDIR}/.meta.$$
2123
	
2124
}
2125

    
2126
do_pbi_mt_add_app() {
2127
	init_tmpdir
2128
	# Remove any duplicate name
2129
	do_pbi_mt_rem_app "${PBI_MT_ADDNAME}" "${PBI_MT_METAFILE}"
2130

    
2131
	local _date=`date '+%s'`
2132

    
2133
	cp ${PBI_MT_METAFILE} ${PBI_TMPDIR}/.meta.$$
2134
	echo "App=${PBI_MT_ADDNAME};${PBI_MT_ADDCAT};${PBI_MT_ADDICON};${PBI_MT_ADDAUTHOR};${PBI_MT_ADDURL};${PBI_MT_ADDLIC};${PBI_MT_ADDTYPE};${PBI_MT_ADDKEYWORDS};${PBI_MT_ADDDESC};$PBI_MT_REQUIRESROOT;${_date};${PBI_MT_MAINTAINER};${PBI_MT_ADDSHORTDESC};" \
2135
	>> ${PBI_TMPDIR}/.meta.$$
2136
	sort ${PBI_TMPDIR}/.meta.$$ > "${PBI_MT_METAFILE}"
2137
	rm ${PBI_TMPDIR}/.meta.$$
2138
}
2139

    
2140
do_pbi_mt_rem_cat() {
2141
	sed -i '' "\|^Cat=${1};|d" "${2}"
2142
}
2143

    
2144
do_pbi_mt_rem_app() {
2145
	sed -i '' "\|^App=${1};|d" "${2}"
2146
}
2147

    
2148
# Init the indextool
2149
pbi_it_init() {
2150
	parse_it_pbi_cmdline "$@"
2151
	case $PBI_IT_MODE in
2152
		ADD) do_pbi_it_add ;; 
2153
		REM) do_pbi_it_rem ;; 
2154
		  *) ;;
2155
	esac
2156
}
2157

    
2158
# Remove a target PBI from an index
2159
do_pbi_it_rem() {
2160
	init_tmpdir
2161
	_pbilow="`echo ${PBI_IT_REMNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2162

    
2163
	cat "${PBI_IT_REMINDEX}" | grep -v "^${_pbilow}:${PBI_IT_REMARCH}:${PBI_IT_REMVER}" \
2164
		> "${PBI_TMPDIR}/.indextmp"
2165
	sort ${PBI_TMPDIR}/.indextmp > "${PBI_IT_REMINDEX}"
2166

    
2167
	rm_tmpdir
2168
}
2169

    
2170
# Add a new PBI to the specified INDEX file
2171
do_pbi_it_add() {
2172
	init_tmpdir
2173

    
2174
	# First load values from the target PBI
2175
	PBI_FILENAME="$PBI_IT_ADDFILE"
2176
	load_info_from_header
2177

    
2178
	# Get the name in lower-case
2179
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2180
	
2181
	# Prune any old copies of this app from the index
2182
	prune_from_index "$_pbilow" "$PBI_APPARCH"
2183
	
2184
	# Prune any old copies of this app from the index
2185
	mark_current_active_index "$_pbilow" "$PBI_APPARCH"
2186

    
2187
	# Add the new index entry
2188
	add_to_index
2189
	rm_tmpdir
2190
}
2191

    
2192
# Mark any current versions of this PBI as active in the index
2193
mark_current_active_index() {
2194

    
2195
	while read iLine
2196
	do
2197
		echo "$iLine" | grep "^${1}:${2}:" >/dev/null 2>/dev/null
2198
		if [ "$?" != "0" ] ; then
2199
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
2200
			continue
2201
		fi
2202
	 	echo "$iLine" | sed 's|:current|:active|' >> ${PBI_TMPDIR}/.indextmp	
2203

    
2204
	done < $PBI_IT_ADDINDEX	
2205
	mv "${PBI_TMPDIR}/.indextmp" "${PBI_IT_ADDINDEX}"
2206
}
2207

    
2208
# Add the specified PBI to the index
2209
add_to_index() {
2210
	mv "${PBI_IT_ADDINDEX}" "${PBI_TMPDIR}/.indextmp"
2211
	local _date=`date '+%s'`
2212
	local _sha256=`sha256 -q ${PBI_FILENAME}`
2213
	local _psize=`du -k ${PBI_FILENAME} | cut -f 1`
2214
	echo "${_pbilow}:${PBI_APPARCH}:${PBI_PROGVERSION}:${_sha256}:${PBI_PROGMDATE}:${PBI_IT_ADDURL}:$_date:${PBI_IT_ADDBPVERS}:current:${_psize}:" >>"${PBI_TMPDIR}/.indextmp"
2215
	sort ${PBI_TMPDIR}/.indextmp > "${PBI_IT_ADDINDEX}"
2216
}
2217

    
2218

    
2219
# Remove a set number of PBIs from the index
2220
prune_from_index() {
2221
	if [ -z "$PBI_IT_ADDKEEP" ]; then return ; fi
2222

    
2223
	local found="0"
2224
	local added="0"
2225
	while read iLine
2226
	do
2227
		echo "$iLine" | grep "^${1}:${2}:" >/dev/null 2>/dev/null
2228
		if [ "$?" != "0" ] ; then
2229
			# Ready to add back the saved lines
2230
			if [ $found -ne 0 ] ; then
2231
				while read fLine
2232
				do
2233
				  if [ $found -le $PBI_IT_ADDKEEP ] ; then
2234
	 			     echo "$fLine" >> ${PBI_TMPDIR}/.indextmp	
2235
				  fi
2236
				  found=`expr $found - 1`
2237
				done < ${PBI_TMPDIR}/.foundtmp
2238
			fi
2239
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
2240
			continue
2241
		fi
2242
		found=`expr $found + 1`
2243
	 	echo "$iLine" >> ${PBI_TMPDIR}/.foundtmp	
2244
	done < $PBI_IT_ADDINDEX	
2245
	mv "${PBI_TMPDIR}/.indextmp" "${PBI_IT_ADDINDEX}"
2246
}
2247

    
2248
# Add a new repo to the db
2249
pbi_browser_init() {
2250
	parse_browse_pbi_cmdline "$@"
2251
	init_tmpdir
2252

    
2253
	# Check if we are doing a category listing, the default if no options
2254
	if [ "$PBI_BROWSE_LISTCATS" = "YES" -o -z "${PBI_BROWSE_LISTALLPBI}${PBI_BROWSE_CAT}${PBI_BROWSE_SEARCH}" ] ; then
2255
		pbi_browse_listcats
2256
	else
2257
		pbi_browse_listpbi
2258
	fi
2259

    
2260
}
2261

    
2262
# List PBIs from a repo
2263
pbi_browse_listpbi() {
2264
	_rArch=`uname -m`
2265

    
2266
	# Figure out which type of display we are doing
2267
	if [ -n "$PBI_BROWSE_LISTALLPBI" ] ; then
2268
		echo "Using RepoID: $PBI_BROWSE_RID"
2269
		echo "Listing all available PBIs"
2270
		grep -i -e "^App=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2271
	elif [ -n "$PBI_BROWSE_CAT" ] ; then
2272
		echo "Using RepoID: $PBI_BROWSE_RID"
2273
		echo "Available PBIs for Category: $PBI_BROWSE_CAT"
2274
		grep -i -e "^App=" -i -e ";${PBI_BROWSE_CAT};" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2275
	elif [ -n "$PBI_BROWSE_SEARCH" ] ; then
2276
		echo "Using RepoID: $PBI_BROWSE_RID"
2277
		echo "Searching for: $PBI_BROWSE_SEARCH"
2278
		grep -i -e "^App=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2279
	else
2280
		exit_err "No valid search variable set!"
2281
	fi
2282

    
2283
	while read app
2284
	do
2285
		line=`echo $app | sed 's|^App=||g'`
2286
		catCheck=`echo $line | cut -d ';' -f 2 2>/dev/null`
2287
		aName=`echo $line | cut -d ';' -f 1 2>/dev/null`
2288

    
2289
		# Make sure this is from the correct category
2290
		if [ -n "$PBI_BROWSE_CAT" ] ; then
2291
			_cCheck=`echo $catCheck | tr '[:lower:]' '[:upper:]'`
2292
			_cCheck2=`echo $PBI_BROWSE_CAT | tr '[:lower:]' '[:upper:]'`
2293
			if [ "$_cCheck" != "$_cCheck2" ]; then 
2294
			continue
2295
			fi
2296
		fi
2297

    
2298
		# Set the displayed arch type
2299
		aArch="$_rArch"
2300

    
2301
		# Make sure this application has an associated PBI available
2302
		check_pbi_update "$aName" "nodisplay" \
2303
		 "$aName" "current" \
2304
		 "$FBSDMAJOR" "$_rArch" "${PBI_BROWSE_RID}"
2305
		if [ "$?" != "0" ] ; then
2306
			# On amd64, see if 32bit version exists
2307
			if [ "$_rArch" = "amd64" ] ; then
2308
				check_pbi_update "$aName" "nodisplay" \
2309
		 		"$aName" "current" \
2310
		 		"$FBSDMAJOR" "i386" "${PBI_BROWSE_RID}"
2311
				if [ "$?" != "0" ] ; then 
2312
					continue
2313
				else
2314
					# Found a 32bit version of the app
2315
					aArch="i386"
2316
				fi
2317
			else
2318
				# Not on amd64, continue on
2319
				continue
2320
			fi
2321
		fi
2322

    
2323
		aIcon=`echo $line | cut -d ';' -f 3`
2324
		aAuthor=`echo $line | cut -d ';' -f 4`
2325
		aUrl=`echo $line | cut -d ';' -f 5`
2326
		aLic=`echo $line | cut -d ';' -f 6`
2327
		aType=`echo $line | cut -d ';' -f 7`
2328
		aKeywords=`echo $line | cut -d ';' -f 8`
2329
		aDesc=`echo $line | cut -d ';' -f 9`
2330
		aRoot=`echo $line | cut -d ';' -f 10`
2331

    
2332
		# Check for a translation to the description
2333
		get_meta_trans "App" "$cName" "${PBI_BROWSE_METAFILE}"
2334
		if [ -n "$MTRANS" ] ; then
2335
			aDesc="$MTRANS"
2336
		fi
2337

    
2338
		# Search the description / keywords
2339
		if [ -n "$PBI_BROWSE_SEARCH" ] ; then
2340
			echo "$aName,$aDesc,$aKeywords,$MTRANS" | grep -i "$PBI_BROWSE_SEARCH" >/dev/null 2>/dev/null
2341
			if [ "$?" != "0" ]; then continue ; fi
2342
		fi
2343

    
2344
		# Get the local icon file
2345
		ext=`echo $aIcon | sed 's/.*\.//'`
2346
		aIcon="${PBI_DBICONDIR}/${PBI_BROWSE_REPOMD5}-${aName}.${ext}"
2347

    
2348
		echo "------------------------------------"
2349
		echo "Application: $aName"
2350
		echo "Version: $PBI_UPNVER"
2351
		if [ -n "$PBI_UPSIZE" ] ; then
2352
			echo "Size: $PBI_UPSIZE"
2353
		fi
2354
		if [ -n "$PBI_BROWSE_LISTALLPBI" ] ; then
2355
			echo "Category: $catCheck"
2356
		fi
2357
		echo "Created: `echo $PBI_UPMDATE`"
2358
		if [ "$aRoot" = "YES" ] ; then
2359
			echo "RootInstall: YES"
2360
		else
2361
			echo "RootInstall: NO"
2362
		fi
2363
		echo "Arch: $aArch"
2364
		echo "Author: $aAuthor"
2365
		echo "URL: $aUrl"
2366
		echo "License: $aLic"
2367
		echo "Type: $aType"
2368
		echo "Keywords: $aKeywords"
2369
		echo "Icon: $aIcon"
2370
		echo "Description: $aDesc"
2371
		echo ""
2372
		if [ "$aRoot" = "YES" ] ; then
2373
			echo "To install this PBI (As Root):"
2374
		else
2375
			echo "To install this PBI:"
2376
		fi
2377
		echo "# pbi_add --rArch $aArch --repo $PBI_BROWSE_RID -r $aName"
2378
		echo ""
2379

    
2380
		
2381
	done < ${PBI_TMPDIR}/.meta.$$
2382

    
2383
}
2384

    
2385
# List available categories for this repository
2386
pbi_browse_listcats() {
2387

    
2388
	echo "Using RepoID: $PBI_BROWSE_RID"
2389
	echo "Available Categories:"
2390
	grep "^Cat=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2391
	while read cat
2392
	do
2393
		line=`echo $cat | sed 's|^Cat=||g'`
2394
		cName=`echo $line | cut -d ';' -f 1`
2395
		cIcon=`echo $line | cut -d ';' -f 2`
2396
		cDesc=`echo $line | cut -d ';' -f 3`
2397
		
2398
		# Check for a translation to the description
2399
		get_meta_trans "Cat" "$cName" "${PBI_BROWSE_METAFILE}"
2400
		if [ -n "$MTRANS" ] ; then
2401
			cDesc="$MTRANS"
2402
		fi
2403

    
2404
		# Get the local icon file
2405
		ext=`echo $cIcon | sed 's/.*\.//'`
2406
		cIcon="${PBI_DBICONDIR}/${PBI_BROWSE_REPOMD5}-${cName}.${ext}"
2407

    
2408
		echo "------------------------------------"
2409
		echo "Category: $cName"
2410
		echo "Icon: $cIcon"
2411
		echo "Description: $cDesc"
2412
		echo ""
2413

    
2414
	done < ${PBI_TMPDIR}/.meta.$$
2415

    
2416
	echo "To view available PBIs for a particular category:"
2417
	echo " % pbi_browser -c <category> <repoid>"
2418
}
2419

    
2420
# Function to check if we have a translated description
2421
get_meta_trans() {
2422
	local tag="$1"
2423
	local name="$2"
2424
	local metaFile="$3"
2425

    
2426
	# Check if we have a translation to overwrite with
2427
	MTRANS=""
2428
	if [ -z "$LANG" ] ; then return; fi
2429

    
2430
	lCheck="`echo $LANG | cut -d '_' -f 1` `echo $LANG | cut -d '.' -f 1`"
2431
	for l in $lCheck
2432
	do
2433
		catTrans=`grep "^${tag}\[$l\]=${name}" ${metaFile}`	
2434
		if [ -n "$catTrans" ] ; then
2435
			MTRANS=`echo $catTrans | cut -d ";" -f 2`
2436
			return
2437
		fi
2438
	done
2439
}
2440

    
2441
# List repos in the db
2442
pbi_listrepo_init() {
2443
  	require_root_or_group
2444
	parse_listrepo_pbi_cmdline "$@"
2445

    
2446
	# List the repos
2447
	if [ -z "$PBI_LISTREPO_ID" ] ; then
2448
		list_all_pbi_repo
2449
	else
2450
		if [ -n "${PBI_LISTREPO_UP}" ]; then
2451
			require_root
2452
			move_repo_up "${PBI_LISTREPO_ID}" 
2453
			list_all_pbi_repo
2454
		elif [ -n "${PBI_LISTREPO_DOWN}" ] ; then
2455
			require_root
2456
			move_repo_down "${PBI_LISTREPO_ID}"
2457
			list_all_pbi_repo
2458
		elif [ -n "${PBI_LISTREPO_MIRROR}" ] ; then
2459
			require_root
2460
			change_repo_mirror "${PBI_LISTREPO_ID}"
2461
			listrepo_details "${PBI_LISTREPO_ID}"
2462
		else
2463
			listrepo_details "${PBI_LISTREPO_ID}"
2464
		fi
2465
	fi
2466
}
2467

    
2468
# Function to change a specific repos mirror URL
2469
change_repo_mirror() {
2470
	local _rMd5=`ls ${PBI_DBREPODIR}/${1}.* | cut -d '.' -f 2`
2471
	echo "$PBI_LISTREPO_MIRROR" | sed 's|,|\
2472
|g' > "${PBI_DBMIRRORDIR}/${_rMd5}"
2473
}
2474

    
2475
# Move a repo down in priority
2476
move_repo_down() {
2477
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2478
	_uNum=`expr ${1} + 1`
2479

    
2480
	case `echo ${_uNum} | wc -m | tr -d ' '` in
2481
		2) _uNum="00${_uNum}" ;;
2482
		3) _uNum="0${_uNum}" ;;
2483
		*) ;;
2484
	esac
2485
	_uFile=`ls ${PBI_DBREPODIR}/${_uNum}.* 2>/dev/null`
2486
	if [ -z "$_uFile" ] ; then exit_err "This repo is already at the lowest priority!" ; fi
2487

    
2488
	_umd5=`echo $_uFile | cut -d '.' -f 2`
2489
	mv "${_uFile}" "${PBI_DBREPODIR}/${1}.${_umd5}"
2490
	_rmd5=`echo $_rFile | cut -d '.' -f 2`
2491
	mv "${_rFile}" "${PBI_DBREPODIR}/${_uNum}.${_rmd5}"
2492
}
2493

    
2494
# Move a repo up in priority
2495
move_repo_up() {
2496
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2497
	_uNum=`expr ${1} - 1`
2498

    
2499
	case `echo ${_uNum} | wc -m | tr -d ' '` in
2500
		2) _uNum="00${_uNum}" ;;
2501
		3) _uNum="0${_uNum}" ;;
2502
		*) ;;
2503
	esac
2504
	_uFile=`ls ${PBI_DBREPODIR}/${_uNum}.* 2>/dev/null`
2505
	if [ -z "$_uFile" ] ; then exit_err "This repo is already at the highest priority!" ; fi
2506

    
2507
	_umd5=`echo $_uFile | cut -d '.' -f 2`
2508
	mv "${_uFile}" "${PBI_DBREPODIR}/${1}.${_umd5}"
2509
	_rmd5=`echo $_rFile | cut -d '.' -f 2`
2510
	mv "${_rFile}" "${PBI_DBREPODIR}/${_uNum}.${_rmd5}"
2511
}
2512

    
2513
# List all PBI repos
2514
listrepo_details() {
2515
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2516
	_md5=`ls ${PBI_DBREPODIR}/${1}.* | cut -d '.' -f 2`
2517
	_desc=`cat ${_rFile} | grep "Desc: " | sed "s|Desc: ||g"` 
2518
	_url=`cat ${_rFile} | grep "URL: " | sed "s|URL: ||g"` 
2519
	_mirror=`cat ${PBI_DBMIRRORDIR}/$_md5` 
2520
	echo "Repo ID: ${1}"
2521
	echo "Description: ${_desc}"
2522
	echo "IndexURL: ${_url}"
2523
	echo "MD5: ${_md5}"
2524
	echo "LocalMeta: `ls ${PBI_DBINDEXDIR}/${_md5}*meta 2>/dev/null`"
2525
	echo "LocalIndex: `ls ${PBI_DBINDEXDIR}/${_md5}*index 2>/dev/null`"
2526
	echo "Mirror(s):"
2527
	echo "$_mirror"
2528
}
2529

    
2530
# List all PBI repos
2531
list_all_pbi_repo() {
2532
	echo "[ID]	[Description]"
2533
	echo "-----------------------------------------------------"
2534
	for repo in `ls ${PBI_DBREPODIR} | sort `
2535
	do
2536
		_id=`echo $repo | cut -d '.' -f 1`
2537
		_desc=`cat ${PBI_DBREPODIR}/${repo} | grep "Desc: " | sed "s|Desc: ||g"` 
2538
		echo "${_id}	${_desc}"
2539
	done
2540
}
2541

    
2542
# Start the patch process
2543
pbi_patch_init() {
2544
  	require_root_or_group
2545
	init_tmpdir
2546
	parse_patch_pbi_cmdline "$@"
2547

    
2548
	# Check if we are only displaying information
2549
	check_pbi_info_display
2550
	check_pbi_gui_display
2551
	check_pbi_scripts_display
2552
	check_pbi_license_display
2553
	if [ "$PBI_ADD_GUIDISPLAY" = "YES" -o "$PBI_ADD_INFODISPLAY" = "YES" -o "$PBI_CHECKSCRIPTS" = "YES" -o "${PBI_ADD_LICDISPLAY}" = "YES" -o "${PBI_ADD_METADISPLAY}" = "YES" ] 
2554
	then 
2555
		exit_trap
2556
	fi
2557

    
2558
	# Try to apply this patch file
2559
	do_pbi_patch
2560
}
2561

    
2562
# Start the PBI patch process
2563
do_pbi_patch() {
2564
	
2565
	# Verify the target PBI is installed
2566
	verify_pbi_update_target
2567

    
2568
        pbi_verify_signatures
2569
        pbi_verify_archivesum
2570
        
2571
	# Extract the archive contents
2572
        mk_pbi_extract_dir
2573
        pbi_extract_archive
2574

    
2575
	set_patch_wrkdir
2576

    
2577
	init_tmpdir
2578

    
2579
	# Run the uninstall script
2580
	if [ -e "${PBI_PATCHWRKDIR}/.sbin/.pbi-uninstall.sh" ] ; then
2581
		echo "Removing old xdg data..."
2582
		sh "${PBI_PATCHWRKDIR}/.sbin/.pbi-uninstall.sh"	>/dev/null 2>/dev/null
2583
	fi
2584

    
2585
	# Remove old files from the installed PBI
2586
	patch_rm_old_files
2587
	
2588
	# Extract the new files
2589
	patch_extract_new_files
2590

    
2591
	# Merge in the bsdiffs
2592
	patch_merge_bsdiffs
2593

    
2594
	# Make sure we have good permissions on this PBI
2595
	patch_apply_chmod
2596

    
2597
	# Run the install script
2598
	if [ -e "${PBI_PATCHWRKDIR}/.sbin/.pbi-install.sh" ] ; then
2599
		echo "Adding new xdg data..."
2600
		sh "${PBI_PATCHWRKDIR}/.sbin/.pbi-install.sh"	>/dev/null 2>/dev/null
2601
	fi
2602

    
2603
	# If running as user, add bin path-links
2604
	if [ "`id -u`" != "0" ] ; then add_app_path_links "${PBI_PATCHWRKDIR}" ; fi
2605

    
2606
	# Update the registered version of the PBI
2607
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2608
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2609
        newDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHVERSION}-${PBI_APPARCH}"
2610
	mv "$oldDir" "$newDir"
2611
	rm ${newDir}/*.sha1 >/dev/null 2>/dev/null
2612

    
2613
	# Register the app
2614
	pbi_add_register_app	
2615

    
2616
        # Check if we need to run a post-install.sh script again
2617
	if [ -e "${newDir}/${MOD_POSTINS}" ] ; then
2618
          export_script_vars
2619
          sh "${newDir}/${MOD_POSTINS}"
2620
        fi
2621

    
2622
	# Cleanup after our selves
2623
	if [ -d "$PBI_EXTRACTDIR" ] ; then
2624
		echo "Cleaning up..."
2625
		rm -rf "$PBI_EXTRACTDIR"
2626
	fi
2627

    
2628
	# Update the hashdir
2629
	add_hashdir_trigger
2630

    
2631
	# Mark the hash-dir as dirty as well
2632
	make_hashdir_dirty
2633

    
2634
	echo "Finished patching ${_pbilow}: $PBI_PATCHTARGET -> $PBI_PATCHVERSION"
2635
}
2636

    
2637
# Mark the hashdir as dirty
2638
make_hashdir_dirty() {
2639
	date "+%s" > "${PBI_DBDIRTYFILE}"
2640
}
2641

    
2642
# Do any chmod stuff after patching
2643
patch_apply_chmod()
2644
{
2645
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-permList" ] ; then return; fi
2646

    
2647
	cuDir=`pwd`
2648

    
2649
	cd "${PBI_PATCHWRKDIR}"
2650
	echo "Applying updated permissions..."
2651
	while read chLine
2652
	do
2653
		$chLine >/dev/null 2>/dev/null
2654
	done < "${PBI_EXTRACTDIR}/PBI-permList"
2655

    
2656
	cd "$cuDir"
2657
}
2658

    
2659
# Function which does the merge of bsdiff files
2660
patch_merge_bsdiffs()
2661
{
2662
	echo "Applying patch data..."
2663
	find ${PBI_EXTRACTDIR} | grep '.bsdiff' | sed "s|${PBI_EXTRACTDIR}/||g" > ${PBI_TMPDIR}/.PBI.bspatch.$$
2664

    
2665
	while read pLine
2666
	do
2667
		if [ -z "$pLine" ] ; then continue; fi
2668
		_tFile="`echo $pLine | sed 's|.bsdiff$||g'`"
2669
		
2670
		if [ ! -e "${PBI_EXTRACTDIR}/${_tFile}.sha256" ] ; then
2671
			exit_err "Missing checksums for \"${_tFile}\" this patch is corrupt"
2672
		fi
2673

    
2674
		if [ ! -e "${PBI_PATCHWRKDIR}/${_tFile}" ] ; then
2675
			echo "Warning: Missing target file for patching: $_tFile"
2676
			continue
2677
		fi
2678
		
2679
		# Make sure we really are trying to patch the same file
2680
		sha1="`sha256 -q ${PBI_PATCHWRKDIR}/${_tFile}`"
2681
		sha2="`cat ${PBI_EXTRACTDIR}/${_tFile}.sha256`"
2682
		if [ "$sha1" != "$sha2" ] ; then
2683
			exit_err "Error: Checksum failed for ${_tFile}, you may need to re-install this PBI."
2684
		fi
2685

    
2686
		_fPerm=`stat -f %Op "${PBI_PATCHWRKDIR}/${_tFile}"  | cut -c 3-6`
2687

    
2688
		# See if we have a hard-link to take care of first
2689
		get_hard_link_count "${PBI_PATCHWRKDIR}/${_tFile}"
2690
       	 	if [ "$HLINKS" != "1" ] ; then
2691
			mv "${PBI_PATCHWRKDIR}/${_tFile}" "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2692
			cp "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$" "${PBI_PATCHWRKDIR}/${_tFile}"
2693
			rm -f "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2694
        	fi
2695
		
2696
		# Now do the patching
2697
	 	#echo "Patching $_tFile"	
2698
		mv "${PBI_PATCHWRKDIR}/${_tFile}" "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2699
		bspatch "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$" \
2700
			"${PBI_PATCHWRKDIR}/${_tFile}" \
2701
			"${PBI_EXTRACTDIR}/$pLine" >/dev/null 2>/dev/null
2702
		if [ "$?" != "0" ] ; then
2703
			echo "Warning: Failed to apply patch to \"$_tFile\""
2704
		fi
2705

    
2706
		# Re-apply the same permissions to the new file
2707
		chmod $_fPerm "${PBI_PATCHWRKDIR}/${_tFile}"
2708

    
2709
		# Remove the old file
2710
		rm "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2711

    
2712
	done < "${PBI_TMPDIR}/.PBI.bspatch.$$"
2713

    
2714
	rm "${PBI_TMPDIR}/.PBI.bspatch.$$"
2715
}
2716

    
2717
# Function which does the new file extraction for this PBI
2718
patch_extract_new_files()
2719
{
2720
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-newFiles.tar" ] ; then return; fi
2721
	echo "Installing new files..."
2722
	tar xf "${PBI_EXTRACTDIR}/PBI-newFiles.tar" -C "${PBI_PATCHWRKDIR}" >/dev/null 2>/dev/null
2723
	if [ "$?" != "0" ] ; then
2724
		echo "Warning: Error during new file extraction, PBI may not function correctly."
2725
	fi
2726
}
2727

    
2728
# Function which removes files that no longer exist in this updated PBI
2729
patch_rm_old_files()
2730
{
2731
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-rmList" ] ; then return; fi
2732
	
2733
	echo "Removing old files..."
2734
	while read rmLine
2735
	do
2736
		if [ -z "$rmLine" ] ; then continue ; fi
2737
		if [ ! -e "${PBI_PATCHWRKDIR}/$rmLine" ] ; then
2738
			continue
2739
		fi
2740

    
2741
		rm -rf "${PBI_PATCHWRKDIR}/${rmLine}"
2742
	done < "${PBI_EXTRACTDIR}/PBI-rmList"
2743

    
2744
}
2745

    
2746
# Sets the workdir of the target PBI we are patching
2747
set_patch_wrkdir()
2748
{
2749
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2750
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2751

    
2752
	if [ ! -e "${oldDir}/pbi_defaultpath" ] ; then
2753
        	exit_err "Can not fild default path for \"$PBI_PROGNAME\"!"
2754
        fi
2755

    
2756
	PBI_PATCHWRKDIR="`cat ${oldDir}/pbi_defaultpath`"
2757

    
2758
	if [ ! -d "$PBI_PATCHWRKDIR" ] ; then
2759
        	exit_err "Path for \"$PBI_PROGNAME\" does not exist!"
2760
	fi
2761
}
2762

    
2763
# Confirms that the target PBI for this patch is installed
2764
# Exits if not and we are not doing a extract only
2765
verify_pbi_update_target()
2766
{
2767
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then return ; fi
2768
	
2769
	# Make sure the target PBI is installed
2770
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2771
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2772

    
2773
	if [ ! -e "${oldDir}" ] ; then
2774
        	exit_err "\"${_pbilow}\" does not appear to be installed!"
2775
        fi
2776

    
2777
	# Check the arch type
2778
	if [ "`cat ${oldDir}/pbi_arch`" != "$PBI_APPARCH" ] ; then
2779
     		exit_err "Installed \"${PBI_PROGNAME}\" is not compiled for $PBI_APPARCH"
2780
	fi
2781

    
2782
	# Check the taret version
2783
	if [ "`cat ${oldDir}/pbi_version`" != "$PBI_PATCHTARGET" ] ; then
2784
     		exit_err "\"${_pbilow}\" patch is for \"$PBI_PROGVERSION\" only!"
2785
	fi
2786

    
2787
	# Check the fbsd version
2788
	_pFbsdVer="`cat ${oldDir}/pbi_fbsdver | cut -c 1`"
2789
	_sFbsdVer="`echo $PBI_FBSDVER | cut -c 1`"
2790
	if [ "$_pFbsdVer" != "$_sFbsdVer" ] ; then
2791
     		exit_err "\"${_pbilow}\" patch is for FreeBSD ${_sFbsdVer}.X only!"
2792
	fi
2793

    
2794
	# Check the mdate of the pbi
2795
	_pMDate="`cat ${oldDir}/pbi_mdate`"
2796
	_sMDate="$PBI_PATCHMDATE"
2797
	if [ "$_pMDate" != "$_sMDate" ] ; then
2798
     		exit_err "\"${_pbilow}\" patch is for the $PBI_PATCHMDATE build!"
2799
	fi
2800
}
2801

    
2802
# Start the pbi_add process
2803
pbi_add_init() {
2804
	init_tmpdir
2805
	parse_add_pbi_cmdline "$@"
2806

    
2807

    
2808
	# Check if we are only displaying information
2809
	check_pbi_info_display
2810
	check_pbi_gui_display
2811
	check_pbi_scripts_display
2812
	check_pbi_license_display
2813
	check_pbi_meta_display
2814
	if [ "$PBI_ADD_GUIDISPLAY" = "YES" -o "$PBI_ADD_INFODISPLAY" = "YES" -o "$PBI_CHECKSCRIPTS" = "YES" -o "${PBI_ADD_LICDISPLAY}" = "YES" -o "${PBI_ADD_METADISPLAY}" = "YES" ] 
2815
	then 
2816
		clean_remote_dl
2817
		exit_trap
2818
	fi
2819

    
2820
  	require_root_or_group
2821

    
2822
	# If this app can only be installed as root
2823
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then require_root ; fi
2824

    
2825
	check_agree_lic
2826
	check_existing_pbi
2827
	do_pbi_add
2828
}
2829

    
2830
# Check if this PBI exists and exit if so
2831
check_existing_pbi() {
2832
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then return 0; fi
2833
	get_dbdir
2834
	dir="${APPDBDIR}"
2835

    
2836
	# See if this PBI is already installed
2837
	if [ -d "$dir" ]; then
2838
		get_username_from_file "${APPDBDIR}/pbi_name"
2839
		if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
2840
			exit_err "Permission denied to modify PBI installed by: $FILEUSER"     
2841
		fi
2842

    
2843
		if [ "${PBI_FORCEADD}" = "YES" ] ; then return 0; fi
2844
		exit_err "${PBI_PROGNAME} ${PBI_PROGVERSION} is already installed! Use -f to force installation."
2845
	fi
2846

    
2847
	if [ -e "${PBI_PROGDIRPATH}" ]; then
2848
		get_username_from_file "${PBI_PROGDIRPATH}"
2849
		if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
2850
			exit_err "Permission denied to modify PBI installed by: $FILEUSER"     
2851
		fi
2852
		if [ "${PBI_FORCEADD}" = "YES" ] ; then return 0; fi
2853
		exit_err "${PBI_PROGDIRPATH} already exists! Use -f to force installation."
2854
	fi
2855

    
2856

    
2857
}
2858

    
2859
# Check if we have a license to agree to, and if we've provided the flag to do so
2860
check_agree_lic() {
2861
        open_header_tmp
2862
        if [ -f "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}" -a "${PBI_LICAGREE}" = "NO" ] ; then
2863
        	delete_header_tmp
2864
		exit_err "LICENSE must be agreed to (--licagree) before this PBI can be installed."
2865
        fi
2866
        delete_header_tmp
2867
}
2868

    
2869
# See if we need to display pbi meta file
2870
check_pbi_meta_display() {
2871
	if [ "$PBI_ADD_METADISPLAY" != "YES" ] ; then return 0 ; fi
2872
	open_header_tmp
2873
	
2874
	if [ -f "${PBI_HEADER_TMPDIR}/${PBI_USERMETAFILE}" ] ; then 
2875
		cat "${PBI_HEADER_TMPDIR}/${PBI_USERMETAFILE}"	
2876
	else
2877
		echo "`basename $0`: No user metafile included with this PBI"
2878
	fi
2879
	delete_header_tmp
2880
}
2881

    
2882
# See if we need to display pbi license
2883
check_pbi_license_display() {
2884
	if [ "$PBI_ADD_LICDISPLAY" != "YES" ] ; then return 0 ; fi
2885
	open_header_tmp
2886
	
2887
	if [ -f "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}" ] ; then 
2888
		echo "LICENSE:"
2889
		cat "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}"	
2890
	else
2891
		echo "`basename $0`: No LICENSE included with this PBI"
2892
	fi
2893
	delete_header_tmp
2894
}
2895

    
2896
# See if we need to display pbi info
2897
check_pbi_info_display() {
2898
	if [ "$PBI_ADD_INFODISPLAY" != "YES" ] ; then return 0 ; fi
2899
	pbi_display_info
2900
}
2901

    
2902
# Display pbi information to stdout
2903
pbi_display_info() {
2904

    
2905
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
2906
        _appname="${tmp}-${PBI_PROGVERSION}-${PBI_APPARCH}"
2907

    
2908
	if [ -z "$PBI_PATCHVERSION" ] ; then
2909
		echo "PBI Information for: $_appname"
2910
	else
2911
		echo "PBP Information for: $_appname"
2912
	fi
2913
	echo "-----------------------------------------------------"
2914
	echo "Name: ${PBI_PROGNAME}"
2915

    
2916
	if [ -n "$PBI_PATCHVERSION" ] ; then
2917
		echo "PatchTarget: $PBI_PATCHTARGET"
2918
	fi
2919

    
2920
	if [ -n "$PBI_INSTALLED_BY" ] ; then
2921
		echo "InstalledBy: $PBI_INSTALLED_BY"
2922
	fi
2923

    
2924
	# Does this PBI need root to install?
2925
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then
2926
		echo "RootInstall: YES"
2927
	else
2928
		echo "RootInstall: NO"
2929
	fi
2930

    
2931
	echo "Version: ${PBI_PROGVERSION}"
2932
	echo "Built: ${PBI_PROGMDATE}"
2933
	echo "Prefix: ${PBI_ORIGPROGDIRPATH}"
2934
	echo "Author: ${PBI_PROGAUTHOR}"
2935
	echo "Website: ${PBI_PROGWEB}"
2936
	echo "Arch: ${PBI_APPARCH}"
2937
	echo "FbsdVer: ${PBI_FBSDVER}"
2938
	echo "CreatorVer: ${PBI_APPCREATEVER}"
2939
	echo "ArchiveCount: ${PBI_ARCHIVE_COUNT}"
2940
	echo "ArchiveSum: ${PBI_ARCHIVE_CHECKSUM}"
2941
	case ${PBI_SIGVALID} in
2942
		0) echo "Signature: Verified" ;;
2943
  	       -1) echo "Signature: Not Signed" ;;
2944
  	        1) echo "Signature: Bad" ;;
2945
		*) echo "Signature: <Unknown>" ;;
2946
	esac
2947

    
2948
	if [ -n "$PBI_LICENSE" ] ; then
2949
		echo "License: $PBI_LICENSE"
2950
	fi
2951

    
2952
	if [ -n "${PBI_REPO}" ] ; then
2953
		local _rDesc="`cat ${PBI_DBREPODIR}/*.${PBI_REPO} | grep "Desc:" | sed 's|Desc: ||g'`"
2954
		local _rID="`ls ${PBI_DBREPODIR}/*.${PBI_REPO}`"
2955
		_rID=`basename $_rID | cut -d '.' -f 1`
2956
		echo "Associated Repo: ${_rID} (${_rDesc})"
2957
	fi
2958
	
2959
	# Check if autoupdate is enable or not
2960
	if [ "${PBI_ENABLEAUTOUPDATE}" = "YES" ] ; then
2961
		echo "AutoUpdate: YES"
2962
	else
2963
		echo "AutoUpdate: NO"
2964
	fi
2965

    
2966
	# See if we have any XDG stuff
2967
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-desktop/install-desktop-icons.sh" ] ; then
2968
		echo "DesktopIcons: YES"
2969
	fi
2970
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-menu/install-menu-icons.sh" ] ; then
2971
		echo "MenuIcons: YES"
2972
	fi
2973
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-mime/install-mime.sh" ] ; then
2974
		echo "MimeRegistration: YES"
2975
	fi
2976

    
2977
	# If verbose mode, show file contents
2978
	if [ "$PBI_VERBOSE" = "YES" ] ; then
2979
		if [ -n "${PBI_FILENAME}" -a -e "${PBI_FILENAME}" ] ; then
2980
	  		pbi_find_archive_header
2981
                	echo "TOTALFILES: ${PBI_ARCHIVE_COUNT}"
2982
                	echo "Archive Contents:"
2983
                	echo "--------------------------------------"
2984
                	tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar tvf - 
2985
		fi
2986
        fi
2987
}
2988

    
2989
# See if we need to display gui header info
2990
check_pbi_gui_display() {
2991
	if [ "$PBI_ADD_GUIDISPLAY" != "YES" ] ; then return 0 ; fi
2992
	open_header_tmp
2993
	
2994
	pbi_display_gui "$PBI_HEADER_TMPDIR" "COPY"
2995

    
2996
	delete_header_tmp
2997

    
2998
}
2999

    
3000
# Display location of PBI graphics
3001
pbi_display_gui() {
3002
	dir="$1"
3003
	copy="$2"
3004
	if [ -e "${dir}/top-banner.png" ] ; then 
3005
		if [ "$copy" = "COPY" ] ; then
3006
			pbi_guitop="/tmp/.PBI-top.$$.png"
3007
			cp "${dir}/top-banner.png" "$pbi_guitop"
3008
		else
3009
			pbi_guitop="${dir}/top-banner.png"
3010
		fi
3011
		echo "TopBanner: ${pbi_guitop}"
3012
	fi
3013
	if [ -e "${dir}/side-banner.png" ] ; then 
3014
		if [ "$copy" = "COPY" ] ; then
3015
			pbi_guiside="/tmp/.PBI-side.$$.png"
3016
			cp "${dir}/side-banner.png" "$pbi_guiside"
3017
		else
3018
			pbi_guiside="${dir}/side-banner.png"
3019
		fi
3020
		echo "SideBanner: ${pbi_guiside}"
3021
	fi
3022

    
3023
	# Try to find an icon
3024
	ls ${dir}/pbi_icon.* >/dev/null 2>/dev/null
3025
	if [ "$?" = "0" ] ; then
3026
		_iconExt=`ls ${dir}/pbi_icon.* | head -n 1 | awk -F . '{print $NF}'`
3027
		if [ "$copy" = "COPY" ] ; then
3028
			pbi_guiicon="/tmp/.PBI-icon.$$.${_iconExt}"
3029
			cp "${dir}/pbi_icon.${_iconExt}" "$pbi_guiicon"
3030
		else
3031
			pbi_guiicon="${dir}/pbi_icon.${_iconExt}"
3032
		fi
3033
		echo "Icon: ${pbi_guiicon}"
3034
	fi
3035

    
3036
}
3037

    
3038
open_header_tmp() {
3039
	init_tmpdir
3040

    
3041
	# If we have a custom extract dir, use it
3042
	if [ -z "$1" ] ; then
3043
		PBI_HEADER_TMPDIR="${PBI_TMPDIR}/.PBI-header.$$"
3044
	else
3045
		PBI_HEADER_TMPDIR="${1}/.PBI-header.$$"
3046
	fi
3047

    
3048
	if [ -e "${PBI_HEADER_TMPDIR}" ] ; then rm -rf "${PBI_HEADER_TMPDIR}" ; fi
3049
	mkdir -p "${PBI_HEADER_TMPDIR}"
3050
	
3051
	# Extract the header files 
3052
	tar xf "${PBI_FILENAME}" -C "${PBI_HEADER_TMPDIR}" >/dev/null 2>/dev/null
3053
	if [ "$?" != "0" ] ; then exit_err "Failed to read PBI header! Possible corrupt PBI, or wrong PBI version for this OS." ; fi
3054

    
3055
}
3056

    
3057
delete_header_tmp() {
3058
	if [ -z "${PBI_HEADER_TMPDIR}" ] ; then return 0 ; fi
3059
	if [ -d "${PBI_HEADER_TMPDIR}" ] ; then rm -rf "${PBI_HEADER_TMPDIR}" ; fi
3060
}
3061

    
3062
# Load in all the configuration data from the header
3063
load_info_from_header() {
3064
	open_header_tmp
3065

    
3066
	# Start loading our variables
3067
	load_info_from_dir "${PBI_HEADER_TMPDIR}"
3068

    
3069
	delete_header_tmp
3070
}
3071

    
3072
# See if we need to display scripts
3073
check_pbi_scripts_display() {
3074
	if [ "$PBI_CHECKSCRIPTS" != "YES" ] ; then return 0 ; fi
3075

    
3076
	# Display our scripts
3077
	open_header_tmp
3078
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_PREINS}" ] ; then
3079
		echo -e "\n${MOD_PREINS}:"
3080
		echo "--------------------------------"
3081
		cat "${PBI_HEADER_TMPDIR}/${MOD_PREINS}"
3082
	fi
3083
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}" ] ; then
3084
		echo -e "\n${MOD_POSTINS}:"
3085
		echo "--------------------------------"
3086
		cat "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}"
3087
	fi
3088
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_PREREM}" ] ; then
3089
		echo -e "\n${MOD_PREREM}:"
3090
		echo "--------------------------------"
3091
		cat "${PBI_HEADER_TMPDIR}/${MOD_PREREM}"
3092
	fi
3093
	delete_header_tmp
3094
}
3095

    
3096
# Load pbi information from the specified directory
3097
load_info_from_dir() {
3098
	REQUIRED_FILES="pbi_defaultpath pbi_name pbi_version pbi_author pbi_web pbi_arch pbi_fbsdver pbi_createver"
3099
	for f in $REQUIRED_FILES
3100
	do
3101
		if [ ! -e "${1}/${f}" ] ; then echo "Warning: Missing file: ${f}" ; fi
3102
	done
3103
        PBI_APPARCH=""
3104
        PBI_APPCREATEVER=""
3105
        PBI_ARCHIVE_CHECKSUM=""
3106
        PBI_ARCHIVE_COUNT=""
3107
	PBI_ENABLEAUTOUPDATE=""
3108
        PBI_FBSDVER=""
3109
	PBI_ORIGPROGDIRPATH=""
3110
	PBI_PATCHMDATE=""
3111
	PBI_PATCHVERSION=""
3112
	PBI_PATCHTARGET=""
3113
	PBI_PROGNAME=""
3114
        PBI_PROGVERSION=""
3115
        PBI_PROGAUTHOR=""
3116
        PBI_PROGMDATE=""
3117
        PBI_PROGWEB=""
3118
	PBI_REPO=""
3119
	PBI_REQUIRESROOT=""
3120
	PBI_SIGVALID=""
3121
	PBI_DESC=""
3122
	PBI_SHORTDESC=""
3123
	PBI_MAINTAINER=""
3124
	PBI_TAGS=""
3125
	PBI_PROGTYPE=""
3126
	PBI_CATEGORY=""
3127
	PBI_ICONURL=""
3128
	PBI_LICENSE=""
3129

    
3130
	PBI_ORIGPROGDIRPATH="`cat ${1}/pbi_defaultpath`"
3131
        PBI_PROGNAME="`cat ${1}/pbi_name`"
3132
        PBI_PROGVERSION="`cat ${1}/pbi_version`"
3133
        PBI_PROGAUTHOR="`cat ${1}/pbi_author`"
3134
        PBI_PROGWEB="`cat ${1}/pbi_web 2>/dev/null`"
3135
        PBI_PROGMDATE="`cat ${1}/pbi_mdate 2>/dev/null`"
3136
        PBI_APPARCH="`cat ${1}/pbi_arch 2>/dev/null`"
3137
        PBI_FBSDVER="`cat ${1}/pbi_fbsdver 2>/dev/null`"
3138
        PBI_APPCREATEVER="`cat ${1}/pbi_createver 2>/dev/null`"
3139
        PBI_ARCHIVE_COUNT="`cat ${1}/pbi_archivecount 2>/dev/null`"
3140
        PBI_ARCHIVE_CHECKSUM="`cat ${1}/pbi_archivesum 2>/dev/null`"
3141

    
3142
	if [ -e "${1}/pbi_license" ] ; then
3143
                PBI_LICENSE="`cat ${1}/pbi_license`"
3144
        fi
3145
	if [ -e "${1}/pbi_tags" ] ; then
3146
                PBI_TAGS="`cat ${1}/pbi_tags`"
3147
        fi
3148
	if [ -e "${1}/pbi_type" ] ; then
3149
                PBI_PROGTYPE="`cat ${1}/pbi_type`"
3150
        fi
3151
	if [ -e "${1}/pbi_category" ] ; then
3152
                PBI_CATEGORY="`cat ${1}/pbi_category`"
3153
        fi
3154
	if [ -e "${1}/pbi_iconurl" ] ; then
3155
                PBI_ICONURL="`cat ${1}/pbi_iconurl`"
3156
        fi
3157
	if [ -e "${1}/pbi_desc" ] ; then
3158
                PBI_DESC="`cat ${1}/pbi_desc | awk 1 ORS=' ' | sed 's|  |<br>|g' | sed 's|*|-|g'`"
3159
        fi
3160
	if [ -e "${1}/pbi_shortdesc" ] ; then
3161
                PBI_SHORTDESC="`cat ${1}/pbi_shortdesc | awk 1 ORS=' ' | sed 's|  |<br>|g' | sed 's|*|-|g'`"
3162
        fi
3163
	if [ -e "${1}/pbi_maintainer" ] ; then
3164
                PBI_MAINTAINER="`cat ${1}/pbi_maintainer`"
3165
        fi
3166

    
3167
	# Check if auto-update is enabled
3168
	if [ -e "${1}/autoupdate-enable" ] ; then
3169
		PBI_ENABLEAUTOUPDATE="YES"
3170
	fi
3171

    
3172
	# Does this PBI need to be installed as root
3173
	if [ -e "${1}/pbi_requiresroot" ] ; then
3174
		PBI_REQUIRESROOT="YES"
3175
	fi
3176
	
3177
	# Check if this is a patch file
3178
	if [ -e "${1}/pbi_patchfile" ] ; then
3179
        	PBI_PATCHVERSION=`cat ${1}/pbi_patchfile | cut -d ':' -f 2`
3180
		PBI_PATCHTARGET=`cat ${1}/pbi_patchfile | cut -d ':' -f 1`
3181
	fi
3182
	
3183
	# Check if this associates with a particular repo
3184
	if [ -e "${1}/pbi_repo" ] ; then
3185
        	PBI_REPO=`cat ${1}/pbi_repo`
3186
	fi
3187

    
3188
	# See if this patch is for a particular mdate
3189
	if [ -e "${1}/pbi_patchmdate" ] ; then
3190
        	PBI_PATCHMDATE=`cat ${1}/pbi_patchmdate`
3191
	fi
3192

    
3193
	# See if this PBI was signed
3194
	if [ -e "${1}/pbi_archivesum.sha1" ] ; then
3195
		check_valid_sigs "${1}"
3196
		if [ "$?" = "0" ] ; then
3197
			PBI_SIGVALID="0"
3198
		else
3199
			PBI_SIGVALID="1"
3200
		fi
3201
	else
3202
		PBI_SIGVALID="-1"
3203
	fi
3204
}
3205

    
3206
# Start installing the PBI
3207
do_pbi_add() {
3208
	pbi_verify_signatures
3209
	pbi_verify_archivesum
3210

    
3211
	check_preinstall_script
3212

    
3213
	mk_pbi_extract_dir
3214
	pbi_extract_archive
3215
	
3216
	pbi_add_check_uids
3217
	pbi_add_check_gids
3218

    
3219
	pbi_add_run_script
3220
	check_postinstall_script
3221

    
3222
	pbi_add_register_app
3223

    
3224
	# Be sure to let the pbid know we have a new hash-dir to register
3225
	add_hashdir_trigger
3226

    
3227
	# Flush to disk
3228
	sleep 0.5
3229
	sync
3230

    
3231
	clean_remote_dl
3232
}
3233

    
3234
# Check for any GIDs we need to create
3235
pbi_add_check_gids() {
3236
	if [ ! -e "${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}" ] ; then return ; fi
3237
	runUID=`id -u`
3238

    
3239
	while read gidLine
3240
	do
3241
		gName=`echo $gidLine | cut -d ':' -f 1`
3242
		gID=`echo $gidLine | cut -d ':' -f 3`
3243
		gUsers=`echo $gidLine | cut -d ':' -f 4`
3244

    
3245
		# Is this group already on the system?
3246
		pw groupshow $gName >/dev/null 2>/dev/null
3247
		if [ $? -eq 0 ] ; then 
3248
			echo "Using existing group: $gName"
3249
		else
3250
			# Are we installing as root?
3251
			if [ "$runUID" != "0" ] ; then
3252
				echo "Please create group \"$gName\" manually or re-install PBI as root."
3253
			else
3254
				echo "Adding group: $gName"
3255
				pw groupadd $gName -g $gID;
3256
			fi
3257
		fi
3258

    
3259
		if [ -n "$gUsers" ] ; then
3260
			for gUser in `echo $gUsers | sed 's|,| |g'`
3261
			do
3262
				pw groupshow ${gName} | grep -qw ${gUser}
3263
				if [ $? -ne 0 ] ; then
3264
					# Are we installing as root?
3265
					if [ "$runUID" != "0" ] ; then
3266
						echo "Please add user \"$gUser\" to group \"$gName\" manually or re-install PBI as root."
3267
						continue
3268
					fi
3269

    
3270
					echo "Adding user ${gUser} to group ${gName}"
3271
					pw groupmod ${gName} -m ${gUser}
3272
				fi
3273
			done
3274
		fi
3275
	done < ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}
3276
}
3277

    
3278
# Check for any UIDs we need to create
3279
pbi_add_check_uids() {
3280
	if [ ! -e "${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}" ] ; then return ; fi
3281
	runUID=`id -u`
3282

    
3283
	while read uidLine
3284
	do
3285
		uName=`echo $uidLine | cut -d ':' -f 1`
3286

    
3287
		# Is this user already on the system?
3288
		pw usershow $uName >/dev/null 2>/dev/null
3289
		if [ $? -eq 0 ] ; then echo "Using existing user: $uName"; continue ; fi
3290

    
3291
		# Are we installing as root?
3292
		if [ "$runUID" != "0" ] ; then
3293
			echo "Please create user \"$uName\" manually or re-install PBI as root."
3294
			continue
3295
		fi
3296

    
3297
		uID=`echo $uidLine | cut -d ':' -f 3`
3298
		gID=`echo $uidLine | cut -d ':' -f 4`
3299
		uClass=`echo $uidLine | cut -d ':' -f 5`
3300
		uGecos=`echo $uidLine | cut -d ':' -f 8`
3301
		uHomedir=`echo $uidLine | cut -d ':' -f 9 | sed "s|^/usr/local|${PBI_PROGDIRPATH}|"`
3302
		uShell=`echo $uidLine | cut -d ':' -f 10`
3303

    
3304
		echo "Adding user: $uName"
3305
		pw useradd $uName -u $uID -g $gID $uClass -c "$uGecos" -d $uHomedir -s $uShell;
3306

    
3307
		# Create homedir
3308
		case $uHomedir in 
3309
			/nonexistent|/var/empty) ;; 
3310
			*) install -d -g $gID -o $uID $uHomedir ;;
3311
		esac 
3312
	done < ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}
3313
}
3314

    
3315
add_hashdir_trigger() {
3316
	get_dbdir
3317
        _htrig=`echo ${APPDBDIR} | sed "s|${PBI_DBAPPDIR}|${PBI_DBHASHQUEUEDIR}|g"`
3318
	if [ ! -e "${_htrig}" ] ; then
3319
		touch "${_htrig}"
3320
	fi
3321
}
3322

    
3323
# Run the install script if exists
3324
pbi_add_run_script() {
3325

    
3326
	# If running as user, add bin path-links
3327
	if [ "`id -u`" != "0" ] ; then add_app_path_links "${PBI_PROGDIRPATH}" ; fi
3328

    
3329
	insc="${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/.pbi-install.sh"
3330
	if [ ! -e "${insc}" ] ; then return 0 ; fi
3331
	export_script_vars
3332
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3333
		${insc}
3334
	else
3335
		${insc} >/dev/null 2>/dev/null
3336
	fi
3337

    
3338
}
3339

    
3340
# If we need to, update the hashdir
3341
pbi_add_update_hashdir() {
3342
	if [ "${PBI_NOHASHDIR}" = "YES" ] ; then return 0 ; fi
3343
	if [ ! -e "${1}/${PBI_HASHLIST}" ] ; then return 0; fi
3344
	local hDir="${1}/local"
3345

    
3346
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3347
		echo "HASHCOUNT: `wc -l ${1}/${PBI_HASHLIST} | tr -d ' ' | cut -d '/' -f 1`"
3348
	else
3349
	
3350
		echo -e "Merging with hashdir...\c"
3351
	fi
3352
	
3353
	inUseDir="/usr/pbi/.mounts/`basename $1`/virtbase/dev"
3354

    
3355
	# Read the hashfile, and start making links to identical files
3356
	while read hl
3357
	do
3358
		# Is this PBI running?
3359
		if [ -d "$inUseDir" ] ; then
3360
			echo "hASHBUSY - Canceled"
3361
			return
3362
		fi
3363

    
3364
		file="`echo $hl | sed 's/:::.*$//g'`"
3365

    
3366
		# If we are trying to merge a PBI which was deleted, stop
3367
		if [ -n "${2}" -a -e "${2}" ] ; then
3368
			echo "HASHDONE - Deleted" 
3369
			return
3370
		fi
3371

    
3372
		# Make sure the target file hasnt been removed
3373
		if [ ! -e "${hDir}/${file}" ] ; then continue ; fi
3374

    
3375
		# We dont need no stinking sym-links
3376
		if [ -h "${hDir}/${file}" ] ; then continue ; fi
3377

    
3378
		if [ -f "${PBI_HASHDIR}/${hl}" ] ; then
3379
			use_hashfile "$hl" "${hDir}/$file"
3380
		else
3381
			mv_ln_hashfile "$hl" "${hDir}/$file"
3382
		fi
3383
	done < "${1}/${PBI_HASHLIST}"
3384

    
3385
	if [ "$PBI_VERBOSE" = "YES" ] ; then 
3386
		echo "HASHDONE"
3387
	else 
3388
		echo -e "Done!" 
3389
	fi
3390
}
3391

    
3392
# Use an existing hashfile
3393
use_hashfile() {
3394
	tfile="$1"
3395
	file="$2"
3396
	dir="`dirname ${tfile}`"
3397
	if [ ! -d "${PBI_HASHDIR}/${dir}" ] ; then
3398
		mkdir -p ${PBI_HASHDIR}/${dir}
3399
	fi
3400

    
3401
	# We have a match!
3402
	ln -f "${PBI_HASHDIR}/${tfile}" "${file}"
3403
	if [ $? -ne 0 ] ; then 
3404
		echo "Warning: Unable to make hash-link ${PBI_HASHDIR}/${tfile} -> ${file}"
3405
		return
3406
	fi
3407
	
3408
	# Make sure the hard-linked file doesn't get changed
3409
	chmod u-w,g-w,o-w "${file}"
3410
	if [ $? -ne 0 ] ; then 
3411
		echo "Warning: Unable to chmod ${file}"
3412
		return
3413
	fi
3414
	
3415
}
3416

    
3417
# New file we can save to hashdir
3418
mv_ln_hashfile() {
3419
	tfile="$1"
3420
	file="$2"
3421
	dir="`dirname ${tfile}`"
3422
	if [ ! -d "${PBI_HASHDIR}/${dir}" ] ; then
3423
		mkdir -p ${PBI_HASHDIR}/${dir}
3424
	fi
3425

    
3426
	ln -f "${file}" "${PBI_HASHDIR}/${tfile}"
3427
	if [ $? -ne 0 ] ; then 
3428
		echo "Warning: Unable to make hash-link ${file} -> ${PBI_HASHDIR}/${tfile}"
3429
		return
3430
	fi
3431

    
3432
	# Make sure the hard-linked file doesn't get changed
3433
	chmod u-w,g-w,o-w "${file}"
3434
	if [ $? -ne 0 ] ; then 
3435
		echo "Warning: Unable to chmod ${file}"
3436
		return
3437
	fi
3438

    
3439
	# Make sure the hard-linked file doesn't get changed
3440
	chmod u-w,g-w,o-w "${PBI_HASHDIR}/${tfile}"
3441
	if [ $? -ne 0 ] ; then 
3442
		echo "Warning: Unable to chmod ${PBI_HASHDIR}/${tfile}"
3443
		return
3444
	fi
3445

    
3446
	if [ "$PBI_VERBOSE" = "YES" ] ; then echo "L" ; fi
3447
}
3448

    
3449
# Return the dbdir for this PBI
3450
get_dbdir() {
3451
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
3452
        APPDBDIR="${PBI_DBAPPDIR}/${tmp}-${PBI_PROGVERSION}-${PBI_APPARCH}"
3453
}
3454

    
3455
# Register this app as installed
3456
pbi_add_register_app() {
3457
	if [ ! -d "$PBI_DBAPPDIR" ] ; then mkdir -p ${PBI_DBAPPDIR} ; fi
3458
        open_header_tmp
3459
	get_dbdir
3460
	dir="${APPDBDIR}"
3461

    
3462
	# Make sure we remove any existing meta-data if forcing an installation
3463
	if [ "$PBI_FORCEADD" = "YES" ] ; then
3464
	  	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
3465
          	rm -rf ${PBI_DBAPPDIR}/${tmp}-*-${PBI_APPARCH}
3466
	fi
3467

    
3468
	mkdir -p "${dir}"
3469
	
3470
        tar cf - -C "${PBI_HEADER_TMPDIR}" . 2>/dev/null | tar xvf - -C "$dir" 2>/dev/null
3471

    
3472
	# If this was a patch, use the original path
3473
	if [ -n "${PBI_ORIGPROGDIRPATH}" ] ; then
3474
		echo "${PBI_ORIGPROGDIRPATH}" >${dir}/pbi_installedpath
3475
	else
3476
		echo "${PBI_PROGDIRPATH}" >${dir}/pbi_installedpath
3477
	fi
3478

    
3479
	# See which repo / key this PBI associates to, if any
3480
	check_valid_sigs "${dir}"
3481
	if [ -n "$PBI_VALIDKEYSIG" ] ; then
3482
		_rMd5="`echo ${PBI_VALIDKEYSIG} | cut -d '.' -f 1`"
3483
		echo "$_rMd5" | sed "s|${PBI_DBKEYDIR}/||g" > ${dir}/pbi_repo
3484
	fi
3485

    
3486
	# Dont need any patch version info
3487
	if [ -e "${dir}/pbi_patchfile" ] ; then
3488
		rm "${dir}/pbi_patchfile"
3489
	fi
3490

    
3491
        delete_header_tmp
3492

    
3493
	echo "Installed: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3494
}
3495

    
3496
# Check if we have a postinstall script we need to use
3497
check_postinstall_script() {
3498
        open_header_tmp
3499

    
3500
        if [ ! -e "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}" ] ; then
3501
                delete_header_tmp
3502
                return 0
3503
        fi
3504

    
3505
        export_script_vars
3506
        sh "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}"
3507
        delete_header_tmp
3508
}
3509

    
3510
# Check if we have a preinstall script we need to use
3511
check_preinstall_script() {
3512
	open_header_tmp
3513

    
3514
	if [ ! -e "${PBI_HEADER_TMPDIR}/${MOD_PREINS}" ] ; then 
3515
		delete_header_tmp
3516
		return 0 
3517
	fi
3518

    
3519
	export_script_vars
3520
	sh "${PBI_HEADER_TMPDIR}/${MOD_PREINS}"
3521
	if [ "$?" != "0" ] ; then
3522
        	delete_header_tmp
3523
		exit_err "${MOD_PREINS} returned error status"
3524
	fi
3525
        delete_header_tmp
3526
}
3527

    
3528
# Verify if we have valid openssl signatures on important parts of PBI
3529
pbi_verify_signatures() {
3530
	if [ "${PBI_SKIPSIGVERIFY}" = "YES" ] ; then return 0 ; fi
3531
	if [ "$PBI_SIGVALID" = "0" ] ; then return ; fi
3532
	if [ "$PBI_SIGVALID" = "1" ] ; then kw="Invalid" ; else kw="No" ; fi
3533
	exit_err "$kw digital signature! If you are *SURE* you trust this PBI, re-install with --no-checksig option. "
3534

    
3535
}
3536

    
3537
# Check if we have valid signatures, and return "0" if success, "1" if failure
3538
check_valid_sigs() {
3539
	PBI_VALIDKEYSIG=""
3540

    
3541
	for _pk in ${PBI_PUBKEYS}
3542
	do
3543
		good="true"
3544
		_sf="${1}/pbi_archivesum ${1}/${MOD_PREINS} ${1}/${MOD_POSTINS} ${1}/${MOD_PREREM}"
3545
       		for _ts in $_sf
3546
        	do
3547
                	openssl dgst -sha1 \
3548
                        -verify ${_pk} \
3549
                        -signature ${_ts}.sha1 \
3550
                        ${_ts} >/dev/null 2>/dev/null
3551
			if [ "$?" != "0" ] ; then
3552
				good="false" ; break
3553
			fi
3554
			PBI_VALIDKEYSIG="$_pk"
3555
		done
3556
		if [ "$good" = "true" ] ; then return 0 ; fi
3557
        done
3558
	return 1	
3559
}
3560

    
3561
# Verify if the archive checksum is good
3562
pbi_verify_archivesum() {
3563
	if [ "${PBI_SKIPCHECKSUM}" = "YES" ] ; then return 0 ; fi
3564
	echo -e "Verifying Checksum...\c"
3565

    
3566
        pbi_find_archive_header
3567
	sum=`tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | sha256 -q`
3568
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3569
		echo "Archive checksum: ${sum}"
3570
		echo "Saved checksum: ${PBI_ARCHIVE_CHECKSUM}"
3571
	fi
3572
	if [ "$sum" != "$PBI_ARCHIVE_CHECKSUM" ] ; then
3573
		exit_err "${PBI_FILENAME} failed checksum, the archive may be corrupt."
3574
	fi
3575
	echo -e "OK"
3576

    
3577
}
3578

    
3579
# Make our PBI extraction dir
3580
mk_pbi_extract_dir() {
3581
	PBI_EXTRACTDIR="${PBI_PROGDIRPATH}"
3582
	if [ -e "${PBI_EXTRACTDIR}" ] ; then
3583
               rm -rf "$PBI_EXTRACTDIR"
3584
	fi
3585
	mkdir -p "${PBI_EXTRACTDIR}" >/dev/null 2>/dev/null
3586
	if [ "$?" != "0" ] ; then 
3587
		exit_err "Failed to create directory: ${PBI_PROGDIRPATH}"
3588
	fi
3589
}
3590

    
3591
pbi_find_archive_header() {
3592
	# Find the header for the archive
3593
	# SEARCH FOR: $PBI_SS_ARCHIVE
3594
	PBI_SKIP_ARCHLINES=`awk "/^${PBI_SS_ARCHIVE}/ { print NR + 1; exit 0; }" "${PBI_FILENAME}"`
3595
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3596
		echo "SKIP_ARCHLINES: $PBI_SKIP_ARCHLINES"
3597
	fi
3598
}
3599

    
3600
# Extract the PBI archive file
3601
pbi_extract_archive() {
3602
	pbi_find_archive_header	
3603

    
3604
	echo "Extracting to: ${PBI_EXTRACTDIR}"
3605

    
3606
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3607
		tar="xvf -"
3608
		echo "TOTALFILES: ${PBI_ARCHIVE_COUNT}"
3609
	else
3610
		tar="xf -"
3611
	fi
3612
	tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar ${tar} -C "${PBI_EXTRACTDIR}" 2>/dev/null
3613
	err="$?"
3614
	
3615
	if [ "$err" != "0" ] ; then exit_err "Failed extracting ${PBI_FILENAME}" ; fi
3616

    
3617
	if [ "$PBI_VERBOSE" = "YES" ] ; then echo "Extraction Finished!" ; fi
3618

    
3619
	# If this is an extract only, do it and exit
3620
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then exit_trap ; fi
3621
}
3622
	
3623

    
3624
# Starting pbi_create
3625
pbi_create_init() {
3626

    
3627
	require_root
3628

    
3629
	parse_create_pbi_cmdline "$@"
3630

    
3631
	# If we are making a backup copy of an installed PBI
3632
	if [ "$PBI_CBACKUP" = "YES" ] ; then
3633
		init_tmpdir
3634
		do_pbi_create_backup
3635
		exit_trap
3636
	fi
3637

    
3638
	load_pbi_conffile
3639

    
3640
	parse_cmdline_overrides
3641

    
3642
	# Copy over the application to the correct location
3643
        echo ${PBI_PROGDIRPATH} | grep -q "^${PBI_APPDIR}/"
3644
	if [ $? -ne 0 ] ; then
3645
	   _pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
3646
	   newPDP="${PBI_APPDIR}/${_pbilow}-${ARCH}"
3647
	   if [ -d "${newPDP}" ] ; then exit_err "Error: ${newPDP} already exists!" ; fi	
3648
	   cp -r ${PBI_PROGDIRPATH} ${newPDP}
3649
	   PBI_PROGDIRPATH="${newPDP}"
3650
	   export PBI_PROGDIRPATH
3651
	fi
3652

    
3653
	PBI_CREATEONLY="YES"
3654

    
3655
	check_create_required_vars
3656

    
3657
	do_pbi_create
3658

    
3659
	# Cleanup the copy dir
3660
 	if [ -n "$newPDP" ] ; then
3661
		if [ "${newPDP}" != "/" -a "${newPDP}" != "${PBI_APPDIR}/-" ] ; then
3662
			rm -rf "${newPDP}"
3663
		fi
3664
	fi
3665
}
3666

    
3667
# Start the pbi_create backup process
3668
do_pbi_create_backup() {
3669

    
3670
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_CBACKUPTARGET}"
3671
	echo "Creating backup PBI: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3672

    
3673
	# Start by making a fresh archive of the installed PBI
3674
	PBI_STAGEDIR="$PBI_ORIGPROGDIRPATH"
3675
	mk_archive_file
3676

    
3677
	# Now make the header dir
3678
	_hDir="${PBI_TMPDIR}/.header.$$"
3679
	PBI_HEADERDIR="${_hDir}"
3680
	mkdir -p "${_hDir}"
3681
	cp ${PBI_DBAPPDIR}/${PBI_CBACKUPTARGET}/* "${_hDir}"
3682
	rm ${_hDir}/*.sha1 >/dev/null 2>/dev/null
3683

    
3684
	# Get the total number of files in the STAGEDIR
3685
	get_filetotal_dir "${PBI_STAGEDIR}"
3686
	echo "${FILETOTAL}" > "${PBI_HEADERDIR}/pbi_archivecount"
3687

    
3688
	# Save a checksum of archive file
3689
	sha256 -q "${PBI_CREATE_ARCHIVE}" > "${PBI_HEADERDIR}/pbi_archivesum"
3690

    
3691
	# Sign any header files
3692
	sign_pbi_files "$PBI_HEADERDIR"
3693

    
3694
	# Make the header archive
3695
	mk_header_file
3696

    
3697
	# Now finish up and make the resulting PBI file
3698
	mk_output_pbi
3699

    
3700
}
3701

    
3702

    
3703
# Vars required for creation
3704
check_create_required_vars() {
3705
	if [ -z "${PBI_PROGNAME}" ] ; then exit_err "Missing PBI_PROGNAME"; fi
3706
	if [ -z "${PBI_PROGVERSION}" ] ; then exit_err "Missing PBI_PROGVERSION"; fi
3707
	if [ -z "${PBI_PROGAUTHOR}" ] ; then exit_err "Missing PBI_PROGAUTHOR"; fi
3708
	if [ -z "${PBI_PROGWEB}" ] ; then exit_err "Missing PBI_PROGWEB"; fi
3709
}
3710

    
3711
# Start the pbi_create process
3712
do_pbi_create() {
3713
	get_pbi_progname
3714
	echo "Creating PBI: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3715

    
3716

    
3717
	if [ "`basename $0`" = "pbi_makeport" -o "`basename $0`" = "pbi_makeport_chroot" ] ; then
3718
	  mk_stage_dir "/usr/local" "move"
3719

    
3720
	  # Check if we created a linux app, and need to copy files for it
3721
	  auto_copy_linuxbase
3722
	else
3723
	  mk_stage_dir
3724
	fi
3725

    
3726
	copy_resource_dir
3727
	clean_stage_dir
3728

    
3729
	mk_extlink_entries
3730
	clean_icons_dir
3731
	mk_xdg_scripts
3732

    
3733
	# Check for any users / groups we need to save for install time
3734
	mk_pbi_users_file
3735
	mk_pbi_groups_file
3736

    
3737
	run_pbi_prepkgscript
3738

    
3739
	mk_install_script
3740
	mk_deinstall_script
3741

    
3742
	mk_hash_list
3743

    
3744
	mk_archive_file
3745

    
3746
	mk_header_dir
3747
 	save_pbi_details_to_header
3748
	mk_header_file
3749

    
3750
	mk_output_pbi
3751

    
3752
	rm_stage_dir
3753
	exit 0
3754
}
3755

    
3756
# Start looping through and creating a hash-list of files
3757
mk_hash_list() {
3758
  	if [ "${PBI_CREATE_HASHLIST}" = "NO" ] ; then return 0 ; fi
3759
	echo "Creating hash list..."
3760

    
3761
	hashfile="${PBI_STAGEDIRMNT}/${PBI_HASHLIST}"
3762

    
3763
	if [ -e "${hashfile}" ] ; then rm "${hashfile}" ; fi
3764

    
3765
	for hdir in ${HASH_SEARCH_DIRS}
3766
	do
3767
		if [ ! -d "${PBI_STAGEDIR}/${hdir}" ] ; then continue ; fi
3768
	 	save_dir_hash_list "${hdir}" "${hashfile}"	
3769
	done
3770
}
3771

    
3772
#  Read the specified directory and save hashsums of each file
3773
save_dir_hash_list() {
3774
	cd ${PBI_STAGEDIR}
3775
	tmp_hashdir="${PBI_STAGEDIR}/.tmp-hash.$$"
3776
	find "${1}" -type f > ${tmp_hashdir}
3777
	while read line
3778
	do
3779
		if [ ! -f "$line" -o -h "$line" ] ; then continue ; fi
3780
		
3781
		# Check if this hash file is excluded
3782
		_hfound="0"
3783
		if [ -n "${PBI_HASH_EXCLUDES}" ] ; then
3784
			for _hexcl in ${PBI_HASH_EXCLUDES}
3785
			do
3786
				if [ "$_hexcl" = "$line" ] ; then
3787
					_hfound="1"
3788
				fi
3789
			done
3790
			if [ "$_hfound" = "1" ] ; then
3791
				continue
3792
			fi
3793
		fi	
3794

    
3795
		# Add to the hash-dir
3796
	 	sha=`sha256 -q "$line"`
3797
		echo "${line}:::${sha}" >> ${2}
3798

    
3799
	done < ${tmp_hashdir}
3800
	rm ${tmp_hashdir}
3801
	cd /
3802
}
3803

    
3804
# Parse any external link directives
3805
mk_extlink_entries() {
3806
	echo "Creating external link entries..."
3807
	init_tmpdir
3808
	_extf="${PBI_CONFDIR}/${MOD_EXTLINKFILE}"
3809
	_autoextf="${PBI_TMPDIR}/${MOD_AUTOEXTLINKFILE}"
3810
	_tmpextf="${PBI_TMPDIR}/${MOD_AUTOEXTLINKFILE}.$$"
3811
  	if [ ! -e "${_extf}" -a ! -e "${_autoextf}" ] ; then return 0 ; fi
3812

    
3813
	dir="${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}"
3814
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3815

    
3816
	# Create the headers for the PATH link scripts
3817
        echo "#!/bin/sh" >"${dir}/${PBI_INS_PATHSCRIPT}"
3818
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_PATHSCRIPT}"
3819

    
3820
	# Make sure we also set SYS_LOCALBASE in case user runs these stand-alone at some point
3821
        echo "if [ -z \"\$SYS_LOCALBASE\" ]; then SYS_LOCALBASE=\"${SYS_LOCALBASE}\" ; fi" >>"${dir}/${PBI_INS_PATHSCRIPT}"
3822
        echo "if [ -z \"\$SYS_LOCALBASE\" ]; then SYS_LOCALBASE=\"${SYS_LOCALBASE}\" ; fi" >>"${dir}/${PBI_UNINS_PATHSCRIPT}"
3823
        echo "if [ -z \"\$PBI_RCDIR\" ]; then PBI_RCDIR=\"${PBI_RCDIR}\" ; fi" >>"${dir}/${PBI_INS_PATHSCRIPT}"
3824
        echo "if [ -z \"\$PBI_RCDIR\" ]; then PBI_RCDIR=\"${PBI_RCDIR}\" ; fi" >>"${dir}/${PBI_UNINS_PATHSCRIPT}"
3825
        echo "if [ -z \"\$PBI_MANDIR\" ]; then PBI_MANDIR=\"${PBI_MANDIR}\" ; fi" >>"${dir}/${PBI_INS_PATHSCRIPT}"
3826
        echo "if [ -z \"\$PBI_MANDIR\" ]; then PBI_MANDIR=\"${PBI_MANDIR}\" ; fi" >>"${dir}/${PBI_UNINS_PATHSCRIPT}"
3827
        echo "if [ -z \"\$PBI_BINDIR\" ]; then PBI_BINDIR=\"${PBI_BINDIR}\" ; fi" >>"${dir}/${PBI_INS_PATHSCRIPT}"
3828
        echo "if [ -z \"\$PBI_BINDIR\" ]; then PBI_BINDIR=\"${PBI_BINDIR}\" ; fi" >>"${dir}/${PBI_UNINS_PATHSCRIPT}"
3829

    
3830
	touch "$_tmpextf"
3831
	if [ -e "$_autoextf" ]; then cat "${_autoextf}" >> "${_tmpextf}" ; fi
3832
	if [ -e "$_extf" ]; then cat "${_extf}" >> "${_tmpextf}" ; fi
3833

    
3834
        while read line
3835
        do
3836
		_bin="NO"
3837
		_wraponly="NO"
3838
		_crashhandle="YES"
3839
		_keep="YES"
3840
		_linux="NO"
3841
                echo $line | tr '\t' ' ' | tr -s ' ' | grep "^#" >/dev/null 2>/dev/null
3842
                if [ "$?" != "0" ] ; then
3843
                        src="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 1`"
3844
                        tar="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 2`"
3845
                        act="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 3`"
3846

    
3847
			if [ -z "$src" -o -z "$tar" ] ; then continue ; fi
3848

    
3849
			# Check if this is an icon we need to preserve
3850
			echo $src | grep -q "^share/icons/"
3851
			if [ $? -eq 0 -a "${PBI_USESYSFONTS}" != "NO" ] ; then
3852
				iDir=`dirname $src`
3853
				if [ ! -d "${PBI_STAGEDIR}/${PBI_ICDIR}/${iDir}" ] ; then 
3854
					mkdir -p "${PBI_STAGEDIR}/${PBI_ICDIR}/${iDir}"
3855
				fi
3856
				cp "${PBI_STAGEDIR}/${src}" "${PBI_STAGEDIR}/${PBI_ICDIR}/${iDir}"
3857
				src="${PBI_ICDIR}/${src}"
3858
			fi
3859

    
3860
			if [ ! -e "${PBI_STAGEDIR}/$src" ] ; then
3861
				echo "WARN: external_link target: \"$src -> $tar $act\" does not exist!"
3862
				continue
3863
			fi
3864

    
3865
			# Check for act directives
3866
			for i in `echo ${act} | sed 's|,| |g'`
3867
  			do
3868
				case ${i} in
3869
					binary) _bin="YES" ;;
3870
	  			    binwrapper) _bin="YES" ; _wraponly="YES" ;;
3871
				       nocrash) _crashhandle="NO" ;;
3872
				          keep) _keep="YES" ;;
3873
				       replace) _keep="NO" ;;
3874
				         linux) _bin="YES" ; _linux="YES" ;;
3875
					*) echo "Warning: Unknown option \"$i\" in ${MOD_EXTLINKFILE}";;
3876
				esac
3877
				
3878
			done
3879

    
3880

    
3881
			# If we are doing a binary, run special function to make wrapper
3882
			if [ "$_bin" = "YES" ] ; then
3883

    
3884
				# Make sure we don't create any duplicates
3885
				echo "$_donewrap" | grep "#${src}#" >/dev/null 2>/dev/null
3886
				if [ "$?" = "0" ] ; then continue ; fi
3887
				
3888
				# Make the binary wrapper
3889
				mk_path_wrappers "$src" "$tar" "$_crashhandle" "$_wraponly" "$_linux"
3890

    
3891
				# This binary is done, save it now so we don't duplicate later
3892
				_donewrap="$_donewrap #${src}#"
3893
			else
3894
				# Make our link commands
3895
				if [ "$_keep" = "YES" ] ; then _lop="-fs"; else _lop="-s"; fi
3896
				echo $tar | grep -q "^man/"
3897
				if [ $? -eq 0 ] ; then
3898
					# Strip off the man/ path
3899
					_mTar=`echo $tar | sed 's|^man/||g'`
3900
					_dTar="\$PBI_MANDIR/${_mTar}"
3901
					echo "_bd=\"\`dirname ${_dTar}\`\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3902
					echo "if [ ! -d \"\$_bd\" ] ; then mkdir -p \"\${_bd}\"; fi" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3903
					echo "ln ${_lop} $PBI_PROGDIRPATH/local/${src} \$PBI_MANDIR/${_mTar}" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3904
				else
3905
					_dTar="\$SYS_LOCALBASE/${tar}"
3906
					echo "_bd=\"\`dirname ${_dTar}\`\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3907
					echo "if [ ! -d \"\$_bd\" ] ; then mkdir -p \"\${_bd}\"; fi" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3908
					echo "ln ${_lop} $PBI_PROGDIRPATH/local/${src} \$SYS_LOCALBASE/${tar}" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3909

    
3910
				fi
3911
			fi
3912

    
3913
			# Make the uninstall command
3914
			echo "ls -al \"${_dTar}\" | grep \"> $PBI_PROGDIRPATH\" >/dev/null 2>/dev/null " \
3915
				>> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3916
			echo "if [ \"\$?\" = \"0\" ] ; then" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3917
			echo "	rm \"${_dTar}\"" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3918
			echo "fi" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3919

    
3920
			echo " " >> "${dir}/${PBI_INS_PATHSCRIPT}"
3921
			echo " " >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3922

    
3923
                fi
3924

    
3925
        done < "${_tmpextf}"
3926
	rm "${_tmpextf}"
3927

    
3928
	chmod 755 "${dir}/${PBI_INS_PATHSCRIPT}"
3929
	chmod 755 "${dir}/${PBI_UNINS_PATHSCRIPT}"
3930
}
3931

    
3932

    
3933
# Create the wrapper scripts for the specified binaries 
3934
mk_path_wrappers() {
3935
	dir="${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}"
3936
	rcdir="${PBI_STAGEDIRMNT}/${PBI_FAKERC_DIR}"
3937
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3938

    
3939
	bin="${1}"
3940
	fbin="`basename ${bin}`"
3941
	tar="${2}"
3942
	ch="${3}"
3943
	onlywrap="${4}"
3944
	linwrap="${5}"
3945

    
3946
	# Check if the fake-bin wrapper already exists, and if so use
3947
	# a different name
3948
	if [ -e "${dir}/${fbin}" ] ; then
3949
		fbin=`echo $bin | sed 's|/|-|g'`
3950
	fi
3951

    
3952
	# If this is an rc.d script, add it to the PBI_RCDIR
3953
	if [ "`dirname $tar`" = "etc/rc.d" ] ; then
3954
			>> "${dir}/${PBI_INS_PATHSCRIPT}"
3955
		_dTar="\$PBI_RCDIR/`basename ${tar}`"
3956
		echo "_bd=\"\`dirname ${_dTar}\`\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3957
		echo "if [ ! -d \"\$_bd\" ] ; then mkdir -p \"\${_bd}\"; fi" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3958
		echo "ln -fs $PBI_PROGDIRPATH/${PBI_FAKERC_DIR}/${fbin} \$PBI_RCDIR/`basename ${tar}`" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3959

    
3960
		# Copy the wrapper binary
3961
		PBI_WRAPPERFILE="/.pbiwrapper-$ARCH"
3962
		cp ${PBI_WRAPPERFILE} ${rcdir}/${fbin}
3963
		chmod 755 ${rcdir}/${fbin}
3964

    
3965
		# Create the wrapper .pbiopt
3966
		echo "PROGDIR: ${PBI_PROGDIRPATH}" >${rcdir}/${fbin}.pbiopt
3967
		echo "TARGET: ${bin}" >>${rcdir}/${fbin}.pbiopt
3968
		return
3969
	fi
3970

    
3971
	# Make our link to the system localbase if its not a wrapper only
3972
 	if [ "$onlywrap" != "YES" ] ; then	
3973
		_mTar=`echo $tar | sed "s|^bin/||g" | sed "s|^sbin/||g"`
3974
		_dTar="\$PBI_BINDIR/${_mTar}"
3975

    
3976
			>> "${dir}/${PBI_INS_PATHSCRIPT}"
3977
		echo "_bd=\"\`dirname ${_dTar}\`\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3978
		echo "if [ ! -d \"\$_bd\" ] ; then mkdir -p \"\${_bd}\"; fi" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3979
		echo "ln -fs $PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${fbin} \$PBI_BINDIR/${_mTar}" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3980
	fi
3981

    
3982

    
3983
	# Copy the wrapper binary
3984
	PBI_WRAPPERFILE="/.pbiwrapper-$ARCH"
3985
	cp ${PBI_WRAPPERFILE} ${dir}/${fbin}
3986
	chmod 755 ${dir}/${fbin}
3987

    
3988
	# Create the wrapper .pbiopt
3989
	echo "PROGDIR: ${PBI_PROGDIRPATH}" >${dir}/${fbin}.pbiopt
3990
	echo "TARGET: ${bin}" >>${dir}/${fbin}.pbiopt
3991
}
3992

    
3993
# Create any XDG script for install / deinstall
3994
mk_xdg_scripts() {
3995
 	echo "Creating xdg scripts..."
3996
  	mk_xdg_desktop_script
3997
  	mk_xdg_menu_script
3998
  	mk_xdg_mime_script
3999
}
4000

    
4001
# Create any XDG script for desktop icons
4002
mk_xdg_desktop_script() {
4003
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGDESK_DIR}" ] ; then return 0 ; fi
4004
	_dFound=0
4005

    
4006
	dir="${PBI_STAGEDIRMNT}/${PBI_APPDESK_DIR}"
4007
	if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
4008
	echo "#!/bin/sh" >"${dir}/${PBI_INS_DESKSCRIPT}"
4009
	echo "#!/bin/sh" >"${dir}/${PBI_UNINS_DESKSCRIPT}"
4010

    
4011
  	cd "${PBI_CONFDIR}/${MOD_XDGDESK_DIR}"
4012
  	for i in `ls *.desktop 2>/dev/null`
4013
  	do
4014
		_dFound=1
4015

    
4016
		# Copy over the .desktop file, modifying any variables within
4017
	        cat "${i}" \
4018
           	| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
4019
		| sed "s|%%PBI_APPDIR%%|${PBI_PROGDIRPATH}/local|g" \
4020
		> "${dir}/PBI-${i}"
4021

    
4022
		# Set the correct permissions on the desktop file
4023
		chmod 744 "${dir}/PBI-${i}"
4024

    
4025
		ifi="$PBI_PROGDIRPATH/${PBI_APPDESK_DIR}/PBI-${i}"
4026

    
4027
		echo "xdg-desktop-icon install --novendor ${ifi}" \
4028
			 >> "${dir}/${PBI_INS_DESKSCRIPT}"
4029
		echo "xdg-desktop-icon uninstall ${ifi}" \
4030
			 >> "${dir}/${PBI_UNINS_DESKSCRIPT}"
4031
		
4032
  	done
4033

    
4034
	chmod 755 "${dir}/${PBI_INS_DESKSCRIPT}"
4035
	chmod 755 "${dir}/${PBI_UNINS_DESKSCRIPT}"
4036

    
4037
	# No desktop entries
4038
        if [ "$_dFound" = "0" ] ; then
4039
                rm "${dir}/${PBI_INS_DESKSCRIPT}"
4040
                rm "${dir}/${PBI_UNINS_DESKSCRIPT}"
4041
        fi
4042
}
4043

    
4044
# Create any XDG script for menu icons
4045
mk_xdg_menu_script() {
4046
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGMENU_DIR}" ] ; then return 0 ; fi
4047

    
4048
	_mFound=0
4049

    
4050
	dir="${PBI_STAGEDIRMNT}/${PBI_APPMENU_DIR}"
4051
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
4052
        echo "#!/bin/sh" >"${dir}/${PBI_INS_MENUSCRIPT}"
4053
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_MENUSCRIPT}"
4054

    
4055
  	cd "${PBI_CONFDIR}/${MOD_XDGMENU_DIR}"
4056
  	for i in `ls *.desktop 2>/dev/null`
4057
  	do
4058
		_mFound=1
4059

    
4060
		# Copy the desktop file, changing any included vars
4061
	        cat "${i}" \
4062
           	| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
4063
		| sed "s|%%PBI_APPDIR%%|${PBI_PROGDIRPATH}/local|g" \
4064
		> "${dir}/PBI-${i}"
4065

    
4066
		# Set the correct permissions on the menu file
4067
		chmod 744 "${dir}/PBI-${i}"
4068

    
4069
		ifi="$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/PBI-${i}"
4070

    
4071
		# Check for a .directory file associated with this .desktop
4072
		ifd=""
4073
		dirfile="`basename -s .desktop ${i}`"
4074
		if [ -e "${dirfile}.directory" ] ; then
4075
	        	cat "${dirfile}.directory" \
4076
           		| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
4077
			| sed "s|%%PBI_APPDIR%%|${PBI_PROGDIRPATH}/local|g" \
4078
			> "${dir}/PBI-${dirfile}.directory"
4079
			#cp "${dirfile}.directory" "${dir}/PBI-${dirfile}.directory"
4080
			ifd="$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/PBI-${dirfile}.directory "	
4081
		fi
4082

    
4083
		echo "xdg-desktop-menu install --novendor ${ifd}${ifi}" \
4084
			 >> "${dir}/${PBI_INS_MENUSCRIPT}"
4085
		echo "xdg-desktop-menu uninstall ${ifd}${ifi}" \
4086
			 >> "${dir}/${PBI_UNINS_MENUSCRIPT}"
4087

    
4088
  	done
4089

    
4090
	chmod 755 "${dir}/${PBI_INS_MENUSCRIPT}"
4091
	chmod 755 "${dir}/${PBI_UNINS_MENUSCRIPT}"
4092

    
4093
	# No mime entries
4094
        if [ "$_mFound" = "0" ] ; then
4095
                rm "${dir}/${PBI_INS_MENUSCRIPT}"
4096
                rm "${dir}/${PBI_UNINS_MENUSCRIPT}"
4097
        fi
4098
}
4099

    
4100
# Create any XDG script for mime types
4101
mk_xdg_mime_script() {
4102
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGMIME_DIR}" ] ; then return 0 ; fi
4103
	_mFound=0
4104

    
4105
        dir="${PBI_STAGEDIRMNT}/${PBI_APPMIME_DIR}"
4106
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
4107
        echo "#!/bin/sh" >"${dir}/${PBI_INS_MIMESCRIPT}"
4108
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_MIMESCRIPT}"
4109

    
4110

    
4111
  	cd "${PBI_CONFDIR}/${MOD_XDGMIME_DIR}"
4112
  	for i in `ls *.xml 2>/dev/null`
4113
  	do
4114
		_mFound=1
4115
		cp "${i}" "${dir}/PBI-${i}"
4116
		ifi="$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/PBI-${i}"
4117

    
4118
		# Check for a .directory file associated with this .desktop
4119
		ifp=""
4120
		iconfile="`basename -s .xml ${i}`"
4121
		if [ -e "${iconfile}.png" ] ; then
4122
			cp "${iconfile}.png" "${dir}/${iconfile}.png"
4123
			ifp="$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${iconfile}.png"
4124
			mi=`cat "$i" | grep '<mime-type' | cut -d '"' -f 2 | sed 's|/|-|g'`
4125
			echo "xdg-icon-resource install --novendor --context mimetypes ${ifp} --size 64 $mi" \
4126
				 >> "${dir}/${PBI_INS_MIMESCRIPT}"
4127
			echo "xdg-icon-resource uninstall --context mimetypes ${ifp} --size 64" \
4128
				 >> "${dir}/${PBI_UNINS_MIMESCRIPT}"
4129
		fi
4130

    
4131
		echo "xdg-mime install --novendor ${ifi}" \
4132
			 >> "${dir}/${PBI_INS_MIMESCRIPT}"
4133
		echo "xdg-mime uninstall ${ifi}" \
4134
			 >> "${dir}/${PBI_UNINS_MIMESCRIPT}"
4135
  	done
4136

    
4137
	chmod 755 "${dir}/${PBI_INS_MIMESCRIPT}"
4138
	chmod 755 "${dir}/${PBI_UNINS_MIMESCRIPT}"
4139

    
4140
	# No mime entries
4141
	if [ "$_mFound" = "0" ] ; then
4142
		rm "${dir}/${PBI_INS_MIMESCRIPT}"
4143
		rm "${dir}/${PBI_UNINS_MIMESCRIPT}"
4144
	fi
4145
}
4146

    
4147

    
4148
# Create the install script for the PBI
4149
mk_install_script() {
4150
	echo "Creating install script..."
4151
	if [ ! -d "${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}" ] ; then mkdir -p "${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}" ; fi
4152
	if [ ! -d "${PBI_STAGEDIRMNT}/${PBI_FAKERC_DIR}" ] ; then mkdir -p "${PBI_STAGEDIRMNT}/${PBI_FAKERC_DIR}" ; fi
4153
	insc="${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}/.pbi-install.sh"
4154
	echo "#!/bin/sh" > "$insc"
4155
	echo "PBI_WRAPPERBIN=\"${PBI_FAKEBIN_DIR}\"" >> "$insc"
4156
	echo "PBI_PROGDIRPATH=\"${PBI_PROGDIRPATH}\"" >> "$insc"
4157
	echo "SYS_LOCALBASE=\"${SYS_LOCALBASE}\"" >> "$insc"
4158
	echo "cd \"\$PBI_PROGDIRPATH\"" >> "$insc"
4159

    
4160
	# Add the binary wrapper sym-links
4161
        if [ -e "${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" ] ; then
4162
		echo 'if [ `id -u` = "0" ] ; then ' >>${insc}
4163
		echo "	$PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" >>${insc}
4164
		echo "fi" >>${insc}
4165
	fi
4166

    
4167
	# Look for any XDG scripts
4168
        if [ -e "${PBI_STAGEDIRMNT}/${PBI_APPMIME_DIR}/${PBI_INS_MIMESCRIPT}" ] ; then
4169
		echo "$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${PBI_INS_MIMESCRIPT}" >>${insc}
4170
	fi
4171
        if [ -e "${PBI_STAGEDIRMNT}/${PBI_APPMENU_DIR}/${PBI_INS_MENUSCRIPT}" ] ; then
4172
		echo "$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/${PBI_INS_MENUSCRIPT}" >>${insc}
4173
	fi
4174

    
4175
	chmod 755 "${insc}"
4176
	
4177
}
4178

    
4179
# Create the deinstall script for the PBI
4180
mk_deinstall_script() {
4181
	echo "Creating deinstall script..."
4182
	uisc="${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}/.pbi-uninstall.sh"
4183

    
4184
	echo "#!/bin/sh" > "$uisc"
4185
	echo "PBI_PROGDIRPATH=\"${PBI_PROGDIRPATH}\"" >> "$uisc"
4186
	echo "SYS_LOCALBASE=\"${SYS_LOCALBASE}\"" >> "$uisc"
4187

    
4188
	# Remove the binary wrapper sym-links
4189
        if [ -e "${PBI_STAGEDIRMNT}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" ] ; then
4190
		echo 'if [ `id -u` = "0" ] ; then ' >>${uisc}
4191
		echo "	$PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" >>${uisc}
4192
		echo "fi" >>${uisc}
4193
	fi
4194

    
4195
	# Look for any XDG scripts
4196
        if [ -e "${PBI_STAGEDIRMNT}/${PBI_APPMIME_DIR}/${PBI_UNINS_MIMESCRIPT}" ] ; then
4197
		echo "$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${PBI_UNINS_MIMESCRIPT}" >>${uisc}
4198
	fi
4199
        if [ -e "${PBI_STAGEDIRMNT}/${PBI_APPMENU_DIR}/${PBI_UNINS_MENUSCRIPT}" ] ; then
4200
		echo "$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/${PBI_UNINS_MENUSCRIPT}" >>${uisc}
4201
	fi
4202
	chmod 755 "${uisc}"
4203
}
4204

    
4205
# Create a dir for manipulating header info
4206
mk_header_dir() {
4207
	PBI_HEADERDIR="${PBI_STAGEDIRMNT}/pbimeta"
4208
	if [ -e "${PBI_HEADERDIR}" ] ; then rm -rf "${PBI_HEADERDIR}" ; fi
4209
	mkdir -p ${PBI_HEADERDIR}
4210
}
4211

    
4212
# Create a dir for staging the final archive
4213
mk_stage_dir() {
4214
	if [ -n "$1" ] ; then
4215
		cpDir="$1"
4216
	else
4217
		cpDir="${PBI_PROGDIRPATH}"
4218
	fi
4219

    
4220
	PBI_STAGEDIR="${PBI_PROGDIRPATH}/.stagedir"
4221
	echo "Creating Stage Dir: ${PBI_STAGEDIR}"
4222
	if [ -e "${PBI_STAGEDIR}" ] ; then 
4223
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4224
		chflags -R noschg ${PBI_STAGEDIR} 2>/dev/null
4225
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4226
	fi
4227
	mkdir -p ${PBI_STAGEDIR}
4228

    
4229
	mkdir -p ${PBI_STAGEDIR}/local
4230
	mkdir -p ${PBI_STAGEDIR}/etc
4231
	mkdir -p ${PBI_STAGEDIR}/rc.d
4232
	mkdir -p ${PBI_STAGEDIR}/pbimeta
4233
	mkdir -p ${PBI_STAGEDIR}/virtbase
4234
	mkdir -p ${PBI_STAGEDIR}/linux
4235
	mkdir -p ${PBI_STAGEDIR}/run
4236

    
4237
	# If we built with a module / conf directory, lets include it
4238
	if [ -d "${PBI_CONFDIR}" ] ; then cp -r ${PBI_CONFDIR} ${PBI_STAGEDIR}/pbiconf; fi
4239

    
4240
	local _excOpts=""
4241

    
4242
	# Build module list of excludes
4243
	if [ -n "$PBI_EXCLUDELIST" ] ; then
4244
		for excl in $PBI_EXCLUDELIST
4245
		do
4246
			if [ -z "$_excOpts" ] ; then
4247
				_excOpts="--exclude ${excl}"
4248
			else
4249
				_excOpts="$_excOpts --exclude ${excl}"
4250
			fi
4251
		done
4252
	fi
4253

    
4254
	if [ "$2" = "move" ] ; then
4255
		rmdir ${PBI_STAGEDIR}/local
4256
		mv ${cpDir} ${PBI_STAGEDIR}/local
4257
		ln -s ${PBI_STAGEDIR}/local /usr/local
4258
	else
4259
		# Now copy the stagedir
4260
		tar cf - ${_excOpts} --exclude .stagedir \
4261
		--exclude .pkgdb --exclude .ld-elf.hints --exclude make.conf \
4262
		--exclude make.conf.bak --exclude .keepports \
4263
		-C "${cpDir}" . 2>/dev/null \
4264
		| tar xpf - -C ${PBI_STAGEDIR}/local 2>/dev/null
4265
	fi
4266

    
4267
	cd ${PBI_PROGDIRPATH}
4268
	PBI_STAGEDIRMNT="${PBI_STAGEDIR}"
4269
	PBI_STAGEDIR="${PBI_STAGEDIR}/local"
4270
}
4271

    
4272
# Remove the stagedir
4273
rm_stage_dir() {
4274
	# If this is in the chroot we can exit and let the parent cleanup
4275
	if [ "$0" = "pbi_makeport_chroot" ] ; then return; fi
4276

    
4277
	cd /
4278
	PBI_STAGEDIR="${PBI_PROGDIRPATH}/.stagedir"
4279
	if [ -e "${PBI_STAGEDIR}" ] ; then 
4280
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4281
		chflags -R noschg ${PBI_STAGEDIR} 2>/dev/null
4282
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4283
	fi
4284
}
4285

    
4286
# See if we need to clean the icons dir
4287
clean_icons_dir() {
4288
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
4289
		rm -rf ${PBI_STAGEDIR}/share/icons >/dev/null 2>/dev/null
4290
		mkdir ${PBI_STAGEDIR}/share/icons >/dev/null 2>/dev/null
4291
	fi
4292
}
4293

    
4294
# See if we need to clean the stagedir
4295
clean_stage_dir() {
4296

    
4297
	if [ "${PBI_USESYSGL}" != "NO" ] ; then
4298
		rm ${PBI_STAGEDIR}/lib/libGl.* >/dev/null 2>/dev/null
4299
		rm ${PBI_STAGEDIR}/lib/libGL.* >/dev/null 2>/dev/null
4300
		rm ${PBI_STAGEDIR}/lib/libGLU.* >/dev/null 2>/dev/null
4301
	fi
4302
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
4303
		rm -rf ${PBI_STAGEDIR}/etc/fonts/* >/dev/null 2>/dev/null
4304
		rm -rf ${PBI_STAGEDIR}/lib/X11/fonts/* >/dev/null 2>/dev/null
4305
		rm -rf ${PBI_STAGEDIR}/lib/X11/icons/* >/dev/null 2>/dev/null
4306
	fi
4307
	if [ -e "${PBI_STAGEDIR}/lib/X11" ] ; then
4308
		mkdir -p ${PBI_STAGEDIR}/lib/X11/icons/ >/dev/null 2>/dev/null
4309
		mkdir -p ${PBI_STAGEDIR}/lib/X11/fonts/ >/dev/null 2>/dev/null
4310
		mkdir -p ${PBI_STAGEDIR}/etc/fonts/ >/dev/null 2>/dev/null
4311
	fi
4312
}
4313

    
4314
# Copy over any resource files into the PBI dir
4315
copy_resource_dir() {
4316
	if [ -d "${PBI_CONFDIR}/${PBI_RESOURCE_DIR}" ] ; then
4317
		echo "Copying ${PBI_CONFDIR}/${PBI_RESOURCE_DIR} -> ${PBI_STAGEDIR}"
4318
		tar cf - -C ${PBI_CONFDIR}/${PBI_RESOURCE_DIR} --exclude .svn . 2>/dev/null \
4319
		| tar xpf - -C ${PBI_STAGEDIR} 2>/dev/null
4320
	fi
4321
}
4322

    
4323
# Check if tar supports lzma compression
4324
test_tar_lzma() {
4325
	touch /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
4326
	tar cJf /tmp/.pbilzma.tar.$$ /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
4327
	_exitcode=$?
4328
	rm /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
4329
	rm /tmp/.pbilzma.tar.$$ >/dev/null 2>/dev/null
4330
	return $_exitcode
4331
}
4332

    
4333
# Start creating the application archive 
4334
mk_archive_file() {
4335
        # Build module list of excludes
4336
        if [ -n "$PBI_EXCLUDELIST" ] ; then
4337
                for excl in $PBI_EXCLUDELIST
4338
                do
4339
                        if [ -z "$_excOpts" ] ; then
4340
                                _excOpts="--exclude ${excl}"
4341
                        else
4342
                                _excOpts="$_excOpts --exclude ${excl}"
4343
                        fi
4344
                done
4345
        fi
4346
	PBI_CREATE_ARCHIVE="${PBI_CREATE_OUTDIR}/.PBI.$$.tbz"
4347
	if test_tar_lzma ; then _tcmp="J" ; else _tcmp="j" ; fi
4348
	echo "Creating compressed archive..."
4349
	tar c${_tcmp}f "${PBI_CREATE_ARCHIVE}" ${_excOpts} -C ${PBI_STAGEDIRMNT} . 2>/dev/null
4350
}
4351

    
4352
# Start creating the header archive
4353
mk_header_file() {
4354
	PBI_HEADER_ARCHIVE="${PBI_CREATE_OUTDIR}/.PBI-header.$$.tbz"
4355
	tar cjf ${PBI_HEADER_ARCHIVE} -C ${PBI_HEADERDIR} . >/dev/null 2>/dev/null
4356
}
4357

    
4358
# Start copying pbi details into header file
4359
save_pbi_details_to_header() {
4360
	local _osArch="$ARCH"
4361
	local _osRel="$FBSDREL"
4362
	if [ -n "${PBI_OSREL}" ] ; then
4363
		_osRel="${PBI_OSREL}"
4364
	fi
4365

    
4366
	if [ "${PBI_CREATEONLY}" = "YES" ] ; then
4367
		_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
4368
		echo "${PBI_APPDIR}/${_pbilow}-${_osArch}" > "${PBI_HEADERDIR}/pbi_defaultpath"
4369
	else	
4370
		echo "${PBI_PROGDIRPATH}" > "${PBI_HEADERDIR}/pbi_defaultpath"
4371
	fi
4372
	echo "${PBI_PROGNAME}" > "${PBI_HEADERDIR}/pbi_name"
4373
	echo "${PBI_PROGVERSION}" > "${PBI_HEADERDIR}/pbi_version"
4374
	echo "${PBI_PROGAUTHOR}" > "${PBI_HEADERDIR}/pbi_author"
4375
	echo "${PBI_PROGWEB}" > "${PBI_HEADERDIR}/pbi_web"
4376
	date "+%Y%m%d %H%M%S" > "${PBI_HEADERDIR}/pbi_mdate"
4377

    
4378
	if [ "${PBI_REQUIRESROOT}" = "YES" ] ; then
4379
		touch ${PBI_HEADERDIR}/pbi_requiresroot
4380
	fi
4381

    
4382
	# Do we have a license to accept?
4383
	if [ -e "${PBI_CONFDIR}/${PBI_LICENSEFILE}" ] ; then
4384
		cp "${PBI_CONFDIR}/${PBI_LICENSEFILE}" "${PBI_HEADERDIR}/${PBI_LICENSEFILE}"
4385
	fi
4386

    
4387
	# Do we have a conf-supplied meta-file to copy?
4388
	if [ -e "${PBI_CONFDIR}/${PBI_USERMETAFILE}" ] ; then
4389
		cp "${PBI_CONFDIR}/${PBI_USERMETAFILE}" "${PBI_HEADERDIR}/${PBI_USERMETAFILE}"
4390
	fi
4391
	# Do we have a user-supplied meta-file to copy?
4392
	if [ -n "$PBI_CREATE_USERMETA" ] ; then
4393
		cp "$PBI_CREATE_USERMETA" "${PBI_HEADERDIR}/${PBI_USERMETAFILE}"
4394
	fi
4395

    
4396
	# Check for additional meta-data
4397
	if [ -n "$PBI_LICENSE" ] ; then
4398
		echo "$PBI_LICENSE" > ${PBI_HEADERDIR}/pbi_license
4399
	fi
4400
	if [ -n "$PBI_TAGS" ] ; then
4401
		echo "$PBI_TAGS" > ${PBI_HEADERDIR}/pbi_tags
4402
	fi
4403
	if [ -n "$PBI_PROGTYPE" ] ; then
4404
		echo "$PBI_PROGTYPE" > ${PBI_HEADERDIR}/pbi_type
4405
	fi
4406
	if [ -n "$PBI_CATEGORY" ] ; then
4407
		echo "$PBI_CATEGORY" > ${PBI_HEADERDIR}/pbi_category
4408
	fi
4409
	if [ -n "$PBI_ICONURL" ] ; then
4410
		echo "$PBI_ICONURL" > ${PBI_HEADERDIR}/pbi_iconurl
4411
	fi
4412
	if [ -n "$PBI_DESC" ] ; then
4413
		echo "$PBI_DESC" > ${PBI_HEADERDIR}/pbi_desc
4414
	fi
4415
	if [ -n "$PBI_SHORTDESC" ] ; then
4416
		echo "$PBI_SHORTDESC" > ${PBI_HEADERDIR}/pbi_shortdesc
4417
	fi
4418
	if [ -n "$PBI_MAINTAINER" ] ; then
4419
		echo "$PBI_MAINTAINER" > ${PBI_HEADERDIR}/pbi_maintainer
4420
	fi
4421

    
4422
	# Custom install / remove scripts
4423
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREINS}" ] ; then
4424
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREINS}" \
4425
			"${PBI_HEADERDIR}/${MOD_PREINS}"
4426
	else
4427
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_PREINS}
4428
	fi
4429
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_POSTINS}" ] ; then
4430
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_POSTINS}" \
4431
			"${PBI_HEADERDIR}/${MOD_POSTINS}"
4432
	else
4433
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_POSTINS}
4434
	fi
4435
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREREM}" ] ; then
4436
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREREM}" \
4437
			"${PBI_HEADERDIR}/${MOD_PREREM}"
4438
	else
4439
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_PREREM}
4440
	fi
4441

    
4442
	# Copy over our icon
4443
	if [ -n "${PBI_PROGICON}" -a -e "${PBI_STAGEDIR}/${PBI_PROGICON}" ] ; then
4444
		# Get the file extension
4445
		_iconExt=`echo "$PBI_PROGICON" | awk -F . '{print $NF}'`
4446
		cp "${PBI_STAGEDIR}/${PBI_PROGICON}" "${PBI_HEADERDIR}/pbi_icon.${_iconExt}" >/dev/null 2>/dev/null
4447
	else
4448
		_iconExt=`echo "$PBI_DEFAULT_ICON_CHROOT" | awk -F . '{print $NF}'`
4449
		cp "${PBI_DEFAULT_ICON_CHROOT}" "${PBI_HEADERDIR}/pbi_icon.${_iconExt}" >/dev/null 2>/dev/null
4450
	fi
4451

    
4452
	# Check for any gui images
4453
	if [ -e "${PBI_STAGEDIR}/${PBI_GUITOPBANNER}" ] ; then
4454
		cp "${PBI_STAGEDIR}/${PBI_GUITOPBANNER}" "${PBI_HEADERDIR}/top-banner.png"
4455
	fi
4456
	if [ -e "${PBI_STAGEDIR}/${PBI_GUISIDEBANNER}" ] ; then
4457
		cp "${PBI_STAGEDIR}/${PBI_GUISIDEBANNER}" "${PBI_HEADERDIR}/side-banner.png"
4458
	fi
4459

    
4460
	# Save the uname details
4461
	echo "${_osArch}" > "${PBI_HEADERDIR}/pbi_arch"
4462
	echo "${_osRel}" > "${PBI_HEADERDIR}/pbi_fbsdver"
4463
	echo "${PROGVERSION}" > "${PBI_HEADERDIR}/pbi_createver"
4464

    
4465
	# Get the total number of files in the STAGEDIR
4466
	get_filetotal_dir "${PBI_STAGEDIR}"
4467
	echo "${FILETOTAL}" > "${PBI_HEADERDIR}/pbi_archivecount"
4468

    
4469
	# Save a checksum of archive file
4470
	sha256 -q "${PBI_CREATE_ARCHIVE}" > "${PBI_HEADERDIR}/pbi_archivesum"
4471

    
4472
	sign_pbi_files "$PBI_HEADERDIR"
4473
}
4474

    
4475
# Use openssl to sign parts of the pbi header structure and archive 
4476
sign_pbi_files() {
4477
	if [ -z "${PBI_SSLPRIVKEY}" ] ; then return 0 ; fi
4478
	_sf="${1}/pbi_archivesum ${1}/${MOD_PREINS} ${1}/${MOD_POSTINS} ${1}/${MOD_PREREM}"
4479
	for i in $_sf
4480
	do
4481
		openssl dgst -sha1 \
4482
  			-sign ${PBI_SSLPRIVKEY} \
4483
  			-out ${i}.sha1 \
4484
  			${i} >/dev/null 2>/dev/null
4485
	done
4486
}
4487

    
4488
# All the pieces are ready, spit out the final PBI file
4489
mk_output_pbi() {
4490
        if [ -n "${PBI_PROGICON}" -a -e "${PBI_STAGEDIR}/${PBI_PROGICON}" ] ; then
4491
                icon="${PBI_STAGEDIR}/${PBI_PROGICON}"
4492
        else
4493
                icon="${PBI_DEFAULT_ICON_CHROOT}"
4494
        fi
4495

    
4496
	# Set PBI name all lower-case
4497
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
4498
	outfile="${PBI_CREATE_OUTDIR}/${_pbilow}-${PBI_PROGVERSION}-${ARCH}.pbi"
4499

    
4500
	mark1="${PBI_CREATE_OUTDIR}/.pbimark1.$$"
4501
	mark2="${PBI_CREATE_OUTDIR}/.pbimark2.$$"
4502
	echo "
4503
${PBI_SS_ICON}" >$mark1
4504
	echo "
4505
${PBI_SS_ARCHIVE}" >$mark2
4506

    
4507

    
4508
	# DO IT, DO IT NOW!!!
4509
	cat ${PBI_HEADER_ARCHIVE} $mark1 ${icon} $mark2 ${PBI_CREATE_ARCHIVE} > ${outfile}
4510
	sha256 -q ${outfile} > ${outfile}.sha256
4511

    
4512
	echo "Created PBI: ${outfile}"
4513

    
4514
	rm $mark1
4515
	rm $mark2
4516
	rm ${PBI_HEADER_ARCHIVE}
4517
	rm ${PBI_CREATE_ARCHIVE}
4518
}
4519

    
4520
get_filetotal_dir() {
4521
	FILETOTAL="`find ${1} | wc -l | tr -d ' '`"
4522
}
4523

    
4524
pbi_delete_init() {
4525
  	require_root_or_group
4526
	init_tmpdir
4527
	parse_delete_pbi_cmdline "$@"
4528
	do_pbi_delete
4529
}
4530

    
4531
# Delete this PBI
4532
do_pbi_delete() {
4533
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4534
	PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}"
4535

    
4536
	# Unmount the PBI if its mounted
4537
	/usr/pbi/.pbime umount "/usr/pbi/.mounts/`basename $PBI_PROGDIRPATH`"
4538

    
4539
	get_username_from_file "${PBI_DBAPPDIR}/${PBI_DELETENAME}/pbi_name"
4540
	if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
4541
		exit_err "Permission denied to modify PBI installed by: $FILEUSER"
4542
	fi
4543

    
4544
	# Set the dirty flag that we are removing this PBI
4545
	touch ${PBI_DBAPPDIR}/${PBI_DELETENAME}/.pbiDeleted
4546

    
4547
	check_preremove_script
4548
	run_remove_script
4549
 	remove_pbidir
4550
	unregister_pbi
4551
	
4552
	# Mark the hashdir as dirty
4553
	make_hashdir_dirty
4554
}
4555

    
4556
# Save the hash-list to run a cleanup afterwards
4557
pbirm_save_hashlist() {
4558
	if [ "${PBI_DISABLEHASHDIR}" = "YES" ] ; then return 0 ; fi
4559
	if [ -e "${PBI_PROGDIRPATH}/${PBI_HASHLIST}" ] ; then
4560
		PBI_TMPHASHLIST="${PBI_TMPDIR}/.pbi-hash.$$"
4561
		cp ${PBI_PROGDIRPATH}/${PBI_HASHLIST} ${PBI_TMPHASHLIST}
4562
	fi
4563
}
4564

    
4565
# Function which removes all empty dirs from the hash-dir
4566
pbi_clean_emptyhdirs() {
4567
        if [ ! -d "${PBI_HASHDIR}" ] ; then return 0 ; fi
4568
	cd ${PBI_HASHDIR}
4569
	found="0"
4570
	for i in `find . -empty -type d 2>/dev/null`
4571
	do
4572
		if [ "${i}" = "." ] ; then continue ; fi
4573
		if [ -d "${PBI_HASHDIR}/${i}" ] ; then
4574
			rmdir "${PBI_HASHDIR}/${i}"
4575
			found="1"
4576
		fi	
4577
	done
4578

    
4579
	# Run recursively
4580
	if [ "$found" = "1" ];then pbi_clean_emptyhdirs ; fi
4581
}
4582

    
4583
# Read through and clean the given hash-list
4584
pbi_clean_hashlist() {
4585
	if [ -z "${PBI_TMPHASHLIST}" ] ; then return 0 ; fi
4586
	while read hl
4587
	do
4588
		file="`echo $hl | sed 's/:::.*$//g'`"
4589
		hash="`echo $hl | sed 's/^.*::://g'`"
4590
		tfile="${file}:::${hash}"
4591
		if [ -f "${PBI_HASHDIR}/${tfile}" ] ; then
4592
			check_remove_hashfile "${tfile}"
4593
		fi
4594

    
4595
	done < ${PBI_TMPHASHLIST}
4596
	rm ${PBI_TMPHASHLIST}
4597
}
4598

    
4599
# Read through and clean the entire hashdir
4600
pbi_clean_hashdir() {
4601
        if [ ! -d "${PBI_HASHDIR}" ] ; then return 0 ; fi
4602
	echo "Cleaning shared-hash dir..."
4603
	cd ${PBI_HASHDIR}
4604
	tmphashlist="${PBI_TMPDIR}/.pbi-hashdir.$$"
4605
	find * -type f -links 1 > "${tmphashlist}" 2>/dev/null
4606
        while read hl
4607
        do
4608
		if [ ! -f "$hl" -o -h "$hl" ] ; then continue ; fi
4609
                if [ -f "${PBI_HASHDIR}/${hl}" ] ; then
4610
                        check_remove_hashfile "${hl}"
4611
                fi
4612

    
4613
        done < $tmphashlist
4614
        rm "$tmphashlist"
4615
	pbi_clean_emptyhdirs
4616
}
4617

    
4618
# Check if this hash-file is ready to be removed from the hash-dir
4619
check_remove_hashfile() {
4620
	tfile="${PBI_HASHDIR}/${1}"
4621
	get_hard_link_count "${tfile}"
4622
	if [ "$HLINKS" = "1" ] ; then
4623
		if [ "${PBI_VERBOSE}" = "YES" ] ; then 
4624
			echo "Removing unused hashfile: $tfile"
4625
		fi
4626
		rm -f "${tfile}"
4627
	fi
4628
}
4629

    
4630
# Run the removal script for this PBI
4631
run_remove_script() {
4632
	uisc="${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/.pbi-uninstall.sh"
4633
	if [ ! -e "$uisc" ] ; then return 0 ; fi
4634

    
4635
	# If not running as root, be sure to cleanup path links
4636
	if [ "`id -u`" != "0" ]; then
4637
	 	cat ${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT} | grep 'rm "$SYS_LOCALBASE/bin' | sed 's|$SYS_LOCALBASE|${HOME}|g' >${PBI_TMPDIR}/.binlnks
4638
         	while read lnk
4639
          	do
4640
               	 	/bin/sh -c "${lnk}"
4641
          	done <${PBI_TMPDIR}/.binlnks
4642
          	rm ${PBI_TMPDIR}/.binlnks
4643
        fi
4644
        export_script_vars
4645
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4646
       		sh "${uisc}"
4647
	else
4648
       		sh "${uisc}" >/dev/null 2>/dev/null
4649
	fi
4650
}
4651

    
4652
# Function to check the supplied $1 dir for any mounts before we
4653
# do a rm -rf
4654
umount_before_rm()
4655
{
4656
   	if [ -z "${1}" ] ; then return 0 ; fi
4657

    
4658
        local _ddir="$1"
4659
        echo "$_ddir" | rev | grep -q '^/'	
4660
	if [ $? -ne 0 ] ; then
4661
	   _ddir="${_ddir}/"
4662
	fi
4663
	
4664
	mount | grep -q "on ${_ddir}"
4665
	if [ $? -ne 0 ] ; then return 0; fi
4666

    
4667
        for i in `mount | grep "on ${_ddir}" | awk '{print $3}'`
4668
	do
4669
	   umount -f ${i} >/dev/null 2>/dev/null
4670
	   if [ $? -ne 0 ] ; then 
4671
		exit_err "Could not umount ${i} before rm -rf, bailing!"
4672
	   fi
4673
	done
4674
	return 0
4675
}
4676

    
4677
# Remove the pbi directory
4678
remove_pbidir() {
4679
	if [ -z "${PBI_PROGDIRPATH}" ] ; then return 0 ; fi
4680
	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then return 0 ; fi
4681
	if [ "${PBI_PROGDIRPATH}" = "/" ] ; then return 0 ; fi
4682
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4683
		echo "Removing: ${PBI_PROGDIRPATH}"
4684
	fi
4685

    
4686
        # Make sure we are unmounted
4687
        umount_before_rm "${PBI_PROGDIRPATH}"
4688
	
4689
	rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4690

    
4691
	# Do we have leftovers?
4692
	if [ -d "${PBI_PROGDIRPATH}" ] ; then
4693
		chflags -R noschg "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4694
		chmod -R 777 "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4695
		rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4696
	fi
4697
}
4698

    
4699
# Remove this PBI registration
4700
unregister_pbi() {
4701
	if [ -z "${PBI_DBAPPDIR}" ] ; then return 0 ; fi
4702
	if [ -z "${PBI_DELETENAME}" ] ; then return 0 ; fi
4703
	if [ ! -d "${PBI_DBAPPDIR}/${PBI_DELETENAME}" ] ; then return 0 ; fi
4704
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4705
		echo "Removing: ${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4706
	fi
4707
	rm -rf "${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4708

    
4709
}
4710

    
4711
# Check if we have a preinstall script we need to use
4712
check_preremove_script() {
4713
	if [ ! -e "${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}" ] ; then return 0 ; fi
4714

    
4715
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4716
		echo "Running pre-removal script: ${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}"
4717
	fi
4718
        export_script_vars
4719
       	sh "${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}"
4720
}
4721

    
4722
add_app_path_links()
4723
{
4724
	# If root, run the regular path script
4725
	if [ `id -u` = "0" ] ; then
4726
		sh "${1}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" >/dev/null 2>/dev/null
4727
		return
4728
	fi
4729

    
4730
	# Running as user add to ~/bin
4731
	init_tmpdir
4732
	if [ ! -d "${HOME}/bin" ] ; then mkdir -p "${HOME}/bin"; fi
4733
	cat ${1}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT} | grep "${1}/${PBI_FAKEBIN_DIR}" | grep '$PBI_BINDIR' | sed 's|$PBI_BINDIR|${HOME}/bin|g' >${PBI_TMPDIR}/.binlnks
4734
	while read lnk
4735
	do
4736
		/bin/sh -c "${lnk}"
4737
		
4738
	done <${PBI_TMPDIR}/.binlnks
4739
	rm ${PBI_TMPDIR}/.binlnks
4740
	
4741
}
4742

    
4743
del_app_path_links()
4744
{
4745
	# If root, run the regular path script
4746
	if [ `id -u` = "0" ] ; then
4747
		sh "${1}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" >/dev/null 2>/dev/null
4748
		return
4749
	fi
4750

    
4751
	# Running as user remove from ~/bin
4752
	if [ ! -d "${HOME}/bin" ] ; then mkdir -p "${HOME}/bin"; fi
4753
	for lnk in `ls ${1}/${PBI_FAKEBIN_DIR}`
4754
	do
4755
		if [ "$lnk" = "$PBI_INS_PATHSCRIPT" -o "$lnk" = "$PBI_UNINS_PATHSCRIPT" ]
4756
		then
4757
			continue
4758
		fi
4759

    
4760
		if [ ! -e "${HOME}/bin/$lnk" ] ; then continue ; fi
4761
		if [ ! -h "${HOME}/bin/$lnk" ] ; then continue ; fi
4762
			
4763
		ls -al "${HOME}/bin/$lnk" | awk '{print $11}' | grep $1 >/dev/null 2>/dev/null
4764
		if [ "$?" = "0" ] ; then
4765
			rm ${HOME}/bin/$lnk
4766
		fi
4767
	done
4768
	
4769
}
4770

    
4771
pbi_icon_init() {
4772
	parse_icon_pbi_cmdline "$@"
4773
	
4774
	do_pbi_icon
4775
}
4776

    
4777
# Start the PBI icon process
4778
do_pbi_icon() {
4779
	# Get the dir for this PBI
4780
	_appDir=`cat ${PBI_DBAPPDIR}/${PBI_ICONTARGETAPP}/pbi_installedpath`
4781

    
4782
	if [ "${PBI_PATHADD}" = "YES" ] ; then
4783
		add_app_path_links "$_appDir"
4784
	fi
4785
	if [ "${PBI_PATHDEL}" = "YES" ] ; then
4786
		del_app_path_links "$_appDir"
4787
	fi
4788

    
4789
	if [ "${PBI_DESKADD}" = "YES" ] ; then
4790
		if [ ! -e "${_appDir}/.xdg-desktop/${PBI_INS_DESKSCRIPT}" ] ; then 
4791
			exit_err "No desktop icons for this PBI"
4792
		fi
4793
		sh "${_appDir}/.xdg-desktop/${PBI_INS_DESKSCRIPT}"
4794
	fi
4795
	if [ "${PBI_DESKDEL}" = "YES" ] ; then
4796
		if [ ! -e "${_appDir}/.xdg-desktop/${PBI_UNINS_DESKSCRIPT}" ] ; then 
4797
			exit_err "No desktop icons for this PBI"
4798
		fi
4799
		sh "${_appDir}/.xdg-desktop/${PBI_UNINS_DESKSCRIPT}"
4800
	fi
4801
	if [ "${PBI_MENUADD}" = "YES" ] ; then
4802
		require_root_or_group
4803
		if [ ! -e "${_appDir}/.xdg-menu/${PBI_INS_MENUSCRIPT}" ] ; then 
4804
			exit_err "No menu icons for this PBI"
4805
		fi
4806
		sh "${_appDir}/.xdg-menu/${PBI_INS_MENUSCRIPT}"
4807
	fi
4808
	if [ "${PBI_MENUDEL}" = "YES" ] ; then
4809
		require_root_or_group
4810
		if [ ! -e "${_appDir}/.xdg-menu/${PBI_UNINS_MENUSCRIPT}" ] ; then 
4811
			exit_err "No menu icons for this PBI"
4812
		fi
4813
		sh "${_appDir}/.xdg-menu/${PBI_UNINS_MENUSCRIPT}"
4814
	fi
4815
	if [ "${PBI_MIMEADD}" = "YES" ] ; then
4816
		require_root_or_group
4817
		if [ ! -e "${_appDir}/.xdg-mime/${PBI_INS_MIMESCRIPT}" ] ; then 
4818
			exit_err "No mime registration for this PBI"
4819
		fi
4820
		sh "${_appDir}/.xdg-mime/${PBI_INS_MIMESCRIPT}"
4821
	fi
4822
	if [ "${PBI_MIMEDEL}" = "YES" ] ; then
4823
		require_root_or_group
4824
		if [ ! -e "${_appDir}/.xdg-mime/${PBI_UNINS_MIMESCRIPT}" ] ; then 
4825
			exit_err "No mime registration for this PBI"
4826
		fi
4827
		sh "${_appDir}/.xdg-mime/${PBI_UNINS_MIMESCRIPT}"
4828
	fi
4829
}
4830

    
4831
pbid_init() {
4832
	require_root
4833

    
4834
	parse_pbid_cmdline "$@"
4835

    
4836
	do_pbid
4837
}
4838

    
4839
# This is a crude hack, but we need to copy libGL* to a location outside
4840
# of /usr/local for PBIs to be able to access them
4841
check_populate_opengl()
4842
{
4843
  local lG
4844
  for i in `ls /usr/local/lib/libGl.* /usr/local/lib/libGL.* /usr/local/lib/libGLU.* /usr/local/lib/libnvidia-* 2>/dev/null`
4845
  do
4846
    lG=`basename $i`
4847
    cp ${i} /usr/lib/${lG}
4848
  done
4849
}
4850

    
4851
# Start the PBID daemon
4852
do_pbid() {
4853

    
4854
	# Start by sourcing /etc/profile
4855
	# This grabs any HTTP_ / FTP_ PROXY variables
4856
	. /etc/profile
4857

    
4858
	# Allow user supplied logfile
4859
        if [ -z "${PBID_LOGFILE}" ] ; then
4860
	  _pbid_log="/var/log/pbid.log"
4861
	else
4862
          _pbid_log="${PBID_LOGFILE}"
4863
        fi
4864

    
4865
	# Set verbosity 
4866
	_redir="&1"
4867
	if [ "${PBI_VERBOSE}" != "YES" ] ; then _redir="/dev/null" ; fi
4868
	echo "Started pbid: `date`" > ${_pbid_log}
4869

    
4870
	# Check for opengl libs to link
4871
	check_populate_opengl
4872

    
4873
	while
4874
	i=1
4875
	do
4876
		# Do regular sleeps
4877
		qslp=0
4878

    
4879
		# Check if we have any out of date index files to update
4880
		for _dbIndex in `ls ${PBI_DBREPODIR}`
4881
		do
4882
			_iMd5=`echo ${_dbIndex} | cut -d '.' -f 2`
4883
			check_update_index "${_iMd5}"
4884

    
4885
			# If we failed to get an index try again sooner
4886
			# This is useful if the user has just installed and has not setup
4887
			# the network yet. We want to fetch indexes quickly after net
4888
			# comes up so they dont need to wait 15 min for the next check
4889
			if [ ! -e "${PBI_DBINDEXDIR}/${_iMd5}-index" ] ; then qslp=1; fi
4890
		done
4891

    
4892
		# Check if we have a dirty hash-dir to cleanup
4893
		check_clean_hashdir "$_pbid_log" "$_redir"
4894

    
4895
		# Check if we have any PBIs to auto-update
4896
		check_autoupdate_pbis "$_pbid_log" "$_redir"
4897

    
4898
		# Check if we need to merge files into the hashdir
4899
		if [ -n "`ls ${PBI_DBHASHQUEUEDIR}`" ] ; then
4900
			init_tmpdir
4901
			for _hpbi in `ls ${PBI_DBHASHQUEUEDIR}`
4902
			do
4903
				if [ ! -e "${PBI_DBAPPDIR}/${_hpbi}/pbi_installedpath" ] ; then
4904
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4905
					continue
4906
				fi
4907

    
4908
				_hpbipath=""
4909
				_hpbipath=`cat ${PBI_DBAPPDIR}/${_hpbi}/pbi_installedpath`
4910
				if [ ! -e "${_hpbipath}/${PBI_HASHLIST}" ] ; then
4911
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4912
					continue
4913
				fi
4914

    
4915
				# Get the username this PBI was installed as
4916
				get_username_from_file "${_hpbipath}"
4917

    
4918
				# Lets start this hash merge
4919
				echo "Adding ${_hpbipath} to hash-dir ($FILEUSER): `date`" >> ${_pbid_log}
4920

    
4921
				if [ "$FILEUSER" = "root" ];then
4922
					pbi_add_update_hashdir "${_hpbipath}" "${PBI_DBAPPDIR}/${_hpbi}/.pbiDeleted" >${_redir} 2>${_redir}
4923
				else
4924
					# Run hashdir command as a user
4925
					su $FILEUSER -c "pbi_update_hashdir \"${_hpbipath}\" \"${PBI_DBAPPDIR}/${_hpbi}/.pbiDeleted\"" >${_redir} 2>${_redir}
4926
				fi
4927
				echo "Finished adding ${_hpbipath} to hash-dir: `date`" >> ${_pbid_log}
4928
				
4929

    
4930
				inUseDir="/usr/pbi/.mounts/`basename $_hpbipath`/virtbase/dev"
4931
				# If the PBI isn't running, we can remove trigger
4932
				if [ ! -d "$inUseDir" ] ; then
4933
					# Now remove the trigger file
4934
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4935
				fi
4936

    
4937
			done
4938
			rm_tmpdir
4939

    
4940
		fi
4941
		
4942
		# Check if we should rotate the logfile
4943
		_pbidLines=`wc -l ${_pbid_log} | awk '{ print $1 }'`
4944
		if [ $(is_num "$_pbidLines") ] ; then
4945
			if [ $_pbidLines -gt $PBI_LOG_LINES ] ; then
4946
				echo "Logfile turnover: `date`" >${_pbid_log}
4947
			fi
4948
		fi
4949
		
4950

    
4951
		# Done with our check, lets go back to sleep now
4952
		if [ $qslp -eq 1 ] ; then
4953
			sleep 10
4954
		else
4955
			sleep ${PBIDSLEEP}
4956
		fi
4957
	done
4958

    
4959
}
4960

    
4961
# Check if there are any PBIs which are flagged for auto-updates
4962
check_autoupdate_pbis() {
4963

    
4964
	for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
4965
	do
4966
		if [ ! -e "${PBI_DBAPPDIR}/${i}/autoupdate-enable" ] ; then
4967
			continue 
4968
		fi
4969

    
4970
		# Check if this app is already updating
4971
		if [ -e "${PBI_DBAPPDIR}/${i}/.updating" ] ; then
4972
			ps -p `cat ${PBI_DBAPPDIR}/${i}/.updating` >/dev/null 2>/dev/null
4973
			if [ "$?" != "0" ] ; then
4974
				rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
4975
			else
4976
				continue 
4977
			fi
4978
		fi
4979

    
4980
		# Found an auto-update enabled APP, see if it needs upping
4981
		PBI_UPDATEAPP="$i"
4982

    
4983
		# Load the details about this app
4984
		load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4985
		if [ -z "${PBI_REPO}" ]; then
4986
			pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4987
		fi
4988
		if [ -z "${PBI_REPO}" ]; then continue ; fi
4989
		local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
4990

    
4991
		# Does this need an update?
4992
		check_pbi_update "$PBI_UPDATEAPP" "nodisplay" \
4993
			"$PBI_PROGNAME" "current" \
4994
			"$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
4995
		if [ "$?" != "0" ] ; then
4996
			continue
4997
		fi
4998
		
4999
		# Get the username this PBI was installed as
5000
		get_username_from_file "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5001

    
5002
		# Its Update Time!
5003
		echo "Starting Auto-Update of ${PBI_UPDATEAPP} ($FILEUSER): `date`" >>${_pbid_log}
5004

    
5005
		su ${FILEUSER} -c "pbi_update ${PBI_UPDATEAPP}" >>${_pbid_log} 2>>${_pbid_log}
5006
		if [ "$?" = "0" ] ; then
5007
			echo "Success! Update of ${PBI_UPDATEAPP}: `date`" >>${_pbid_log}
5008
		else
5009
			echo "Failed! Update of ${PBI_UPDATEAPP}: `date`" >>${_pbid_log}
5010
		fi
5011

    
5012
		rm "${PBI_DBAPPDIR}/${i}/.updating" >/dev/null 2>/dev/null
5013
	done
5014
}
5015

    
5016
check_clean_hashdir() {
5017
	if [ ! -e "${PBI_DBDIRTYFILE}" ] ; then return ; fi
5018

    
5019
	# Get the date of the last hash-cleaning done
5020
	local _curDate="`cat ${PBI_DBDIRTYFILE}`"
5021
	if [ -e "${PBI_DBDIRTYFILE}.last" ] ; then
5022
		local _lastDate="`cat ${PBI_DBDIRTYFILE}.last`"
5023
	else
5024
		local _lastDate="0"
5025
	fi
5026

    
5027
	# See if we have a new date trigger to do a cleaning
5028
	if [ "$_curDate" = "${_lastDate}" ]; then return; fi
5029

    
5030
	# Loop through and clean any hash-dirs as the appropriate user
5031
	for cHdir in `ls -d ${PBI_HASHDIR}*`
5032
	do
5033
		get_username_from_file "${cHdir}"
5034
		echo "Cleaning hash-dir ($FILEUSER): `date`" >> ${1}
5035
		su ${FILEUSER} -c "pbi_delete --clean-hdir" >>${2} 2>>${2}
5036
		echo "Finished cleaning hash-dir ($FILEUSER): `date`" >> ${1}
5037
		echo "$_curDate" > ${PBI_DBDIRTYFILE}.last 2>/dev/null
5038
	done
5039
}
5040

    
5041
pbi_info_init() {
5042
	parse_info_pbi_cmdline "$@"
5043
	
5044
	do_pbi_info
5045
}
5046

    
5047
# Display information on the PBI / PBIs
5048
do_pbi_info() {
5049

    
5050
	# If we are listing available PBIs via the index file
5051
	if [ "$PBI_INFOINDEX" = "YES" ] ; then
5052
		
5053
		# List the available PBIs from the index
5054
		do_index_listing
5055
		
5056
		exit_trap
5057
	fi
5058

    
5059
	if [ "$PBI_INFONAME" = "--ALL--" ] ; then
5060
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
5061
		do
5062
			if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
5063
				if [ "$PBI_VERBOSE" = "YES" ] ; then
5064
        				load_info_from_dir "${PBI_DBAPPDIR}/${i}"
5065
					get_username_from_file "${PBI_DBAPPDIR}/${i}"
5066
					PBI_INSTALLED_BY=$FILEUSER
5067
					pbi_display_info
5068
					pbi_display_gui "${PBI_DBAPPDIR}/${i}" ""
5069
					echo " "
5070
				else
5071
					echo "${i}"
5072
				fi
5073
			fi
5074
		done
5075
	else
5076
		# Start loading our variables
5077
        	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_INFONAME}"
5078
		get_username_from_file "${PBI_DBAPPDIR}/${PBI_INFONAME}"
5079
		PBI_INSTALLED_BY=$FILEUSER
5080
		pbi_display_info
5081
	fi
5082
}
5083

    
5084
# Read through the master index file and provide listing of available PBIs for installation
5085
do_index_listing()
5086
{
5087
	# Make sure we have a master index
5088
	ls ${PBI_DBINDEXDIR}/* >/dev/null 2>/dev/null
5089
	if [ "$?" != "0" ] ; then return ; fi
5090

    
5091
	for _rIndex in `ls ${PBI_DBINDEXDIR}/*index* | grep -v '.time'`
5092
	do
5093
		_rMd5=`basename ${_rIndex} | sed 's|-index||g'`
5094
		_rDesc=`cat ${PBI_DBREPODIR}/*.${_rMd5} | grep 'Desc: ' | sed 's|Desc: ||g'`
5095
		echo "Current and available PBIs. * = current"
5096
		echo "Repository: $_rDesc"
5097
		echo "----------------------------------------------------------------"
5098

    
5099
		sort "${_rIndex}" | while read _iLine
5100
		do
5101
			PBI_UPNAME="`echo $_iLine | cut -d ':' -f 1`"
5102
			PBI_UPARCH="`echo $_iLine | cut -d ':' -f 2`"
5103
	        	PBI_UPNVER="`echo $_iLine | cut -d ':' -f 3`"
5104
        		PBI_UPSTATUS="`echo $_iLine | cut -d ':' -f 9`"
5105
			pad_var "${PBI_UPNAME}" "30"
5106
			PBI_UPNAME="${PAD_VAR}"
5107
			pad_var "${PBI_UPNVER}" "15"
5108
			PBI_UPNVER="${PAD_VAR}"
5109
			pad_var "${PBI_UPARCH}" "6"
5110
			PBI_UPARCH="${PAD_VAR}"
5111
	
5112
			if [ "$PBI_UPSTATUS" = "current" ] ; then
5113
				echo "$PBI_UPNAME   $PBI_UPNVER	$PBI_UPARCH *"
5114
			fi
5115
			if [ "$PBI_UPSTATUS" = "active" ] ; then
5116
				echo "$PBI_UPNAME   $PBI_UPNVER	$PBI_UPARCH"
5117
			fi
5118
		done
5119
	done
5120

    
5121
}
5122

    
5123
# Function to pad a variable to X spaces
5124
pad_var() {
5125
	local _pVar="$1"
5126
	local _pNum="$2"
5127
	PAD_VAR="`echo \"$_pVar                                                                                    x\" | cut -c 1-$_pNum`"
5128
}
5129

    
5130
# Checks if we have a custom script to run prior to port make
5131
run_pbi_preportmake()
5132
{
5133
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
5134
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
5135
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-portmake.sh" ] ; then return 0 ; fi
5136

    
5137
	export_script_vars
5138

    
5139
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-portmake.sh"
5140
	if [ "$?" != "0" ] ; then
5141
		exit_err "pre-portmake.sh failed!"
5142
	fi
5143
}
5144

    
5145
# Checks if we have a custom script to run prior to port make
5146
run_pbi_postportmake()
5147
{
5148
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
5149
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
5150
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/post-portmake.sh" ] ; then return 0 ; fi
5151

    
5152
	export_script_vars
5153

    
5154
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/post-portmake.sh"
5155
	if [ "$?" != "0" ] ; then
5156
		echo "Warning: post-portmake.sh returned non-0 status!"
5157
	fi
5158
}
5159

    
5160
# Checks if we have a custom script to run prior to pbi create
5161
run_pbi_prepkgscript()
5162
{
5163
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
5164
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
5165
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-pbicreate.sh" ] ; then return 0 ; fi
5166

    
5167
	export_script_vars
5168

    
5169
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-pbicreate.sh"
5170
	if [ "$?" != "0" ] ; then
5171
		echo "Warning: post-portmake.sh returned non-0 status!"
5172
	fi
5173
}
5174

    
5175
# Begins the port make
5176
start_pbi_makeport()
5177
{
5178
  	# Remove any trailing '/'
5179
  	echo $PBI_MAKEPORT | grep -q "/$"
5180
  	if [ $? -eq 0 ] ; then
5181
     		PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
5182
  	fi
5183

    
5184
	do_port_build "${PBI_MAKEPORT}"
5185
}
5186

    
5187
# Prune any ports which aren't required for runtime
5188
start_pbi_prune_ports()
5189
{
5190
	if [ "${PBI_PRUNEBUILDPORTS}" = "NO" ] ; then return ; fi
5191

    
5192
	get_pkgname "${PBI_MAKEPORT}"
5193
	echo "${PKGNAME}" > /.keepports
5194
	make -C "${PORTSDIR}/${PBI_MAKEPORT}" PORTSDIR=${PORTSDIR} package-depends | cut -d: -f1 >> /.keepports
5195

    
5196
	# Do the same for any OTHERPORTS
5197
	for port in ${PBI_MKPORTBEFORE}
5198
	do
5199
                if [ ! -d "${PORTSDIR}/${port}" ] ; then continue ; fi
5200
		get_pkgname "${port}"
5201
		echo "${PKGNAME}" >> /.keepports
5202
		make -C "${PORTSDIR}/${port}" PORTSDIR=${PORTSDIR} package-depends | cut -d: -f1 >> /.keepports
5203
        done
5204

    
5205
	for port in ${PBI_MKPORTAFTER}
5206
	do
5207
                if [ ! -d "${PORTSDIR}/${port}" ] ; then continue ; fi
5208
		get_pkgname "${port}"
5209
		echo "${PKGNAME}" >> /.keepports
5210
		make -C "${PORTSDIR}/${port}" PORTSDIR=${PORTSDIR} package-depends | cut -d: -f1 >> /.keepports
5211
        done
5212

    
5213
	# Don't strip out pkgng
5214
	pkg info pkg >> /.keepports
5215
	
5216
	# Sort and clean the ports
5217
	cat /.keepports | sort | uniq > /.keepports.tmp
5218
	mv /.keepports.tmp /.keepports
5219

    
5220
	# Now remove any unused ports
5221
	for j in `pkg info -a | cut -d " " -f 1`
5222
	do
5223
		grep -q "^${j}" "/.keepports"
5224
		if [ $? -ne 0 ] ; then 
5225
			echo "Removing non-required port: ${j}"
5226
			$PKG_DELETE ${j} 
5227
		fi
5228
	done
5229
}
5230

    
5231
# Get the full package-name for a target port
5232
get_pkgname() {
5233
        name="`pkg info -O ${1} | awk '{print $1}'`"
5234
	PKGNAME="${name}"
5235
}
5236

    
5237
# Make any additional required ports 
5238
start_pbi_mkportbefore()
5239
{
5240
	if [ -z "${PBI_MKPORTBEFORE}" ] ; then return ; fi
5241
	
5242
	for port in ${PBI_MKPORTBEFORE}
5243
	do
5244
		if [ -n "$PBI_PKGNGBUILD" ] ; then
5245
			pkg-static rquery '%v' ${port} >/dev/null 2>/dev/null
5246
			if [ $? -ne 0 ] ; then
5247
				exit_err "No package exists for: ${port}"
5248
			fi
5249
			do_port_build "${port}"
5250
			continue
5251
		fi
5252

    
5253
		if [ ! -d "/usr/ports/${port}" ] ; then
5254
			exit_err "/usr/ports/${port} does not exist!"
5255
		fi
5256
		do_port_build "${port}"
5257
	done
5258

    
5259
}
5260

    
5261
# Make any additional required ports 
5262
start_pbi_mkportafter()
5263
{
5264
	if [ -z "${PBI_MKPORTAFTER}" ] ; then return ; fi
5265
	
5266
	for port in ${PBI_MKPORTAFTER}
5267
	do
5268
		if [ -n "$PBI_PKGNGBUILD" ] ; then
5269
			pkg-static rquery '%v' ${port} >/dev/null 2>/dev/null
5270
			if [ $? -ne 0 ] ; then
5271
				exit_err "No package exists for: ${port}"
5272
			fi
5273
			do_port_build "${port}"
5274
			continue
5275
		fi
5276

    
5277
		# Doing a regular port build
5278
		if [ ! -d "/usr/ports/${port}" ] ; then
5279
			exit_err "/usr/ports/${port} does not exist!"
5280
		fi
5281
		do_port_build "${port}"
5282
	done
5283

    
5284
}
5285

    
5286
# Start pbi_update_hashdir
5287
pbi_update_hashdir_init() {
5288
	pbi_add_update_hashdir "$1" "$2"
5289
}
5290

    
5291
# Start pbi_update processing
5292
pbi_update_init() {
5293

    
5294
  	parse_update_pbi_cmdline "$@"
5295

    
5296
	check_enable_disable_auto
5297

    
5298
	# Stop here if we are just enabling / disabling auto-update
5299
	if [ -n "$PBI_UPENABLEAUTO" ] ; then return 0 ; fi
5300

    
5301
	start_update_checks
5302
	if [ "$?" != "0" ] ; then rm_tmpdir ; exit 1 ; fi
5303

    
5304
	# Stop here if only doing update checks
5305
	if [ -n "${PBI_UPCHECK}" ]; then return 0 ; fi
5306

    
5307
  	require_root_or_group
5308

    
5309
	do_pbi_update
5310
}
5311

    
5312
# Check if we are enabling / disabling auto-updating
5313
check_enable_disable_auto()
5314
{
5315
	if [ -z "$PBI_UPENABLEAUTO" ] ; then return ; fi
5316
	if [ ! -d "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}" ] ; then return ; fi
5317

    
5318
	# Enable / disable auto-updating now
5319
	if [ "$PBI_UPENABLEAUTO" = "YES" ]; then
5320
		touch ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable
5321
	else
5322
		rm ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable >/dev/null 2>/dev/null
5323
	fi
5324
}
5325

    
5326
# Function which checks the digital signature of a PBI to match it to a particular repo
5327
pbi_checksig_repomatch() {
5328
  	if [ `id -u` != "0" ] ; then return ; fi
5329

    
5330
        # See which repo / key this PBI associates to, if any
5331
	check_valid_sigs "${1}"
5332
	if [ "$?" = "0" -a -n "$PBI_VALIDKEYSIG" ] ; then
5333
		_rMd5="`echo ${PBI_VALIDKEYSIG} | cut -d '.' -f 1`"
5334
		echo "$_rMd5" | sed "s|${PBI_DBKEYDIR}/||g" > ${1}/pbi_repo
5335
	fi
5336
}
5337

    
5338
# See if we are checking for updates and do it
5339
start_update_checks() {
5340
	if [ "${PBI_UPCHECK}" != "YES" -a "${PBI_UPCHECK}" != "ALL" ]; then return 0; fi
5341

    
5342
	# Open up the tmpdir
5343
	init_tmpdir
5344

    
5345
	if [ "${PBI_UPCHECK}" = "YES" ] ; then
5346
		load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5347
		if [ -z "${PBI_REPO}" ]; then
5348
			pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5349
		fi
5350
		if [ -z "${PBI_REPO}" ]; then
5351
			return 1
5352
		else
5353
			local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5354
		fi
5355

    
5356
		check_pbi_update "$PBI_UPDATEAPP" "display" \
5357
	 	 "$PBI_PROGNAME" "current" \
5358
	 	 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5359
		return $?
5360
	else
5361
		# Loop and check all PBIs for updates
5362
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
5363
                do
5364
			PBI_REPO=""
5365
                        if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
5366
				load_info_from_dir "${PBI_DBAPPDIR}/${i}"
5367
				if [ -z "${PBI_REPO}" ]; then
5368
					pbi_checksig_repomatch "${PBI_DBAPPDIR}/${i}"
5369
				fi
5370
				if [ -z "${PBI_REPO}" ]; then
5371
					continue
5372
				else
5373
					local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5374
				fi
5375

    
5376
				check_pbi_update "$i" "display" \
5377
				 "$PBI_PROGNAME" "current" \
5378
				 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5379
                        fi
5380
                done
5381
		return 0
5382
	fi
5383

    
5384
}
5385

    
5386
# Check if we need to pull down the updated INDEX file
5387
check_update_index() {
5388

    
5389
	init_tmpdir
5390
	
5391
	local _repoMd5="$1"
5392
	local _rURL=`cat ${PBI_DBREPODIR}/*${_repoMd5} | grep URL: | sed 's|URL: ||g'`
5393

    
5394
	_pbiIndex="${PBI_DBINDEXDIR}/${_repoMd5}-index"
5395
	_pbiMeta="${PBI_DBINDEXDIR}/${_repoMd5}-meta"
5396
	_pbiIndexTime="${_pbiIndex}.time"
5397
	_tmpPbiIndex="${PBI_TMPDIR}/.upcheck$$"
5398
	_tmpPbiMeta="${PBI_TMPDIR}/.upcheck$$"
5399
		
5400
	# Check if its been greater than $PBI_INDEXREFRESH hours since the last update
5401
	if [ -e "${_pbiIndexTime}" ] ; then
5402
		_curTime=`date +%s`
5403
		_oTime=`cat ${_pbiIndexTime}`
5404
		_trigTime=`expr ${PBI_INDEXREFRESH} \* 60 \* 60`
5405
		expr $_curTime - $_oTime >/dev/null 2>/dev/null
5406
		if [ "$?" = "0" ] ; then
5407
			_passed=`expr $_curTime - $_oTime`
5408
			if [ "$_passed" -lt "$_trigTime" ] ; then
5409
				return;
5410
			fi
5411
		fi
5412
		
5413
	fi
5414

    
5415
	if [ "${PBI_VERBOSE}" = "YES" ] ; then
5416
		echo "Updating index ${_pbiIndex}"
5417
		echo "Updating index ${_pbiIndex}: `date`" >> ${_pbid_log}
5418
	fi
5419

    
5420
	# Check that the last char isn't a '/'
5421
	_tmp=`echo ${_rURL} | wc -m | tr -s ' ' | tr -d ' '`
5422
	_tmp2=`expr $_tmp - 1`
5423
	_lastC=`echo ${_tmp} | cut -c ${_tmp2}-${_tmp}`
5424
	if [ "${_lastC}" = "/" ] ; then
5425
		_upURL="`echo ${_rURL} | sed 's|\(.*\).|\1|'`"
5426
	else
5427
		_upURL="${_rURL}"
5428
	fi
5429

    
5430
	fetch -o "${_tmpPbiIndex}.bz2" "${_upURL}/${PBI_INDEXUPFILE}.bz2" >/dev/null 2>/dev/null
5431
	if [ "$?" != "0" ] ; then
5432
		return
5433
	fi
5434

    
5435
	bzip2 -d "${_tmpPbiIndex}.bz2" >/dev/null 2>/dev/null
5436
	if [ "$?" != "0" ] ; then
5437
		return
5438
	fi
5439

    
5440
	# Move the uncompressed file
5441
	mv "${_tmpPbiIndex}" "${_pbiIndex}" >/dev/null 2>/dev/null
5442

    
5443
	# Wait a sec
5444
 	sleep 1
5445

    
5446
	# Now check for an optional meta file update
5447
	fetch -o "${_tmpPbiMeta}.bz2" "${_upURL}/${PBI_METAUPFILE}.bz2" >/dev/null 2>/dev/null
5448
	if [ "$?" = "0" ] ; then
5449
		bzip2 -d "${_tmpPbiMeta}.bz2" >/dev/null 2>/dev/null
5450
		if [ "$?" = "0" ] ; then
5451
			mv "${_tmpPbiMeta}" "${_pbiMeta}" >/dev/null 2>/dev/null
5452
		fi
5453
	fi
5454

    
5455
	# Update the icons for this repos meta file
5456
	update_repo_icons "${_repoMd5}" "${_pbiMeta}"
5457

    
5458
	echo "Finished updating index ${_pbiIndex}: `date`" >> ${_pbid_log}
5459
	if [ "${PBI_VERBOSE}" = "YES" ] ; then
5460
		echo "Finished updating index ${_pbiIndex}"
5461
	fi
5462

    
5463
	# Save the time that we are done
5464
	date +%s > ${_pbiIndexTime}
5465

    
5466
}
5467

    
5468
# Check if we need to update any repository icons
5469
update_repo_icons() {
5470
	_repoMd5="$1"
5471
	_repoMeta="$2"
5472

    
5473
	echo "Updating meta-icons for $_repoMeta: `date`" >> ${_pbid_log}
5474

    
5475
	# Loop through, downloading icons we find
5476
	while read mLine
5477
	do
5478
		# Make sure this is an app / cat
5479
		echo "$mLine" | grep -e "^App=" -e "^Cat=" >/dev/null 2>/dev/null
5480
		if [ "$?" != "0" ] ; then continue ; fi
5481

    
5482
		# Get the icon URL
5483
		echo "$mLine" | grep "^App=" >/dev/null 2>/dev/null
5484
		if [ "$?" = "0" ] ; then
5485
			line=`echo $mLine | sed 's|^App=||g'`
5486
			aIcon=`echo $line | cut -d ';' -f 3`
5487
		else
5488
			line=`echo $mLine | sed 's|^Cat=||g'`
5489
			aIcon=`echo $line | cut -d ';' -f 2`
5490
		fi
5491
		iName=`echo $line | cut -d ';' -f 1`
5492
		ext=`echo $aIcon | sed 's/.*\.//'`
5493
	
5494
		# If we already have this icon, we can skip
5495
		if [ -e "${PBI_DBICONDIR}/${_repoMd5}-${iName}.${ext}" ] ; then
5496
			continue
5497
		fi
5498

    
5499
		# Now fetch the file
5500
		sFile="${PBI_DBICONDIR}/${_repoMd5}-${iName}.${ext}"
5501
		fetch -o "${sFile}" "${aIcon}" >/dev/null 2>/dev/null
5502
		if [ $? -ne 0 ]; then
5503
		  # Wait a moment before trying the next
5504
		  sleep 40 
5505
		fi
5506
		
5507
	done < ${_repoMeta}
5508
}
5509

    
5510
# Check a specific PBI for updates
5511
check_pbi_update() {
5512

    
5513
	# Init the tmpdir
5514
	init_tmpdir
5515

    
5516
	# Set the vars
5517
	_upbi="${1}"
5518
	_udisp="${2}"
5519
	_uprog="${3}"
5520
	_uver="${4}"
5521
	_ufbsdver="${5}"
5522
	_uarch="${6}"
5523
	_urepo="${7}"
5524
	_omdate="${8}"
5525

    
5526
	_uprog="`echo ${_uprog} | tr -d ' '`"
5527
	appname="`echo ${_uprog} | tr '[:lower:]' '[:upper:]'`"
5528

    
5529
	PBI_UPNVER=""
5530
	PBI_UPFILE=""
5531
	PBI_UPPATCHES=""
5532
	PBI_UPCSUM=""
5533
	PBI_UPMDATE=""
5534
	PBI_UPREPO=""
5535
	PBI_UPSIZE=""
5536

    
5537
	# If we are looking for the current app, set _uver accordingly
5538
	if [ "$_uver" = "current" ] ; then
5539
		_uver=":current"
5540
	else
5541
		_uver=":${_uver}:"
5542
	fi
5543

    
5544

    
5545
	for _repo in `ls ${PBI_DBINDEXDIR}`
5546
	do
5547

    
5548
		if [ "$_urepo" = "AUTO" ] ; then
5549
			_pbiIndex="${PBI_DBINDEXDIR}/${_repo}"
5550
			_rMd5="`echo ${_repo} | sed 's|-index||g'`"
5551
		else
5552
			_rMd5=`ls ${PBI_DBREPODIR}/${_urepo}.* | cut -d '.' -f 2`
5553
			_pbiIndex="${PBI_DBINDEXDIR}/${_rMd5}-index"
5554
		fi
5555

    
5556
		if [ ! -e "${_pbiIndex}" ] ; then continue ; fi
5557

    
5558
		# Search the update index for the specified PBI
5559
		_upLine=`grep -i -e "^$_uprog:" ${_pbiIndex} | grep ":$_uarch:" | grep "$_uver" | head -n 1`
5560

    
5561
		PBI_UPNVER="`echo $_upLine | cut -d ':' -f 3`"
5562
		PBI_UPFILE="`echo $_upLine | cut -d ':' -f 6`"
5563
		PBI_UPPATCHES="`echo $_upLine | cut -d ':' -f 8`"
5564
		PBI_UPCSUM="`echo $_upLine | cut -d ':' -f 4`"
5565
		PBI_UPMDATE="`echo $_upLine | cut -d ':' -f 5`"
5566
		PBI_UPSIZE="`echo $_upLine | cut -d ':' -f 8`"
5567
		PBI_UPMIRROR="`cat ${PBI_DBMIRRORDIR}/${_rMd5} 2>/dev/null`"
5568
		PBI_UPREPO="${_rMd5}"
5569

    
5570
		if [ -n "${PBI_UPNVER}" ] ; then break; fi
5571
		if [ "${_urepo}" != "AUTO" ] ; then break; fi
5572

    
5573
	done
5574

    
5575
	# If no new version
5576
	if [ -z "$PBI_UPNVER" ] ; then return 1 ; fi
5577

    
5578
	# See if this update is newer than the installed date
5579
	if [ -n "$_omdate" ] ; then
5580
		nDay=`echo $PBI_UPMDATE | cut -d ' ' -f 1`
5581
	 	nHour=`echo $PBI_UPMDATE | cut -d ' ' -f 2`
5582
	 	oDay=`echo $_omdate | cut -d ' ' -f 1`
5583
	 	oHour=`echo $_omdate | cut -d ' ' -f 2`
5584
         
5585
		# Make sure we have all legit numbers
5586
	 	if [ $(is_num "$nDay") -a $(is_num "$nHour") \
5587
	 		-a $(is_num "$oDay") -a $(is_num "$oHour") ] ; then
5588
	 		if [ $oDay -gt $nDay ] ; then return 1 ; fi
5589
	 		if [ "$oDay" = "$nDay" -a $oHour -gt $nHour ] ; then return 1 ; fi
5590
	 	fi
5591
	fi
5592

    
5593
	if [ "$PBI_UPNVER" != "$PBI_PROGVERSION" ] ; then
5594
		if [ "$_udisp" = "display" ] ; then 
5595
			echo "${_upbi} - Available: ${PBI_UPNVER}"
5596
		fi
5597
		return 0
5598
	else
5599
		return 1
5600
	fi
5601
}
5602

    
5603
# Start PBI update process
5604
do_pbi_update() {
5605
	if [ -n "${PBI_UPCHECK}" ]; then return 0 ; fi
5606

    
5607
	if [ "$PBI_UPDATEAPP" = "ALL" ] ; then
5608
		# Loop and check all PBIs for updates
5609
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
5610
                do
5611
			if [ -e "${PBI_DBAPPDIR}/${i}/.updating" ] ; then
5612
				ps -p `cat ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating` >/dev/null 2>/dev/null
5613
				if [ "$?" = "0" ] ; then
5614
					continue
5615
				fi
5616
				rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5617
			fi
5618
                        if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
5619
				PBI_UPDATEAPP="${i}"
5620
				start_pbi_updateapp "all"
5621
                        fi
5622
		done
5623
	else
5624
		if [ -e "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" ] ; then
5625
			ps -p `cat ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating` >/dev/null 2>/dev/null
5626
			if [ "$?" = "0" ] ; then
5627
				exit_err "This application is currently updating."
5628
			fi
5629
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5630
		fi
5631
		start_pbi_updateapp "single"
5632
		exit $?
5633
	fi
5634
}
5635

    
5636
# Attempt to download a PBI from the update server for "pbi_add -r"
5637
pbi_add_fetch_remote() {
5638
	# Set the target program we want to download
5639
	_rtar="$PBI_FILENAME"
5640
	unset PBI_FILENAME
5641

    
5642
	# Check if the user overrode the arch / versions we want to install
5643
	_rArch=`uname -m`
5644
	if [ -n "$PBI_ADD_ALTARCH" ] ; then _rArch=$PBI_ADD_ALTARCH ; fi
5645

    
5646
	_rVer="current"
5647
	if [ -n "$PBI_ADD_ALTVER" ] ; then _rVer=$PBI_ADD_ALTVER ; fi
5648

    
5649
	check_pbi_update "$_rtar" "nodisplay" \
5650
	 "$_rtar" "$_rVer" \
5651
	 "$FBSDMAJOR" "$_rArch" "${PBI_ADDREPO_ID}"
5652
	if [ "$?" != "0" ] ; then 
5653
		# If we are on amd64, do a fallback check to i386 for this PBI
5654
		# This catches apps like wine / skype and others
5655
		if [ "$_rArch" = "amd64" ] ; then
5656
			_rArch="i386"
5657
			check_pbi_update "$_rtar" "nodisplay" \
5658
	 		"$_rtar" "$_rVer" \
5659
	 		"$FBSDMAJOR" "$_rArch" "${PBI_ADDREPO_ID}"
5660
			if [ "$?" != "0" ] ; then 
5661
				exit_err "Could not find \"$_rtar\" in any indexes" 
5662
			fi
5663
		else
5664
			exit_err "Could not find \"$_rtar\" in any indexes" 
5665
		fi
5666
	fi
5667

    
5668
	# We've gotten this far, now download the updated PBI
5669
	pbi_update_dl
5670
	if [ "$?" != "0" ] ; then
5671
		exit_err "Failed downloading PBI"
5672
	fi
5673

    
5674
	# Now overwrite the PBI_FILENAME and let us proceed to regular install
5675
	PBI_FILENAME="$PBI_UPDLFILE"
5676

    
5677
	# If we are only fetching, finish up now
5678
	if [ "$PBI_REMOTEFETCHONLY" = "YES" ] ; then
5679
		mv $PBI_FILENAME ./`basename ${PBI_UPFILE}`
5680
		echo "PBI saved to ./`basename ${PBI_UPFILE}`"
5681
		exit_trap
5682
	fi
5683

    
5684
}
5685

    
5686
# Update the targed PBI
5687
start_pbi_updateapp() {
5688
	_upact="${1}"
5689
	if [ "$2" = "pbid" ] ; then 
5690
		_pbidlog="$2"
5691
	else
5692
		_pbidlog=""
5693
	fi
5694

    
5695
	echo "$$" > "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5696

    
5697
	# Check for update to this app, and exit or return if not available
5698
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5699
	if [ -z "${PBI_REPO}" ]; then
5700
		pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5701
	fi
5702
	if [ -z "${PBI_REPO}" ]; then
5703
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5704
		return 1
5705
	else
5706
		local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5707
	fi
5708

    
5709
	check_pbi_update "$PBI_UPDATEAPP" "nodisplay" \
5710
	 "$PBI_PROGNAME" "current" \
5711
	 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5712
	if [ "$?" != "0" ] ; then 
5713
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5714
		if [ "$_upact" = "single" ] ; then
5715
			exit_err "$PBI_UPDATEAPP - no update available!"
5716
		else
5717
			return 1
5718
		fi
5719
	fi
5720
	
5721
	
5722
	echo "Starting update of ${PBI_UPDATEAPP} to ${PBI_UPNVER}..."
5723
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
5724

    
5725
	# Check if there is a possible patch file for this update
5726
	# new filename to download
5727
	_pFile="${_pbilow}-${PBI_PROGVERSION}_to_${PBI_UPNVER}-${PBI_APPARCH}.pbp"
5728

    
5729
	# Try downloading the patch file
5730
	echo "Trying update via patchfile..."
5731
	pbi_update_dl "$_pFile" "OFF"
5732
	if [ "$?" = "0" ] ; then
5733
		# We had a good patch download, try applying it now
5734
		echo "Updating via patch file..."
5735
		pbi_patch "$PBI_UPDLFILE" #>/dev/null 2>/dev/null
5736
		if [ "$?" != "0" ] ; then
5737
			# Patching failed, we'll grab a fresh copy next
5738
			echo "Failed to patch with ${_pFile}"
5739
			echo "Will try full file update"
5740
		else
5741
			echo "Patch successful!"
5742
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" >/dev/null 2>/dev/null
5743
			rm "${PBI_UPDLFILE}" >/dev/null 2>/dev/null
5744
			return 0
5745
		fi
5746
			
5747
	fi
5748

    
5749
	# No patch file, grab the full app
5750
	echo "Trying update via full-file..."
5751
	pbi_update_dl 
5752
	if [ "$?" != "0" ] ; then
5753
		if [ "$_upact" = "single" ] ; then
5754
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5755
			exit_err "Failed downloading update!"
5756
		fi
5757
	fi
5758

    
5759
	echo " "
5760

    
5761
	# Save the auto-update status
5762
	if [ -e "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable" ] ; then
5763
		_autoUpEnable="YES"
5764
	else
5765
		_autoUpEnable="NO"
5766
	fi
5767
	
5768
	echo -e "Removing old version...\c"
5769
	pbi_delete "${PBI_UPDATEAPP}"
5770
	echo "Done"
5771

    
5772
	# Now install new PBI
5773
	echo -e "Installing new version...\c"
5774
	pbi_add --licagree -f "$PBI_UPDLFILE" >/dev/null 2>/dev/null
5775
	if [ "$?" != "0" ] ; then
5776
		echo "Failed to install PBI: ${PBI_UPDLFILE}"
5777
		rm "${PBI_UPDLFILE}"
5778
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" 2>/dev/null
5779
		return 1
5780
	else
5781
		if [ "$_autoUpEnable" = "YES" ] ; then
5782
		 	touch "${PBI_DBAPPDIR}/${_pbilow}-${PBI_UPNVER}-${PBI_APPARCH}/autoupdate-enable"
5783
		fi
5784
		echo "Done"
5785
		rm "${PBI_UPDLFILE}"
5786
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" 2>/dev/null
5787
		return 0
5788
	fi	
5789
}
5790

    
5791
# Start downloading the update
5792
pbi_update_dl() {
5793

    
5794
	_tPatch=$1
5795
	local _CKSUM="$2"
5796
	
5797
	# Set local download location
5798
	_dl_loc="${PBI_APPDIR}/.`basename $PBI_UPFILE`"
5799

    
5800
	# Have a patch file to download instead, make that the active file to try
5801
	if [ -n "$_tPatch" ] ; then
5802
		_bDir=`dirname $PBI_UPFILE`
5803
		_uFile="${_bDir}/${_tPatch}"
5804
	else
5805
		_uFile="${PBI_UPFILE}"
5806
	fi
5807

    
5808
	_mirrorList=`echo $PBI_UPMIRROR | sed 's|\n| |g'`
5809

    
5810
	# Start download from repos mirror(s) in order
5811
	for _cMirror in $_mirrorList
5812
	do
5813
		if [ "$_cMirror" = "PCBSDCDN" -o "$_cMirror" = "http://pbi.cdn.pcbsd.org" ] ; then
5814

    
5815
			# Strip the /PBI from the mirror URL
5816
			_uFile="`echo ${_uFile} | sed 's|^/PBI||g'`"
5817
		  	if [ -e "$_dl_loc" ] ; then rm "$_dl_loc" ; fi	
5818

    
5819
			get_file_from_mirrors "${_uFile}" "$_dl_loc" "pbi"
5820
			if [ "$?" != "0" ]  ; then 
5821
				rm "${_dl_loc}" >/dev/null 2>/dev/null
5822
				echo "Download Failed: ${_furl}"
5823
				continue
5824
			fi
5825
		else
5826
			_furl="`echo $_cMirror | sed 's/\/*$//'`${_uFile}"
5827
		  	if [ -e "$_dl_loc" ] ; then rm "${_dl_loc}" ; fi	
5828

    
5829
			echo "Downloading ${_furl}"
5830
			pbi_get_file "$_furl" "$_dl_loc"
5831
			if [ "$?" != "0" ]  ; then 
5832
				rm "${_dl_loc}" >/dev/null 2>/dev/null
5833
				echo "Download Failed: ${_furl}"
5834
				continue
5835
			fi
5836
		fi
5837
		sync
5838
		sleep 1
5839
		_upcsum=`sha256 -q "$_dl_loc"`
5840
		if [ "$_CKSUM" != "OFF" -a "$_upcsum" != "$PBI_UPCSUM" ] ; then
5841
			rm "${_dl_loc}" >/dev/null 2>/dev/null
5842
			echo "Download fails checksum: ${_furl}"
5843
			continue
5844
		fi
5845

    
5846
		# If we get this far, we have a good file!
5847
		PBI_UPDLFILE="$_dl_loc"
5848
		sync
5849
		return 0
5850
	done
5851

    
5852
	return 1
5853
}
5854

    
5855
# Function to download a file from remote using fetch
5856
pbi_get_file() {
5857
	_rf="${1}"
5858
	_lf="${2}"
5859

    
5860
	init_tmpdir
5861
	if [ -e "${_lf}" ] ; then 
5862
		echo "Resuming download of: ${_lf}"
5863
	fi
5864

    
5865
	if [ "$PBI_FETCH_PARSING" != "YES" ] ; then
5866
		fetch -r -o "${_lf}" "${_rf}"
5867
		_err=$?
5868
	else
5869
		# Doing a front-end download, parse the output of fetch
5870
		_eFile="${PBI_TMPDIR}/.fetch-exit.$$"
5871
		fetch -s "${_rf}" > ${PBI_TMPDIR}/.fetch-size.$$ 2>/dev/null
5872
		_fSize=`cat ${PBI_TMPDIR}/.fetch-size.$$ 2>/dev/null`
5873
		_fSize="`expr ${_fSize} / 1024 2>/dev/null`"
5874
		rm "${PBI_TMPDIR}/.fetch-size.$$" 2>/dev/null
5875
		_time=1
5876

    
5877
		( fetch -r -o "${_lf}" "${_rf}" >/dev/null 2>/dev/null ; echo "$?" > ${_eFile} ) &
5878
		FETCH_PID=`ps -auwwwx | grep -v grep | grep "fetch -r -o ${_lf}" | awk '{print $2}'`
5879
		while : 
5880
		do
5881
			if [ -e "${_lf}" ] ; then
5882
				_dSize=`du -k ${_lf} | tr -d '\t' | cut -d '/' -f 1`
5883
				if [ $(is_num "$_dSize") ] ; then
5884
					if [ ${_fSize} -lt ${_dSize} ] ; then _dSize="$_fSize" ; fi
5885
					_kbs=`expr ${_dSize} \/ $_time`
5886
					echo "SIZE: ${_fSize} DOWNLOADED: ${_dSize} SPEED: ${_kbs} KB/s"
5887
				fi
5888
			fi
5889

    
5890
			# Make sure download isn't finished
5891
			ps -p $FETCH_PID >/dev/null 2>/dev/null
5892
			if [ "$?" != "0" ] ; then break ; fi
5893
			sleep 2
5894
			_time=`expr $_time + 2`
5895
		done
5896

    
5897
		_err="`cat ${_eFile}`"
5898
		if [ "$_err" = "0" ]; then echo "FETCHDONE" ; fi
5899
		unset FETCH_PID
5900
	fi
5901

    
5902
	echo ""
5903
	return $_err
5904
}
5905

    
5906
is_num()
5907
{
5908
	expr $1 + 1 2>/dev/null
5909
	return $?
5910
}
5911

    
5912
# Function to check if the port is flagged to only build on specific arch
5913
# Returns 0 for OK, 1 for invalid arch
5914
check_port_compat_arch()
5915
{
5916
	local sPort=$1
5917
        have32="false";
5918
 	local cValues="`make -C $sPort -V ONLY_FOR_ARCHS PORTSDIR=${PORTSDIR}`"
5919
	if [ -z "$cValues" ] ; then return 0 ; fi
5920

    
5921
	for cArch in $cValues
5922
	do
5923
		if [ "$cArch" = "$ARCH" ] ; then return 0; fi
5924
                if [ "$cArch" = "i386" ] ; then have32="true" ; fi
5925
	done
5926
	return 1
5927
}
5928

    
5929
# start processing autobuild
5930
pbi_autob_init() {
5931

    
5932
        require_root
5933

    
5934
        parse_autob_pbi_cmdline "$@"
5935

    
5936
        do_pbi_autob
5937
}
5938

    
5939
check_zfs_ab_destroy()
5940
{
5941
	local bNum=$1
5942
 	if [ -e "${PBI_TMPDIR}/${bNum}.zmnt" ] ; then
5943
 		zDir=`cat ${PBI_TMPDIR}/${bNum}.zmnt`
5944
  		# Make sure this zfs dataset is in the PBI_APPDIR directory
5945
 		echo $zDir | grep -q "${PBI_APPDIR}/" 
5946
	    	if [ $? -eq 0 ] ; then
5947
		  # Make sure all is unmounted
5948
		  umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
5949
		  umount -f ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
5950
	  	  umount -f ${PBI_CHROOTDIR}/usr/ports >/dev/null 2>/dev/null
5951
	 	  umount -f ${PBI_CHROOTDIR}/pkgs >/dev/null 2>/dev/null
5952
		  umount -f ${PBI_CHROOTDIR}/.ccache >/dev/null 2>/dev/null
5953
		  umount -f ${PBI_CHROOTDIR}/usr/wrkdirprefix >/dev/null 2>/dev/null
5954
		  sleep 3
5955
		  umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
5956
		  sync
5957
		  sleep 3
5958
             	  zfs destroy -r "${zDir}"
5959
       	 	  rmdir "${zDir}" >/dev/null 2>/dev/null
5960
		fi
5961
  	fi
5962
}
5963

    
5964
ab_clean_build_tmpfiles()
5965
{
5966
	local build=$1
5967

    
5968
	# Cleanup 
5969
	rm ${PBI_TMPDIR}/${build}.result 2>/dev/null
5970
	rm ${PBI_TMPDIR}/${build}.pid 2>/dev/null
5971
	rm ${PBI_TMPDIR}/${build}.bPort 2>/dev/null
5972
	rm ${PBI_TMPDIR}/${build}.od 2>/dev/null
5973
	rm ${PBI_TMPDIR}/${build}.mp 2>/dev/null
5974
	rm ${PBI_TMPDIR}/${build}.cd 2>/dev/null
5975
	rm ${PBI_TMPDIR}/${build}.pv 2>/dev/null
5976
	rm ${PBI_TMPDIR}/${build}.zmnt 2>/dev/null
5977
}
5978

    
5979
# Start the auto-build traversal process
5980
do_pbi_autob() {
5981

    
5982
	echo "`basename ${0}` started: `date`"
5983

    
5984
	# Prune any outdir files which we don't have modules for
5985
	do_pbi_autob_prune
5986

    
5987
	cd "${PBI_AB_CONFDIR}"
5988
	init_tmpdir
5989

    
5990
	# Get this runs timestamp
5991
	PBI_AB_TIMESTAMP=`date | md5`
5992

    
5993

    
5994
	# Build our list of targets first
5995
	echo "=> Creating build queue list..."
5996
	ab_get_build_list
5997

    
5998
	done=0
5999
	rebuildlist=0
6000
	while :; do
6001
	  activity=0
6002
	  # Start checking each job
6003
	  for build in ${JOBS-$(jot -w %02d ${PBI_AB_BUILDERS})}; do
6004
		# Is this builder running?
6005
		if [ -e "${PBI_TMPDIR}/${build}.pid" ] ; then
6006
			if pgrep -qF "${PBI_TMPDIR}/${build}.pid" >/dev/null 2>&1; then 
6007
				activity=1
6008
				continue; 
6009
			else
6010
		 		# Do the ZFS destroy here if necessary
6011
				check_zfs_ab_destroy "$build"
6012
				
6013
				# Run the post-build process
6014
				ab_post_build ${build}
6015

    
6016
				# Cleanup
6017
				ab_clean_build_tmpfiles ${build}
6018
			fi
6019
		fi
6020
		if [ $done -eq 1 ] ; then continue ; fi
6021

    
6022
		# Builder idle, lets figure out the next build
6023
  		#echo "==> Finding target for build process [$build]"
6024
		start_next_ab_target "$build"
6025
		if [ $? -eq 0 ] ; then 
6026
			# Nothing left to build, lets wait for any existing build to finish before exiting
6027
			done=1
6028
		fi
6029
		activity=1
6030
          done
6031

    
6032
	  # Every 2 hours, we can re-scan the modules directory, catch any ones which may have been added / changed
6033
	  if [ $rebuildlist -eq 7200 ] ; then
6034
	     rebuildlist=0
6035
	     ab_get_build_list
6036
	  else
6037
	     rebuildlist=`expr $rebuildlist + 1`
6038
          fi
6039

    
6040
	  # Wait before checking again
6041
          [ $activity -eq 1 ] && sleep 1
6042
	  # Nothing to do? We can end now
6043
          [ $activity -eq 0 ] && break
6044
	done 
6045

    
6046
	echo "`basename ${0}` Finished: `date`"
6047
};
6048

    
6049
ab_get_build_list()
6050
{
6051

    
6052
   AB_FOUND="0"
6053
   unset CUR_PRIORITY_PBI CUR_WORKING_PBI
6054

    
6055
   # Clear the tmp build list
6056
   rm ${PBI_TMPDIR}/.ablist 2>/dev/null
6057
		
6058
   cd "${PBI_AB_CONFDIR}"
6059
   for pbi in `find . -type f -name "${PBI_CONFFILE}" | grep -v '\.svn' | sort`
6060
   do
6061
	# Figure out the target port for this build
6062
	unset PBI_MAKEPORT PBI_BUILDKEY PBI_PROGVERSION PBI_REQUIRESROOT PBI_PROGNAME PBI_PROGWEB PBI_PROGAUTHOR PBI_PROGICON PBI_MKPORTBEFORE PBI_MKPORTAFTER PBI_MAKEOPTS PBI_EXCLUDELIST PBI_AB_PRIORITY PBI_HASH_EXCLUDES PBI_AB_NOTMPFS PBI_PROGREVISION PBI_AB_NOPKGBUILD
6063

    
6064
	. ${pbi}
6065

    
6066
	_cd=$(dirname $pbi | sed 's|./||')
6067
	PBI_CONFDIR="$_cd"
6068

    
6069
	# Make sure PBI_MAKEPORT is set
6070
	if [ -z "${PBI_MAKEPORT}" ] ; then
6071
		PBI_MAKEPORT=`echo $pbi | sed 's|./||'`
6072
		export PBI_MAKEPORT
6073
	fi	
6074

    
6075
  	# Remove any trailing '/'
6076
  	echo $PBI_MAKEPORT | grep -q "/$"
6077
  	if [ $? -eq 0 ] ; then
6078
     		PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
6079
  	fi
6080
	
6081
	# Check for missing port target
6082
	if [ -z "$PBI_MAKEPORT" ] ; then
6083
		#echo "Warning: Missing PBI_MAKEPORT for ${pbi}"
6084
		continue
6085
	fi
6086

    
6087
 	if [ "$PBI_AB_PKGBUILD" = "YES" -a -z "$PBI_AB_NOPKGBUILD"  ] ; then
6088
		# Doing a package build for this PBI
6089
		pkg-static rquery "%v" ${PBI_MAKEPORT} >/dev/null 2>/dev/null
6090
		if [ $? -ne 0 ] ; then
6091
			echo "No package found for: ${PBI_MAKEPORT}"
6092
			continue
6093
		fi
6094
		PBI_PKGNGBUILD="YES" ; export PBI_PKGNGBUILD
6095

    
6096
	else
6097

    
6098
		# Doing a port build for this PBI
6099
		if [ ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ] ; then 
6100
			#echo "Skipping invalid port ${PORTSDIR}/${PBI_MAKEPORT}"
6101
			continue
6102
		fi
6103

    
6104
		# Check if this port can be built on this architecture
6105
		check_port_compat_arch "${PORTSDIR}/${PBI_MAKEPORT}"
6106
		if [ "$?" = "1" ] ; then
6107
			if [ "$PBI_ABFB32" != "YES" ] ; then
6108
				echo "${PBI_MAKEPORT} - Skipping for invalid system arch"
6109
				continue
6110
			fi
6111
			if [ "$have32" != "true" ] ; then
6112
				echo "${PBI_MAKEPORT} - Skipping for invalid system arch"
6113
				continue
6114
			fi
6115
		fi
6116
		unset PBI_PKGNGBUILD
6117

    
6118
	fi
6119

    
6120
	# Check if another builder is already doing this port
6121
	pBuilding=0
6122
	for p in `ls ${PBI_TMPDIR}/*.bPort 2>/dev/null`
6123
	do
6124
		if [ "`cat $p`" = "$PBI_MAKEPORT" ] ; then
6125
			pBuilding=1
6126
			break
6127
		fi
6128
	done
6129
	if [ $pBuilding -eq 1 ] ; then
6130
		continue
6131
	fi
6132

    
6133
	check_ab_needed "$PBI_MAKEPORT" "${PBI_BUILDKEY}" "$_cd" "$PBI_AB_TIMESTAMP"
6134
 	if [ "$?" = "0" ] ; then	
6135
	   AB_FOUND="1"
6136

    
6137
 	   # Unset the priority if set to 00 / 0
6138
           if [ "${PBI_AB_PRIORITY}" = "00" -o "${PBI_AB_PRIORITY}" = "0" ] ; then 
6139
	   	unset PBI_AB_PRIORITY
6140
           fi
6141

    
6142
	   # Check the priority of this PBI, see if it rises to the top
6143
	   if [ -z "${CUR_PRIORITY_PBI}" ] ; then 
6144
	     CUR_WORKING_PBI="${pbi}"
6145
	     if [ -z "$PBI_AB_PRIORITY" ] ; then 
6146
                     CUR_PRIORITY_PBI="$internal_ab_priority"
6147
             else
6148
                     CUR_PRIORITY_PBI=`expr $PBI_AB_PRIORITY + 10`
6149
             fi
6150
	     #echo "Setting higher priority target: ${pbi} - Priority: ${CUR_PRIORITY_PBI}"
6151
   	     echo "${CUR_PRIORITY_PBI} $pbi" >> ${PBI_TMPDIR}/.abtmp
6152
             continue
6153
           fi
6154

    
6155
	   # Bump up the supplied AB priority
6156
	   if [ -n "${PBI_AB_PRIORITY}" ] ; then 
6157
              internal_ab_priority=`expr $PBI_AB_PRIORITY + 10`
6158
	   fi
6159

    
6160
	   # Check if this PBI is a higher priority
6161
	   if [ $CUR_PRIORITY_PBI -lt $internal_ab_priority ] ; then
6162
	     #echo "Setting higher priority target: ${pbi} - Priority: ${internal_ab_priority}"
6163
	     CUR_WORKING_PBI="${pbi}"
6164
             CUR_PRIORITY_PBI="$internal_ab_priority"
6165
   	     echo "${internal_ab_priority} $pbi" >> ${PBI_TMPDIR}/.abtmp
6166
	     continue
6167
	   else 
6168
	     echo "${internal_ab_priority} $pbi" >> ${PBI_TMPDIR}/.abtmp
6169
	   fi
6170
	   continue
6171
  	 fi
6172

    
6173
  done
6174

    
6175
  # Sort the list
6176
  if [ -e "${PBI_TMPDIR}/.abtmp" ] ; then
6177
    sort -n -r ${PBI_TMPDIR}/.abtmp > ${PBI_TMPDIR}/.ablist
6178
    rm ${PBI_TMPDIR}/.abtmp
6179
  fi
6180
}
6181

    
6182
start_next_ab_target()
6183
{
6184
  local curBuilder="$1"
6185
  # No list to parse?
6186
  if [ ! -e "${PBI_TMPDIR}/.ablist" ] ; then return 0; fi
6187

    
6188
  # Get the last on the list
6189
  CUR_WORKING_PBI=`cat ${PBI_TMPDIR}/.ablist | head -1 | cut -d ' ' -f 2`
6190
  if [ -z "${CUR_WORKING_PBI}" ] ; then return 0; fi
6191

    
6192
  cd "${PBI_AB_CONFDIR}"
6193

    
6194
  # We have something to build lets do it!
6195
  pbi="$CUR_WORKING_PBI"
6196
  unset PBI_MAKEPORT PBI_BUILDKEY PBI_PROGVERSION PBI_REQUIRESROOT PBI_PROGNAME PBI_PROGWEB PBI_PROGAUTHOR PBI_PROGICON PBI_MKPORTBEFORE PBI_MKPORTAFTER PBI_MAKEOPTS PBI_EXCLUDELIST PBI_AB_PRIORITY PBI_HASH_EXCLUDES PBI_AB_NOTMPFS PBI_PROGREVISION PBI_AB_NOPKGBUILD PBI_PKGNGBUILD
6197
  . ${pbi}
6198

    
6199
  _cd=$(dirname $pbi | sed 's|./||')
6200
  PBI_CONFDIR="$_cd"
6201

    
6202
  if [ -z "${PBI_MAKEPORT}" ] ; then
6203
     PBI_MAKEPORT=$(dirname $pbi | sed 's|./||')
6204
  fi	
6205

    
6206
  # Remove any trailing '/'
6207
  echo $PBI_MAKEPORT | grep -q "/$"
6208
  if [ $? -eq 0 ] ; then
6209
    PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
6210
  fi
6211

    
6212
  # Get the prog version
6213
  get_pbi_progversion
6214

    
6215
  if [ "$PBI_AB_PKGBUILD" = "YES" -a -z "$PBI_AB_NOPKGBUILD"  ] ; then
6216
     ttag="package"
6217
  else
6218
     ttag="source"
6219
  fi
6220

    
6221
  echo "==> Starting $ttag build [$curBuilder]: $PBI_MAKEPORT"
6222
  echo "$PBI_MAKEPORT" >${PBI_TMPDIR}/${curBuilder}.bPort
6223

    
6224
  # Remove this from the queue
6225
  cat ${PBI_TMPDIR}/.ablist | tail -n +2 > ${PBI_TMPDIR}/.abtmp
6226
  mv ${PBI_TMPDIR}/.abtmp ${PBI_TMPDIR}/.ablist
6227

    
6228
  # Start the build now
6229
  start_ext_ab "$PBI_MAKEPORT" \
6230
  "${PBI_BUILDKEY}" "${PBI_PROGVERSION}" \
6231
  "${_cd}" "${PBI_AB_OUTDIR}" "${PBI_AB_TIMESTAMP}" "${curBuilder}"
6232

    
6233
  return 1
6234
};
6235

    
6236
# Prune any outdir files which don't have matching modules
6237
do_pbi_autob_prune() {
6238
	if [ "${PBI_AB_PRUNE}" != "YES" ] ; then return 0 ; fi
6239

    
6240
	echo "=> Cleaning outgoing directory..."
6241
    	# Prune outgoing dirs which don't have matching modules anymore
6242
	cd "${PBI_AB_OUTDIR}"
6243
	for i in `find . -type d | grep -v '\.svn'`
6244
	do
6245
		if [ "${i}" = "." -o "${i}" = ".." ] ; then continue ; fi
6246
		_pDir=`dirname ${i}`
6247
		if [ -d "${i}" -a -n "${i}" ] ; then
6248
    			if [ ! -e "${PBI_AB_CONFDIR}/${_pDir}" ] ; then
6249
      			# Not in our module tree anymore, remove it
6250
      			echo "Auto-Prune: ${PBI_AB_OUTDIR}/${_pDir}"
6251
      			rm -rf "${PBI_AB_OUTDIR}/${_pDir}"
6252
    			fi
6253
  		fi
6254
	done
6255
	cd
6256
}
6257

    
6258
# Start the pbi_makeport process
6259
start_ext_ab() {
6260
	_mp="${1}"
6261
	_bk="${2}"
6262
	_pv="${3}"
6263
	_cd="${4}"
6264
	_od="${5}/${_cd}"
6265
	local _abkey="$6"
6266
	local eBuilder="$7"
6267
	_flags=""
6268
	_flags="-c ${_cd} -d ${PORTSDIR} -o ${_od} --delbuild"
6269
	if [ -n "${PBI_AB_SSLPRIVKEY}" ] ; then
6270
		_flags="${_flags} --sign ${PBI_AB_SSLPRIVKEY}"
6271
	fi
6272

    
6273
	# Check if we need to enable tmpfs
6274
 	if [ "$PBI_AB_TMPFS" = "YES" ] ; then
6275
		if [ -z "${PBI_AB_NOTMPFS}" -o "$PBI_AB_NOTMPFS" != "YES" ] ; then
6276
		   	_flags="${_flags} --tmpfs"
6277
		fi
6278
	fi
6279

    
6280
	# Check if we need to enable pkgbuilding
6281
 	if [ "$PBI_AB_PKGBUILD" = "YES" -a -z "$PBI_AB_NOPKGBUILD"  ] ; then
6282
		_flags="${_flags} --pkgbuild"
6283
	fi
6284

    
6285
	# Are we doing 32bit builds?
6286
 	if [ "$PBI_AB32" = "YES" ] ; then _flags="${_flags} -32"; fi
6287

    
6288
        # Check if this port can be built on this architecture
6289
        check_port_compat_arch "${PORTSDIR}/${_mp}"
6290
        if [ $? -ne 0 ] ; then
6291
           if [ "$PBI_ABFB32" = "YES" -a "$have32" = "true" ] ; then
6292
 	      _flags="${_flags} -32"
6293
           fi
6294
        fi
6295

    
6296
	get_pbi_progversion
6297

    
6298
	#echo "Starting build of ${_mp} - ${_pv}"
6299
	#echo "pbi_makeport ${_flags} ${_mp}"
6300

    
6301
	if [ ! -d "${_od}" ] ; then mkdir -p "${_od}" ; fi
6302

    
6303
	# Save the autobuild hash key
6304
	echo "$_abkey" > ${_od}/.abkey
6305
	
6306
	# Save the build key for this PBI
6307
	if [ -n "$_bk" ] ; then
6308
		echo "$_bk" > "${_od}/pbi-buildkey"
6309
	else
6310
		echo "__NONE__" > "${_od}/pbi-buildkey"
6311
	fi
6312

    
6313
	# Clean old log files
6314
	if [ -e "${_od}/build.log" ] ; then
6315
		rm "${_od}/build.log"
6316
	fi
6317
	if [ -e "${_od}/build.log.bz2" ] ; then
6318
		rm "${_od}/build.log.bz2"
6319
	fi
6320

    
6321
	# Move old PBIs to archived folder
6322
        oldVersion=`cat ${_od}/pbi-version 2>/dev/null`
6323
	if [ "$oldVersion" != "$PBI_PROGVERSION" ]; then
6324
		#echo "Archiving old PBIs..."
6325
		archive_old_pbis "${_od}" "$PBI_AB_ARCHIVENUM"
6326
	fi
6327

    
6328
	# Set some variables we can call in pbi_makeport
6329
	PBI_AB_TMPDIR="${PBI_TMPDIR}"
6330
	PBI_AB_BUILDER="$eBuilder"
6331
	export PBI_AB_TMPDIR PBI_AB_BUILDER
6332

    
6333
	# Add some header info to log file
6334
	echo "Starting build: `date`" >${_od}/build.log
6335
	echo "Build Command:" >>${_od}/build.log
6336
	echo "pbi_makeport ${_flags} ${_mp}" >>${_od}/build.log
6337
	echo "------------------------------------------------------" >>${_od}/build.log
6338
	
6339
	echo "${_od}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.od"
6340
	echo "${_mp}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.mp"
6341
	echo "${_cd}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.cd"
6342
	echo "${PBI_PROGVERSION}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.pv"
6343
	pbi_makeport ${_flags} ${_mp} >>${_od}/build.log 2>>${_od}/build.log &
6344
  	echo "$!" > ${PBI_TMPDIR}/${eBuilder}.pid
6345

    
6346
}
6347

    
6348
ab_post_build() 
6349
{
6350
	local build=$1
6351
	_od="`cat ${PBI_TMPDIR}/${build}.od`"
6352
	_mp="`cat ${PBI_TMPDIR}/${build}.mp`"
6353
	_cd="`cat ${PBI_TMPDIR}/${build}.cd`"
6354
	_pv="`cat ${PBI_TMPDIR}/${build}.pv`"
6355
	sleep 1
6356

    
6357
	if [ -e "${PBI_TMPDIR}/${build}.result" -a "`cat ${PBI_TMPDIR}/${build}.result`" = "0" ] ; then
6358

    
6359
		echo "===> Build of ${_mp} was successfull! [$build]"
6360

    
6361
		echo "$_pv" > "${_od}/pbi-version"
6362
		echo "OK" > "${_od}/pbi-result"
6363

    
6364
		# Save the mdate file
6365
		date "+%Y%m%d %H%M%S" >${_od}/pbi-mdate
6366

    
6367
		if [ -n "${PBI_AB_HELPS}" ] ; then
6368
			${PBI_AB_HELPS} "OK" "${_od}"
6369
		fi
6370

    
6371
		# Copy over a description file
6372
		if [ -e "${PORTSDIR}/${_mp}/pkg-descr" ] ; then
6373
			cp "${PORTSDIR}/${_mp}/pkg-descr" "${_od}/pbi-descr"
6374
		fi
6375
		if [ -e "${PBI_AB_CONFDIR}/${_cd}/pbi-descr" ] ; then
6376
			cp "${PBI_AB_CONFDIR}/${_cd}/pbi-descr" "${_od}/pbi-descr"
6377
		fi
6378

    
6379
		# Check if we need to rebuild patches
6380
		if [ "$PBI_AB_GENPATCH" = "YES" -a -d "${_od}/archived" ] ; then
6381
			echo "===> Generating patches for [$build]"
6382
			gen_pbi_patches "${_od}" "${_od}/archived"
6383
		fi
6384

    
6385
		rm "${_od}/build.log.bz2" >/dev/null 2>/dev/null
6386
		bzip2 "${_od}/build.log"
6387

    
6388
	else
6389
		echo "===> Build of ${_mp} failed! [$build]"
6390
		echo "Failed" > "${_od}/pbi-result"
6391
		if [ -n "${PBI_AB_HELPS}" ] ; then
6392
			${PBI_AB_HELPS} "FAILED" "${_od}"
6393
		fi
6394
	fi
6395

    
6396
}
6397

    
6398
# Function which begins to generate patch files from archived PBIs to current
6399
gen_pbi_patches()
6400
{
6401
	_curPBIdir="$1"
6402
	_oldPBIdir="$2"
6403

    
6404
	_curPBI=`ls ${_curPBIdir}/*.pbi 2>/dev/null`
6405

    
6406
	# First remove any old patches
6407
	rm ${_curPBIdir}/*.pbp 2>/dev/null
6408
	rm ${_curPBIdir}/*.pbp.sha256 2>/dev/null
6409

    
6410
	# Make sure to enable signing of the patch files
6411
	if [ -n "${PBI_AB_SSLPRIVKEY}" ] ; then
6412
        	local _mpflags="-o $_curPBIdir --sign ${PBI_AB_SSLPRIVKEY}"
6413
	else
6414
		local _mpflags="-o $_curPBIdir"
6415
	fi
6416

    
6417
	# Check if we need to enable tmpfs
6418
 	if [ "$PBI_AB_TMPFS" = "YES" ] ; then _mpflags="${_mpflags} --tmpfs" ; fi
6419

    
6420
	# Build a list of old PBIs we need to make patches from
6421
	for _oPBI in `ls ${_oldPBIdir}/*.pbi 2>/dev/null`
6422
	do
6423
		# Make sure we don't try to make a patch of identical files
6424
	  	if [ "`basename $_oPBI`" != "`basename $_curPBI`" ] ; then	
6425
			#echo "Building pbp patch of ${_oPBI} -> ${_curPBI}"
6426
			pbi_makepatch $_mpflags "$_oPBI" "$_curPBI" >/dev/null 2>/dev/null
6427
			if [ "$?" != "0" ] ; then
6428
				echo "pbi_makepatch: Failed creating patchfile for $_oPBI -> $_curPBI"
6429
			fi
6430
		 	
6431
		fi
6432
	done
6433
}
6434

    
6435
# Function which compares two PBIs, and creates a .pbp file from the differences 
6436
make_pbi_patchfile()
6437
{
6438
	_pbiNew="$1"
6439
	_pbiOld="$2"
6440
	_cDir="$3"
6441

    
6442
	init_tmpdir
6443

    
6444
        # Load all the information about this PBI / PBP
6445
	PBI_FILENAME="$1"
6446
        load_info_from_header
6447

    
6448
	_pbiNewDir="${PBI_APPDIR}/.newPBI-$$"
6449
	_pbiOldDir="${PBI_APPDIR}/.oldPBI-$$"
6450
	_pbiPatchDir="${PBI_APPDIR}/.patchPBI-$$"
6451
	_pbiPatchHeaderDir="${PBI_APPDIR}/.patchPBIHeaderDir-$$"
6452
	_pbiPatchArchiveFile="${PBI_APPDIR}/.patchPBIArchive-$$"
6453
	_pbiPatchHeaderFile="${PBI_APPDIR}/.patchPBIHeaderFile-$$"
6454

    
6455
	# Get the PBI Versions
6456
	get_ver_from_pbi_file "$_pbiNew"
6457
	_pbiNewVer="$VAL"
6458
	get_ver_from_pbi_file "$_pbiOld"
6459
	_pbiOldVer="$VAL"
6460

    
6461
	# Get the PBI directory names
6462
	get_prefix_from_pbi_file "$_pbiNew"
6463
	_pbiNewPrefix="`basename $VAL`"
6464
	get_prefix_from_pbi_file "$_pbiOld"
6465
	_pbiOldPrefix="`basename $VAL`"
6466

    
6467
	# Get the mdate of the old PBI
6468
	get_mdate_from_pbi_file "$_pbiOld"
6469
	_pbiOldMDate="$VAL"
6470

    
6471
	# Sanity check these prefixes
6472
	if [ "${_pbiNewPrefix}" != "${_pbiOldPrefix}" ] ; then
6473
		echo "Error: Prefix mismatch between $_pbiNew and $_pbiOld"
6474
		return
6475
	fi
6476

    
6477
	# Get the arch type
6478
	get_arch_from_pbi_file "$_pbiNew"
6479
	_pbiNewArch="$VAL"
6480
	get_arch_from_pbi_file "$_pbiOld"
6481
	_pbiOldArch="$VAL"
6482

    
6483
	# Sanity check these system types
6484
	if [ "${_pbiNewArch}" != "${_pbiOldArch}" ] ; then
6485
		echo "Error: Arch mismatch between $_pbiNew and $_pbiOld"
6486
		return
6487
	fi
6488

    
6489
	# Make our extraction directories
6490
	if [ -e "$_pbiNewDir" ] ; then rm -rf "$_pbiNewDir"; fi
6491
	if [ -e "$_pbiOldDir" ] ; then rm -rf "$_pbiOldDir"; fi
6492
	if [ -e "$_pbiPatchDir" ] ; then rm -rf "$_pbiPatchDir"; fi
6493
	mkdir -p "$_pbiNewDir"
6494
	mkdir -p "$_pbiOldDir"
6495
	mkdir -p "$_pbiPatchDir"
6496

    
6497
	# If using tmpfs to speed up patch process
6498
        if [ "$PBI_MP_TMPFS" = "YES" ] ; then
6499
		mount -t tmpfs tmpfs "${_pbiNewDir}"
6500
		mount -t tmpfs tmpfs "${_pbiOldDir}"
6501
		mount -t tmpfs tmpfs "${_pbiPatchDir}"
6502
	fi
6503

    
6504
	local _opts="-e --licagree"
6505
	if [ "${PBI_SKIPSIGVERIFY}" = "YES" ] ; then
6506
		_opts="${_opts} --no-checksig"
6507
	fi
6508

    
6509
	# Extract the two PBIs
6510
	echo "Extracting PBI: $_pbiNew"
6511
	pbi_add ${_opts} -o "${_pbiNewDir}" "${_pbiNew}" >/dev/null 2>/dev/null
6512
	echo "Extracting PBI: $_pbiOld"
6513
	pbi_add ${_opts} -o "${_pbiOldDir}" "${_pbiOld}" >/dev/null 2>/dev/null
6514

    
6515
	if [ ! -d "${_pbiNewDir}/${_pbiNewPrefix}" -o ! -d "${_pbiOldDir}/${_pbiOldPrefix}" ] ; then 
6516
		exit_err "Failed Extracting PBIs for comparision!"
6517
	fi
6518

    
6519
	# Get a list of files which are removed in the new PBI vs the old
6520
	gen_rem_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
6521
	_rFileList="$VAL"
6522
	if [ -n "$_rFileList" ] ; then
6523
		echo "Saving removed file list..."
6524
		mv "${_rFileList}" ${_pbiPatchDir}/PBI-rmList
6525
	fi
6526

    
6527
	# Get archive of files/dirs which are new to the PBI
6528
	gen_newfile_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
6529
	_nFileList="$VAL"
6530
	if [ -n "$_nFileList" ] ; then
6531
		echo "Saving new files archive..."
6532
		tar cf "$_pbiPatchDir/PBI-newFiles.tar" \
6533
			-C "$_pbiNewDir/$_pbiNewPrefix" -T "$_nFileList" >/dev/null 2>/dev/null
6534
		rm "$_nFileList"
6535
	fi
6536

    
6537
	# Get a listing of permissions
6538
	gen_chmod_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
6539
	_cFileList="$VAL"
6540
	if [ -n "$_cFileList" ] ; then
6541
		echo "Saving permissions list..."
6542
		mv "${_cFileList}" ${_pbiPatchDir}/PBI-permList
6543
	fi
6544

    
6545
	# Generate diffs of files which have changed between the two
6546
	gen_bsdiffs_dirs "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix" "$_pbiPatchDir"
6547

    
6548
	# Make the file archive
6549
	if test_tar_lzma ; then _tcmp="J" ; else _tcmp="j" ; fi
6550
	echo "Creating compressed archive..."
6551
	tar c${_tcmp}f "${_pbiPatchArchiveFile}" -C ${_pbiPatchDir} . 2>/dev/null
6552

    
6553
	# Make the header file
6554
	if [ -e "$_pbiPatchHeaderDir" ] ; then rm -rf "$_pbiPatchHeaderDir"; fi
6555
	mkdir -p "$_pbiPatchHeaderDir"
6556
	open_header_tmp "${PBI_TMPDIR}"
6557
  	cp ${PBI_HEADER_TMPDIR}/* "$_pbiPatchHeaderDir/"
6558

    
6559
	# Save the mdate of the old PBI
6560
	echo "$_pbiOldMDate" > $_pbiPatchHeaderDir/pbi_patchmdate
6561

    
6562
	# Remove any signatures
6563
  	rm $_pbiPatchHeaderDir/*.sha1 >/dev/null 2>/dev/null
6564

    
6565
	# Get the archive checksum
6566
	sha256 -q "${_pbiPatchArchiveFile}" > "${_pbiPatchHeaderDir}/pbi_archivesum"
6567
	
6568
	# Set the tag that this is a patch file
6569
	echo "${_pbiOldVer}:${_pbiNewVer}" > "${_pbiPatchHeaderDir}/pbi_patchfile"
6570
	
6571
	# Sign the files if necessary
6572
	sign_pbi_files "${_pbiPatchHeaderDir}"
6573

    
6574
	# Make the header tmpfile
6575
	tar cjf "${_pbiPatchHeaderFile}" -C ${_pbiPatchHeaderDir} . 2>/dev/null
6576
	if [ "$?" != "0" ] ; then
6577
		echo "Warning: TAR returned error creating header archive!"
6578
	fi
6579
	rm -rf ${_pbiPatchHeaderDir} 
6580
	
6581
	# Make the pbp file
6582
	get_progname_from_pbi_file "$_pbiNew"
6583
        _pbilow="`echo ${VAL} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
6584
        
6585
        outfile="${_cDir}/${_pbilow}-${_pbiOldVer}_to_${_pbiNewVer}-${_pbiNewArch}.pbp"
6586
        mark1="${_cDir}/.pbimark1.$$"
6587
        mark2="${_cDir}/.pbimark2.$$"
6588
        
6589
        echo "
6590
${PBI_SS_ICON}" >$mark1
6591
        echo "
6592
${PBI_SS_ARCHIVE}" >$mark2
6593
                
6594
        # DO IT, DO IT NOW!!!
6595
        cat ${_pbiPatchHeaderFile} $mark1 ${PBI_PATCH_ICON} $mark2 ${_pbiPatchArchiveFile} > ${outfile}
6596
        sha256 -q ${outfile} > ${outfile}.sha256
6597

    
6598
	# Cleanup the archive stuff
6599
        rm $mark1
6600
        rm $mark2
6601
        rm ${_pbiPatchHeaderFile}
6602
        rm ${_pbiPatchArchiveFile}
6603
	
6604
	# Cleanup the directories
6605
	rm_pbipatchfiles
6606

    
6607
	# Do some smell testing, make sure the patch file isn't larger than the PBI itself
6608
	# This happens with some java programs occasionally
6609
	if [ `du -k ${outfile} | awk '{print $1}'` -gt `du -k ${_pbiNew} | awk '{print $1}'` ]; then
6610
		rm ${outfile}
6611
		rm ${outfile}.sha256
6612
		exit_err "The patch is larger than the new PBI, aborting!"
6613
	else
6614
		# We have a patch!
6615
           	echo "Created PBP: ${outfile}"
6616
	fi
6617

    
6618

    
6619
}
6620

    
6621
# Function which compares two directories, and returns a list of chmod commands to get them in line
6622
gen_chmod_list() {
6623

    
6624
	_chList="${PBI_TMPDIR}/.pbi.chList.$$"
6625
	if [ -e "$_chList" ] ; then rm "$_chList" ; fi
6626

    
6627
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6628

    
6629
	echo "Getting permissions of changed files..."
6630

    
6631
	while read line
6632
	do
6633
		# Make sure this file exists in the new / old dirs
6634
		if [ -z "$line" ] ; then continue ; fi
6635
		if [ ! -f "${1}/$line" ] ; then continue ; fi
6636
		if [ ! -e "${2}/$line" ] ; then continue ; fi
6637

    
6638
		# Filter out any special files, we don't need diffs of them
6639
		if [ -L "${1}/$line" ] ; then continue ; fi
6640
		if [ -p "${1}/$line" ] ; then continue ; fi
6641
		if [ -S "${1}/$line" ] ; then continue ; fi
6642
		if [ -d "${1}/$line" ] ; then continue ; fi
6643
		if [ -b "${1}/$line" ] ; then continue ; fi
6644
		if [ -c "${1}/$line" ] ; then continue ; fi
6645

    
6646
		_newPerm=`stat -f %Op "${1}/$line"  | cut -c 3-6`
6647
		_oldPerm=`stat -f %Op "${1}/$line"  | cut -c 3-6`
6648
		if [ "$_newPerm" != "$_oldPerm" ] ; then
6649
			# We have new permissions! Lets be sure to save them
6650
			echo "chmod $_newPerm $line" >> $_chList
6651
		fi
6652

    
6653
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6654

    
6655
	# Remove the tmp list files
6656
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6657

    
6658
	if [ -e "$_chList" ] ; then
6659
		VAL="$_chList"
6660
	else
6661
		VAL=""
6662
	fi
6663
}
6664

    
6665

    
6666

    
6667
# Function which compares two directories, and returns a list of files / dirs removed in the new dir
6668
gen_bsdiffs_dirs() {
6669

    
6670
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6671

    
6672
	echo "Getting bsdiffs of changed files..."
6673

    
6674
	while read line
6675
	do
6676
		# Make sure this file exists in the new / old dirs
6677
		if [ -z "$line" ] ; then continue ; fi
6678
		if [ ! -f "${1}/$line" ] ; then continue ; fi
6679
		if [ ! -e "${2}/$line" ] ; then continue ; fi
6680

    
6681
		# Filter out any special files, we don't need diffs of them
6682
		if [ -L "${1}/$line" ] ; then continue ; fi
6683
		if [ -p "${1}/$line" ] ; then continue ; fi
6684
		if [ -S "${1}/$line" ] ; then continue ; fi
6685
		if [ -d "${1}/$line" ] ; then continue ; fi
6686
		if [ -b "${1}/$line" ] ; then continue ; fi
6687
		if [ -c "${1}/$line" ] ; then continue ; fi
6688

    
6689
		# Check sha256 of each file, see if we have differences
6690
		sha1=`sha256 -q "${1}/${line}"`
6691
		sha2=`sha256 -q "${2}/${line}"`
6692
		if [ "$sha1" != "$sha2" ] ; then
6693
			# These files differ, get a binary patch made of them
6694
			_tDir="${3}/`dirname $line`"
6695
			_bName=`basename $line`
6696
			if [ ! -d "$_tDir" ] ; then mkdir -p "$_tDir" ; fi
6697
			
6698
			bsdiff "${2}/${line}" "${1}/${line}" "${_tDir}/${_bName}.bsdiff"
6699
			if [ "$?" != "0" ] ; then
6700
				exit_err "Failed creating bsdiff patch for $line"
6701
			fi
6702

    
6703
			# Save the sha256 of the file to be modified
6704
			sha256 -q "${2}/${line}" > "${_tDir}/${_bName}.sha256"
6705
		fi
6706

    
6707
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6708

    
6709
	# Remove the tmp list files
6710
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6711
}
6712

    
6713
# Function which compares two directories, and returns a list of files / dirs removed in the new dir
6714
gen_rem_list() {
6715

    
6716
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6717
	find ${2} | sed "s|^${2}/||g" | sed "s|^${2}||g" >${PBI_TMPDIR}/.pbi.oDir.$$
6718

    
6719
	echo "Finding removed files..."
6720

    
6721
	_rmList="${PBI_TMPDIR}/.pbi.rmList.$$"
6722
	if [ -e "$_rmList" ] ; then rm "$_rmList" ; fi
6723

    
6724
	while read line
6725
	do
6726
		if [ -z "$line" ] ; then continue ; fi
6727
		grep "^$line" ${PBI_TMPDIR}/.pbi.nDir.$$ >/dev/null 2>/dev/null
6728
		if [ "$?" != "0" ] ; then
6729
			#echo "Removed File: $line"
6730
			echo "$line" >> ${_rmList}
6731
		fi
6732

    
6733
	done < ${PBI_TMPDIR}/.pbi.oDir.$$
6734

    
6735
	# Remove the tmp list files
6736
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6737
	rm ${PBI_TMPDIR}/.pbi.oDir.$$
6738

    
6739
	if [ -e "$_rmList" ] ; then
6740
		VAL="$_rmList"
6741
	else
6742
		VAL=""
6743
	fi
6744
}
6745

    
6746
# Function which compares two directories, and returns a list of files / dirs added in the new dir
6747
gen_newfile_list() {
6748

    
6749
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6750
	echo "Finding new files..."
6751

    
6752
	_addList="${PBI_TMPDIR}/.pbi.addList.$$"
6753
	if [ -e "$_addList" ] ; then rm "$_addList" ; fi
6754

    
6755
	while read line
6756
	do
6757
		# Search for all new files + symlinks to include in tarball
6758
		if [ -z "$line" ] ; then continue ; fi
6759
		if [ ! -e "${2}/$line" -o -L "${1}/$line" ] ; then
6760
			#echo "New File: $line"
6761
			echo "./$line" >> ${_addList}
6762
		fi
6763

    
6764
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6765

    
6766
	# Remove the tmp list files
6767
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6768

    
6769
	if [ -e "$_addList" ] ; then
6770
		VAL="$_addList"
6771
	else
6772
		VAL=""
6773
	fi
6774
}
6775

    
6776
# Read the version from a PBI file
6777
get_ver_from_pbi_file() 
6778
{
6779
	VAL="`pbi_add -i $1 | grep Version: | cut -d ':' -f 2 | tr -d ' '`"
6780
	export VAL
6781
}
6782

    
6783
# Read the version from a PBI file
6784
get_progname_from_pbi_file() 
6785
{
6786
	VAL="`pbi_add -i $1 | grep Name: | cut -d ':' -f 2 | tr -d ' '`"
6787
	export VAL
6788
}
6789

    
6790
get_prefix_from_pbi_file()
6791
{
6792
	VAL="`pbi_add -i $1 | grep Prefix: | cut -d ':' -f 2 | tr -d ' '`"
6793
	export VAL
6794
}
6795

    
6796
get_mdate_from_pbi_file()
6797
{
6798
	VAL="`pbi_add -i $1 | grep Built: | cut -d ' ' -f 2-5 | tr -s ' '`"
6799
	export VAL
6800
}
6801

    
6802
get_arch_from_pbi_file()
6803
{
6804
	VAL="`pbi_add -i $1 | grep Arch: | cut -d ' ' -f 2-5 | tr -s ' '`"
6805
	export VAL
6806
}
6807

    
6808
# Move old PBIs to the archive
6809
archive_old_pbis()
6810
{
6811
	local _od="$1"
6812
	local _keepnum="$2"
6813

    
6814
	# Make sure the archived dir exists
6815
	if [ ! -d "${_od}/archived" ] ; then mkdir "${_od}/archived"; fi
6816

    
6817
	# Make sure we have PBIs to archive
6818
	ls ${_od}/*.pbi >/dev/null 2>/dev/null
6819
        if [ "$?" != "0" ] ; then return ; fi
6820

    
6821
	#echo "Moving old PBIs from ${_od}/*.pbi -> ${_od}/archived/"
6822
	mv ${_od}/*.pbi ${_od}/archived/ 2>/dev/null
6823
	mv ${_od}/*pbi.sha256 ${_od}/archived/ 2>/dev/null
6824

    
6825
	# Prune anything beyond the _keepnum
6826
        #echo "Checking for more than $_keepnum PBIs in archive"
6827
	oCount="1"
6828
	for oFile in `ls -t ${_od}/archived/*.pbi 2>/dev/null`
6829
	do
6830
		if [ -z "$oFile" ] ; then continue ; fi
6831
		if [ "$oCount" -gt "$_keepnum" ] ; then
6832
			#echo "Removing old PBI ${oFile} from archive"
6833
			rm ${oFile}*
6834
		fi
6835
		oCount=`expr $oCount + 1`	
6836
	done
6837
}
6838

    
6839
# Check if we need to do an auto-build of the target PBI
6840
check_ab_needed() {
6841
	_port="$1"
6842
	_bk="$2"
6843
	_cd="$3"
6844
	local _abkey="$4"
6845
        internal_ab_priority="1"
6846
	export internal_ab_priority
6847
        unset PBI_PROGVERSION
6848

    
6849
	# Check PBI_BUILDKEY, see if we have a manual rebuild triggered
6850
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/pbi-buildkey" ] ; then
6851
		if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-buildkey`" != "$_bk" \
6852
			 -a -n "${_bk}" ]; then 
6853
                   #echo "$_port BUILDKEY bump, rebuild triggered."
6854
                   internal_ab_priority="9"
6855
                   return 0
6856
                fi
6857
	fi
6858

    
6859
	# Make sure this PBI hasn't already failed during this run
6860
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/.abkey" -a -e "${PBI_AB_OUTDIR}/${_cd}/pbi-result" ] ; then
6861
	  if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/.abkey`" = "$_abkey" ] ; then
6862
	    if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-result`" != "OK" ] ; then
6863
              #echo "$_port - Skipping failed from this run"
6864
	      return 1
6865
  	    fi
6866
  	  fi
6867
	fi
6868

    
6869
	#echo "Checking $_port for rebuild in ${PBI_AB_OUTDIR}/$_cd with key of $_bk"
6870

    
6871
	# See if we have an existing PBI
6872
	ls ${PBI_AB_OUTDIR}/${_cd}/*.pbi >/dev/null 2>/dev/null
6873
	if [ "${?}" != "0" ]; then 
6874
	  #echo "$_port - No existing PBI"
6875
          internal_ab_priority="8"
6876
          return 0 
6877
        fi
6878

    
6879
	# See if we have a saved version
6880
	if [ ! -e "${PBI_AB_OUTDIR}/${_cd}/pbi-version" ]; then 
6881
		#echo "No saved pbi-version"
6882
	  	#echo "$_port - No existing version"
6883
          	internal_ab_priority="7"
6884
		return 0
6885
	fi
6886

    
6887
	# Get the programs port version
6888
	get_pbi_progversion
6889

    
6890
	# See if the version is different now
6891
	oldVersion=`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-version`
6892
	if [ "$oldVersion" != "$PBI_PROGVERSION" ]; then 
6893
		oldPortVer="`echo $oldVersion | rev | cut -d '_' -f 2- | rev`"
6894
		if [ "$PORTVER" = "$oldPortVer" ] ; then
6895
			# Just a minor portrev bump
6896
          		internal_ab_priority="2"
6897
			#echo "$_port revision bump: $oldVersion -> $PBI_PROGVERSION"
6898
		else
6899
			# Real version change
6900
          		internal_ab_priority="3"
6901
			#echo "$_port version bump: $oldVersion -> $PBI_PROGVERSION"
6902
		fi
6903
		return 0
6904
	fi
6905

    
6906
	#echo "$_port - is Up2Date!"
6907
	return 1
6908
}
6909

    
6910
# start processing for make port / pbi compile
6911
pbi_make_init() {
6912

    
6913
  	require_root
6914

    
6915
  	parse_make_pbi_cmdline "$@"
6916
 
6917
  	do_pbi_make "$@"
6918
}
6919

    
6920
do_pbi_make() {
6921

    
6922
	# See if we need to enable pkgng
6923
	detect_pkgng
6924

    
6925
  	# Load the PBI settings
6926
	get_pbi_progversion
6927
	get_pbi_progname
6928
  	get_pbi_progdir
6929

    
6930
	# Check if this is being called from within chroot or outside
6931
	if [ "`basename $0`" = "pbi_makeport" ] ; then
6932
		# Extract the chroot 
6933
		chroot_extract
6934

    
6935
		# Now re-run pbi_makeport in chroot environment
6936
		chroot "${PBI_CHROOTDIR}" "/usr/local/sbin/pbi_makeport_chroot" "$@"
6937
		_err=$?
6938
		if [ "$_err" = "0" -a "${PBI_BUILDONLY}" != "YES" ] ; then
6939
			mv ${PBI_CHROOTDIR}/pbiout/*.pbi ${PBI_CREATE_OUTDIR}/ 
6940
			mv ${PBI_CHROOTDIR}/pbiout/*.sha256 ${PBI_CREATE_OUTDIR}/
6941
		else
6942
			echo "Error: pbi_makeport_chroot: returned non-0 status!"
6943
		fi
6944

    
6945
  		# Break here if we are only doing a build
6946
		if [ "${PBI_BUILDONLY}" = "YES" ] ; then exit_trap; fi
6947

    
6948
		# Lets cleanup the chroot environment
6949
		chroot_make_cleanup
6950
		rm_tmpdir
6951

    
6952
		# If running as an auto-build, show that we were successful
6953
		if [ -n "$PBI_AB_TMPDIR" ] ; then
6954
        		echo "$_err" > ${PBI_AB_TMPDIR}/${PBI_AB_BUILDER}.result
6955
		fi
6956
		exit $_err
6957
	fi
6958

    
6959
	if [ "`basename $0`" != "pbi_makeport_chroot" ] ; then return ; fi
6960
	
6961

    
6962
  	# Check if we have some specific make options to use
6963
  	load_pbi_conffile
6964

    
6965
  	# init tmpdir
6966
  	init_tmpdir
6967

    
6968
  	set_make_options
6969

    
6970
  	# See if we need to run a pre make script
6971
  	run_pbi_preportmake
6972

    
6973
  	# Start our build
6974
  	start_pbi_mkportbefore
6975
  	start_prebuild_script
6976
  	start_pbi_makeport
6977
  	start_postbuild_script
6978
  	start_pbi_mkportafter
6979

    
6980
	# Get the version again, in case we installed from pkgng and it doesn't match ports
6981
	get_pbi_progversion
6982

    
6983
  	# Prune any proto / build specific ports
6984
  	if [ -z "$PBI_PKGNGBUILD" ] ; then
6985
  		start_pbi_prune_ports
6986
	fi
6987

    
6988
  	# See if we need to run a post make script
6989
  	run_pbi_postportmake
6990

    
6991
	# Auto-generate a external_links directive from plist info
6992
	mk_auto_ext_linksfile
6993

    
6994
  	# Break here if we are only doing a build
6995
	if [ "${PBI_BUILDONLY}" = "YES" ] ; then exit_trap; fi
6996

    
6997
	# Load any extra meta-data from the package
6998
	load_pkg_metadata
6999

    
7000
	# Start creation of PBI
7001
	do_pbi_create
7002

    
7003
	# Got this far, lets exit with success
7004
	rm_buildfiles
7005
	rm_tmpdir
7006

    
7007
	exit 0
7008
}
7009

    
7010
# Loads some optional meta-data from the package
7011
load_pkg_metadata()
7012
{
7013
  	# Remove any trailing '/'
7014
  	echo $PBI_MAKEPORT | grep -q "/$"
7015
  	if [ $? -eq 0 ] ; then
7016
     		PBI_MAKEPORT="`echo $PBI_MAKEPORT | sed 's|/$||g'`"
7017
  	fi
7018

    
7019
	if [ -z "$PBI_LICENSE" ] ; then
7020
		PBI_LICENSE="`pkg query '%L' ${PBI_MAKEPORT} | head -n 1`"
7021
	fi
7022
	if [ -z "$PBI_SHORTDESC" ] ; then
7023
		PBI_SHORTDESC="`pkg query '%c' ${PBI_MAKEPORT}`"
7024
	fi
7025
	if [ -z "$PBI_MAINTAINER" ] ; then
7026
		PBI_MAINTAINER="`pkg query '%m' ${PBI_MAKEPORT}`"
7027
	fi
7028
	if [ -z "$PBI_DESC" ] ; then
7029
		PBI_DESC="`pkg query '%e' ${PBI_MAKEPORT}`"
7030
	fi
7031
	if [ -z "$PBI_PROGWEB" ] ; then
7032
		PBI_PROGWEB="`pkg query '%w' ${PBI_MAKEPORT}`"
7033
	fi
7034
	if [ -z "$PBI_CATEGORY" ] ; then
7035
		PBI_CATEGORY="`pkg query '%C' ${PBI_MAKEPORT} | head -n 1`"
7036
	fi
7037
	if [ -z "$PBI_PROGTYPE" ] ; then
7038
		PBI_PROGTYPE="Text"
7039
	fi
7040
}
7041

    
7042
# Check if we need to save a list of GROUPS to create at install
7043
mk_pbi_groups_file()
7044
{
7045
	if [ -z "$PBI_BUILD_GROUPS" ] ; then return ; fi
7046

    
7047
	for group in $PBI_BUILD_GROUPS
7048
	do
7049
		# Check /usr/ports/GIDs for group entry
7050
		gidLine=`cat /usr/ports/GIDs | grep "^$group:"`
7051
		if [ -z "$gidLine" ] ; then
7052
			echo "Warning: No entry for \"$group\" in GIDs file..."
7053
			continue
7054
		fi
7055
		grep -q "^$group:" ${PBI_STAGEDIRMNT}/${PBI_INS_GROUPSFILE}
7056
		if [ $? -ne 0 ] ; then
7057
			echo "Saving gid details for group: $group"
7058
			echo "$gidLine" >> ${PBI_STAGEDIRMNT}/${PBI_INS_GROUPSFILE}
7059
		fi
7060
	done
7061
}
7062

    
7063
# Check if we need to save a list of users to create at install
7064
mk_pbi_users_file()
7065
{
7066
	if [ -z "$PBI_BUILD_USERS" ] ; then return ; fi
7067

    
7068
	for user in $PBI_BUILD_USERS
7069
	do
7070
		# Check /usr/ports/UIDs for user entry
7071
		uidLine=`cat /usr/ports/UIDs | grep "^$user:"`
7072
		if [ -z "$uidLine" ] ; then
7073
			echo "Warning: No entry for \"$user\" in UIDs file..."
7074
			continue
7075
		fi
7076
		grep -q "^$user:" ${PBI_STAGEDIRMNT}/${PBI_INS_USERSFILE}
7077
		if [ $? -ne 0 ] ; then
7078
			echo "Saving uid details for user: $user"
7079
			echo "$uidLine" >> ${PBI_STAGEDIRMNT}/${PBI_INS_USERSFILE}
7080
		fi
7081
	done
7082
}
7083

    
7084
# Source any pre-build script to allow a custom script to modify the port
7085
start_prebuild_script()
7086
{
7087
	if [ -e "/pre-build.sh" ] ; then
7088
		chmod 755 /pre-build.sh
7089
		# Source the script
7090
		. /pre-build.sh
7091
	fi
7092
}
7093

    
7094
# Source any post-build script to allow a custom script to modify the port
7095
start_postbuild_script()
7096
{
7097
	if [ -e "/post-build.sh" ] ; then
7098
		chmod 755 /post-build.sh
7099
		# Source the script
7100
		. /post-build.sh
7101
	fi
7102
}
7103

    
7104
# Check if we created any linux stuff, and copy it into the correct PREFIX
7105
auto_copy_linuxbase()
7106
{
7107
	if [ -d "/compat/linux/usr/lib" ] ; then
7108
		mkdir ${PBI_PROGDIRPATH}/linuxlib
7109
		echo "Copying /compat/linux -> ${PBI_STAGEDIRMNT}/linux"
7110
		tar cf - -C /compat/linux . 2>/dev/null | \
7111
		tar xf - -C ${PBI_STAGEDIRMNT}/linux 2>/dev/null
7112
	fi
7113
}
7114

    
7115
# Clean the chroot environment
7116
chroot_make_cleanup() {
7117
	[ -z "${PBI_CHROOTDIR}" ] && return
7118
	[ -d "${PBI_CHROOTDIR}" ] || return
7119
	[ "${PBI_CHROOTDIR}" = "/" ] && return
7120
	
7121
	# Unmount /dev if mounted
7122
	echo "Cleaning $PBI_CHROOTDIR"
7123
	umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
7124
	umount -f ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
7125
	umount -f ${PBI_CHROOTDIR}/usr/ports >/dev/null 2>/dev/null
7126
	umount -f ${PBI_CHROOTDIR}/pkgs >/dev/null 2>/dev/null
7127
	umount -f ${PBI_CHROOTDIR}/.ccache >/dev/null 2>/dev/null
7128
	umount -f ${PBI_CHROOTDIR}/usr/wrkdirprefix >/dev/null 2>/dev/null
7129

    
7130
	# Sleep a moment before we try this again, seems it takes a moment to clear up
7131
	sleep 2
7132
	umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
7133

    
7134
	if [ "${PBI_KEEPBUILDFILES}" = "YES" ] ; then return ; fi
7135

    
7136
	# Cleanup ZFS dataset
7137
        isDirZFS "${PBI_CHROOTDIR}" "1"
7138
        if [ $? -eq 0 ] ; then
7139
   	     tank=`getZFSTank "$PBI_CHROOTDIR"`
7140
	     sleep 1
7141
	     # If we are running as a result of pbi_autobuild, let it do the ZFS cleanup
7142
	     if [ -z "${PBI_AB_TMPDIR}" ] ; then
7143
             	zfs destroy -r "${tank}${PBI_CHROOTDIR}"
7144
  	     	rmdir "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
7145
	     fi
7146
	     return
7147
        fi
7148

    
7149
	# Cleanup normal directory
7150
	rm -rf "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
7151
	chflags -R noschg ${PBI_CHROOTDIR} >/dev/null 2>/dev/null
7152
	rm -rf "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
7153
}
7154

    
7155
# Function which extracts the clean chroot environment for the PBI
7156
chroot_extract() {
7157

    
7158
	# If no freebsd base exists, make it first
7159
	PBI_WORLDCHROOT="${PBI_APPDIR}/.pbi-world-$ARCH"
7160
	export PBI_WORLDCHROOT
7161
	[ -e "${PBI_WORLDCHROOT}/COPYRIGHT" ] || mk_chroot_file
7162

    
7163
	# Set the chroot path
7164
	PBI_CHROOTDIR="${PBI_PROGDIRPATH}.chroot.$$"
7165
	export PBI_CHROOTDIR
7166
	
7167
	# See if there is old chroot to clean first
7168
	chroot_make_cleanup
7169

    
7170
	# Create the new chroot dir
7171
	mkdir -p "${PBI_CHROOTDIR}"
7172

    
7173
	# If on ZFS, we can just clone our existing base system
7174
	isDirZFS "${PBI_APPDIR}"
7175
        if [ $? -eq 0 ] ; then   
7176
           tank=`getZFSTank "$PBI_WORLDCHROOT"`
7177
	   echo "Cloning ${PBI_WORLDCHROOT} -> ${PBI_CHROOTDIR}"
7178
	   if [ -n "${PBI_AB_TMPDIR}" ] ; then
7179
              echo "${tank}${PBI_CHROOTDIR}" > ${PBI_AB_TMPDIR}/${PBI_AB_BUILDER}.zmnt
7180
	   fi
7181
           zfs clone ${tank}${PBI_WORLDCHROOT}@clean ${tank}${PBI_CHROOTDIR}
7182
	   if [ $? -ne 0 ] ; then exit_err "Failed creating clean ZFS base snapshot"; fi
7183
	else
7184
	   echo "Creating chroot environment..."
7185
	   tar cf - -C ${PBI_WORLDCHROOT} . | tar xf - -C "${PBI_CHROOTDIR}" 2>/dev/null
7186
	   [ $? -ne 0 ] && exit_err "Failed copying chroot environment!"
7187
	fi
7188

    
7189
	# If we plan on using TMPFS mount it now
7190
	mkdir -p ${PBI_CHROOTDIR}/usr/wrkdirprefix
7191
	if [ "$MKTMPFS" = "YES" ] ; then 
7192
		mount -t tmpfs tmpfs ${PBI_CHROOTDIR}/usr/wrkdirprefix
7193
	fi
7194

    
7195
	# Copy resolv.conf
7196
	cp /etc/resolv.conf ${PBI_CHROOTDIR}/etc/resolv.conf
7197

    
7198
	# Copy our binary wrapper
7199
	PBI_WRAPPERFILE="${PBI_SHARE_DIR}/.pbiwrapper-$ARCH"
7200
	cp ${PBI_WRAPPERFILE} ${PBI_CHROOTDIR}/.pbiwrapper-$ARCH
7201

    
7202
	# If we are doing a PKGNG build, lets set it up
7203
	if [ "$PBI_PKGNGBUILD" = "YES" ] ; then
7204
		mkdir -p ${PBI_CHROOTDIR}/usr/local/etc 2>/dev/null
7205
	   	cp /usr/local/etc/pkg.conf ${PBI_CHROOTDIR}/usr/local/etc/pkg.conf
7206
		# Copy over the pkg/repo and friends
7207
	   	cp -r /usr/local/etc/pkg ${PBI_CHROOTDIR}/usr/local/etc/
7208

    
7209
		# Install pkgng into the chroot
7210
		# This can fail when we run multiple builders at once,
7211
		# due to the pkgng DB being locked :(
7212

    
7213
		# For now try multiple times, this should be revisited with
7214
		# a cleaner solution at some point
7215
		tries=0
7216
		while :
7217
		do
7218
			pkg-static -c ${PBI_CHROOTDIR} install -y ports-mgmt/pkg
7219
			if [ $? -eq 0 ] ; then break ; fi
7220

    
7221
			if [ $tries -gt 10 ] ; then
7222
				exit_err "Failed installing pkgng into chroot"
7223
			else
7224
				sleepRand="`jot -r 1 1 90`"
7225
				echo "Pkgng is busy, trying again in $sleepRand seconds"
7226
				sleep $sleepRand
7227
				tries=`tries expr + 1`
7228
			fi
7229
		done
7230

    
7231
	fi
7232

    
7233
	# If we have a custom PBI_MAKECONF include it
7234
	[ -e "${PBI_MAKECONF}" ] && cp ${PBI_MAKECONF} ${PBI_CHROOTDIR}/etc/make.conf
7235

    
7236
	# Set any target arch vars
7237
        if [ "${ARCH}" = "i386" -a "${REALARCH}" = "amd64" ];then
7238
                LOGIN_ENV=",UNAME_p=i386,UNAME_m=i386"
7239
                cat >> ${PBI_CHROOTDIR}/etc/make.conf << EOF
7240
ARCH=i386
7241
MACHINE=i386
7242
MACHINE_ARCH=i386
7243
EOF
7244
        	sed -i .back -e "s/:\(setenv.*\):/:\1${LOGIN_ENV}:/" ${PBI_CHROOTDIR}/etc/login.conf
7245
        	cap_mkdb ${PBI_CHROOTDIR}/etc/login.conf
7246
        fi
7247

    
7248
	#echo "Copying ${PORTSDIR} -> ${PBI_CHROOTDIR}/usr/ports"
7249
	#tar cvf - -C "${PORTSDIR}" --exclude ./distfiles . 2>/dev/null | tar xvf - -C "${PBI_CHROOTDIR}/usr/ports" 2>/dev/null
7250
	[ -d "${PORTSDIR}/distfiles" ] || mkdir -p ${PORTSDIR}/distfiles
7251
	mkdir -p ${PBI_CHROOTDIR}/usr/ports 2>/dev/null
7252
	mount_nullfs ${PORTSDIR} ${PBI_CHROOTDIR}/usr/ports
7253

    
7254
	# Now copy over the pbi_* scripts
7255
	mkdir ${PBI_CHROOTDIR}/usr/local/sbin 2>/dev/null
7256
	cp ${PROGBASE}/sbin/pbi_* ${PBI_CHROOTDIR}/usr/local/sbin
7257

    
7258
	# Copy the functions.sh
7259
	mkdir -p ${PBI_CHROOTDIR}/usr/local/share/pcbsd/scripts/
7260
	cp ${PROGBASE}/share/pcbsd/scripts/functions.sh ${PBI_CHROOTDIR}/usr/local/share/pcbsd/scripts/
7261

    
7262
	# Copy over the pbi_makeport app
7263
	cp ${PBI_CHROOTDIR}/usr/local/sbin/pbi_makeport ${PBI_CHROOTDIR}/usr/local/sbin/pbi_makeport_chroot
7264
	chmod 755 ${PBI_CHROOTDIR}/usr/local/sbin/pbi_*
7265

    
7266
	# Copy the default icons
7267
	cp ${PBI_DEFAULT_ICON} ${PBI_CHROOTDIR}${PBI_DEFAULT_ICON_CHROOT}
7268

    
7269
	# Make sure the outgoing dir is created
7270
	mkdir -p ${PBI_CHROOTDIR}/pbiout 2>/dev/null
7271

    
7272
	# Copy over the PBI DB
7273
	mkdir -p ${PBI_CHROOTDIR}/var/db 2>/dev/null
7274
	cp -r ${PBI_DBDIR} ${PBI_CHROOTDIR}${PBI_DBDIR}
7275
	
7276
	# Copy over the confdir as well
7277
	if [ -n "${PBI_CONFDIR}" ] ; then
7278
		mkdir -p "${PBI_CHROOTDIR}/pbimodule"
7279
		echo "Copying ${PBI_CONFDIR} -> ${PBI_CHROOTDIR}/pbimodule"
7280
		tar cf - -C "${PBI_CONFDIR}" . 2>/dev/null | tar xf - -C "${PBI_CHROOTDIR}/pbimodule" 2>/dev/null
7281
	fi
7282

    
7283
	# Copy over the ssl priv key if used
7284
	if [ -n "$PBI_SSLPRIVKEY" ] ; then
7285
	 	cp "${PBI_SSLPRIVKEY}" "${PBI_CHROOTDIR}/privkey.pem"
7286
		chmod 600 "${PBI_CHROOTDIR}/privkey.pem"
7287
	fi
7288

    
7289
	# Check if we have a pre-make script to run
7290
	if [ -n "${PBI_PREMAKE_SCRIPT}" ] ; then
7291
		if [ -e "${PBI_PREMAKE_SCRIPT}" ] ; then
7292
			cp ${PBI_PREMAKE_SCRIPT} ${PBI_CHROOTDIR}/pre-build.sh
7293
		fi
7294
	fi
7295
	# Check if we have a post-make script to run
7296
	if [ -n "${PBI_POSTMAKE_SCRIPT}" ] ; then
7297
		if [ -e "${PBI_POSTMAKE_SCRIPT}" ] ; then
7298
			cp ${PBI_POSTMAKE_SCRIPT} ${PBI_CHROOTDIR}/post-build.sh
7299
		fi
7300
	fi
7301

    
7302
	# Do we have a user-supplied meta-file to include in the PBI?
7303
	if [ -n "${PBI_CREATE_USERMETA}" ] ; then
7304
	   cp "$PBI_CREATE_USERMETA" ${PBI_CHROOTDIR}/user-meta
7305
	fi
7306

    
7307
	# Start devfs in the chroot
7308
	if [ ! -d "${PBI_CHROOTDIR}/dev" ] ; then
7309
		mkdir ${PBI_CHROOTDIR}/dev
7310
	fi
7311
	mount -t devfs devfs ${PBI_CHROOTDIR}/dev
7312

    
7313
	# Mount linprocfs
7314
	mkdir -p ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
7315
	mount -t linprocfs linprocfs ${PBI_CHROOTDIR}/compat/linux/proc
7316

    
7317
	# Make sure the outgoing dir exists
7318
	mkdir -p ${PBI_CHROOTDIR}${PBI_CREATE_OUTDIR} >/dev/null 2>/dev/null
7319

    
7320
	# Check for ccache being enabled on the host and nullfs mount it to the chroot
7321
	if [ -n "${CCACHE_DIR}" -a -d "${CCACHE_DIR}" -a "$PBI_PKGNGBUILD" != "YES" ] ; then
7322
		mkdir ${PBI_CHROOTDIR}/.ccache
7323
		mount_nullfs ${CCACHE_DIR} ${PBI_CHROOTDIR}/.ccache	
7324
	fi
7325

    
7326
}
7327

    
7328
# No chroot environment tar file exists yet, lets build or extract
7329
mk_chroot_file() {
7330

    
7331
	# Check if on PC-BSD and we can instead fetch fbsd-release.txz
7332
	if [ -e "$PCBSD_ETCCONF" -a -z "$FORCE_FBSD_ONLY" ]; then
7333

    
7334
	  cd "$PBI_APPDIR"
7335

    
7336
  	  # Get the system version we are checking for updates to
7337
  	  SYSVER="`uname -r | cut -d '-' -f 1-2`" ; export SYSVER
7338

    
7339
          local dFiles="base.txz doc.txz games.txz src.txz"
7340
          if [ "$ARCH" = "amd64" ] ; then
7341
             dFiles="$dFiles lib32.txz"
7342
          fi
7343

    
7344
          echo "Fetching chroot environment. This may take a while..."
7345
          for i in $dFiles
7346
          do
7347
            echo "Downloading /${SYSVER}/${ARCH}/dist/${i} ..."
7348
            get_file_from_mirrors "/${SYSVER}/${ARCH}/dist/${i}" "${i}" "iso"
7349
            [ $? -ne 0 ] && exit_err "Error while downloading the freebsd world."
7350
          done
7351

    
7352
	  # Create the WORLDCHROOT
7353
	  isDirZFS "${PBI_APPDIR}"
7354
          if [ $? -eq 0 ] ; then   
7355
            # Use ZFS base for cloning
7356
	    echo "Creating ZFS ${PBI_WORLDCHROOT} dataset..."
7357
            tank=`getZFSTank "$PBI_APPDIR"`
7358
	    isDirZFS "${PBI_WORLDCHROOT}" "1"
7359
            if [ $? -ne 0 ] ; then   
7360
              zfs create -o mountpoint=${PBI_WORLDCHROOT} -p ${tank}${PBI_WORLDCHROOT}
7361
	      if [ $? -ne 0 ] ; then exit_err "Failed creating ZFS base dataset"; fi
7362
	    fi
7363
	  else
7364
            mkdir ${PBI_WORLDCHROOT}
7365
	  fi
7366

    
7367
 	  # Extract dist files
7368
          for i in $dFiles
7369
          do
7370
            tar xpf ${i} -C ${PBI_WORLDCHROOT} 2>/dev/null
7371
            if [ $? -ne 0 ] ; then exit_err "Failed extracting freebsd environment"; fi
7372
            rm ${i}
7373
          done
7374

    
7375
          # Create the clean snapshot
7376
	  isDirZFS "${PBI_APPDIR}"
7377
          if [ $? -eq 0 ] ; then   
7378
            zfs snapshot ${tank}${PBI_WORLDCHROOT}@clean
7379
	    if [ $? -ne 0 ] ; then exit_err "Failed creating clean ZFS base snapshot"; fi
7380
          fi
7381

    
7382
	  return
7383
 	fi
7384

    
7385
        local _srcdir="/usr/src"
7386
        if [ -z "${PBI_BUILDSRC}" ] ; then
7387
                PBI_BUILDSRC="${_srcdir}"
7388
        fi
7389

    
7390
        local _targetDir="${PBI_WORLDCHROOT}"
7391
        if [ -z "${PBI_BUILDTARGET}" ] ; then
7392
                PBI_BUILDTARGET="${_targetDir}"
7393
        fi
7394

    
7395
        # Delete source code/build if not /usr/src and PBI_DELETE_BUILD is true
7396
        if [ -z "${PBI_DELETE_BUILD}" ] ; then
7397
                PBI_DELETE_BUILD=1
7398
        fi
7399
 
7400
	# Use existing sources
7401
        if [ -e "${PBI_BUILDSRC}/COPYRIGHT" -a -z "${PBI_OSREL}" ] ; then
7402
		PBI_BUILDLOG="${PBI_APPDIR}/.buildWorldLog"
7403
		: > ${PBI_BUILDLOG}
7404
		mkdir -p "${PBI_BUILDTARGET}"
7405
	
7406
	else
7407
		# Make sure SVN is installed
7408
		which svn >/dev/null 2>/dev/null
7409
		[ "$?" -ne 0 ] && exit_err "Subversion is required to rebuild the chroot environment!"
7410

    
7411
                local _osRel=$FBSDREL
7412
                if [ -n "${PBI_OSREL}" ]; then
7413
                        _osRel="${PBI_OSREL}"
7414
                fi
7415

    
7416
		echo "Building the PBI chroot environment... This may take a while..."
7417
		PBI_BUILDLOG="${PBI_APPDIR}/.buildWorldLog"
7418
		echo "" > ${PBI_BUILDLOG}
7419
		mkdir -p "${PBI_BUILDSRC}"
7420
		mkdir -p "${PBI_BUILDTARGET}"
7421
	
7422
		# Figure out which version of FreeBSD to checkout
7423
		case $_osRel in
7424
			*RELEASE)
7425
				local _osMajor=${_osRel%%.*}
7426
				local svnUrl="svn://svn.freebsd.org/base/releng/${_osMajor}.0"
7427
				echo "Using $svnUrl for sources"
7428
				;;
7429
			*CURRENT)
7430
				local svnUrl="svn://svn.freebsd.org/base/head"
7431
				echo "Using $svnUrl for sources"
7432
				;;
7433
			*STABLE)
7434
				local _osMajor=${_osRel%%.*}
7435
				local svnUrl="svn://svn.freebsd.org/base/stable/${_osMajor}"
7436
				"Using $svnUrl for sources"
7437
				;;
7438
			*)
7439
				local svnUrl="svn://svn.freebsd.org/base/head"
7440
				echo "Using $svnUrl for sources"
7441
				echo "Assuming a BETA|RC or rarely used FreeBSD version. Using CURRENT!"
7442
				;;
7443
		esac
7444

    
7445
		echo "Checking out FreeBSD sources from $svnUrl"
7446
                if [ -e "${PBI_BUILDSRC}/COPYRIGHT" ] ; then
7447
                        svn update ${PBI_BUILDSRC} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7448
                else
7449
                        svn co ${svnUrl} ${PBI_BUILDSRC} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7450
                fi
7451

    
7452
                if [ "$?" != "0" ] ; then
7453
                        if [ "${PBI_DELETE_BUILD}" = "1" ] ; then
7454
                                rm -rf "${PBI_BUILDSRC}"
7455
                                rm -rf "${PBI_BUILDTARGET}"
7456
                        fi
7457
			exit_err "Subversion checkout failed! Logfile saved: ${PBI_BUILDLOG}"
7458
		fi
7459
	fi # End of subversion checkout
7460

    
7461
	echo "Running buildworld / installworld (into a chroot)"
7462
	touch ${PBI_BUILDSRC}/Makefile
7463
	cd ${PBI_BUILDSRC}
7464
        make ${PBI_BUILDFLAGS} TARGET=$ARCH buildworld >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7465
        if [ "$?" != "0" ] ; then
7466
                cd
7467
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7468
                        rm -rf "${PBI_BUILDSRC}"
7469
                        rm -rf "${PBI_BUILDTARGET}"
7470
                fi
7471
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
7472
        fi
7473

    
7474
	# See if we need to create a ZFS dataset
7475
	isDirZFS "${PBI_APPDIR}"
7476
        if [ $? -eq 0 ] ; then   
7477
            # Use ZFS base for cloning
7478
	    echo "Creating ZFS ${PBI_WORLDCHROOT} dataset..."
7479
            tank=`getZFSTank "$PBI_APPDIR"`
7480
	    isDirZFS "${PBI_WORLDCHROOT}" "1"
7481
            if [ $? -ne 0 ] ; then   
7482
              zfs create -o mountpoint=${PBI_WORLDCHROOT} -p ${tank}${PBI_WORLDCHROOT}
7483
	      if [ $? -ne 0 ] ; then exit_err "Failed creating ZFS base dataset"; fi
7484
	    fi
7485
	fi
7486

    
7487
        make ${PBI_BUILDFLAGS} installworld TARGET=$ARCH DESTDIR=${PBI_BUILDTARGET} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7488
        if [ "$?" != "0" ] ; then
7489
                cd
7490
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7491
                        rm -rf "${PBI_BUILDSRC}"
7492
                        rm -rf "${PBI_BUILDTARGET}"
7493
                fi
7494
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
7495
        fi
7496
        make ${PBI_BUILDFLAGS} distribution TARGET=$ARCH DESTDIR=${PBI_BUILDTARGET} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7497
        if [ "$?" != "0" ] ; then
7498
                cd
7499
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7500
                        rm -rf "${PBI_BUILDSRC}"
7501
                        rm -rf "${PBI_BUILDTARGET}"
7502
                fi
7503
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
7504
        fi
7505

    
7506
	# Copy the source since some ports need kern sources
7507
	echo "Copying FreeBSD sources to chroot environment"
7508
	mkdir -p ${PBI_BUILDTARGET}/usr/src >/dev/null 2>/dev/null
7509
	tar cf - -C "${PBI_BUILDSRC}" --exclude "\.svn/" . 2>/dev/null | tar xf - -C "${PBI_BUILDTARGET}/usr/src" 2>/dev/null
7510
	cd
7511

    
7512
	# Cleanup after ourselves
7513
	chflags -R noschg "${PBI_BUILDTARGET}" >/dev/null 2>/dev/null
7514
        if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7515
                rm -rf "${PBI_BUILDSRC}"
7516
        fi
7517
        if [ "${PBI_DELETE_BUILD}" = "1" ] ; then
7518
                rm -rf "${PBI_BUILDTARGET}" >/dev/null 2>/dev/null
7519
        fi
7520
	rm ${PBI_BUILDLOG}
7521

    
7522
	# If on ZFS, create snapshot
7523
	isDirZFS "${PBI_APPDIR}"
7524
	if [ $? -eq 0 ] ; then
7525
           	zfs snapshot ${tank}${PBI_WORLDCHROOT}@clean
7526
	    	if [ $? -ne 0 ] ; then exit_err "Failed creating clean ZFS base snapshot"; fi
7527
		rm ${PBI_BUILDLOG}
7528
		return
7529
	fi
7530

    
7531
}
7532

    
7533
# Read the target ports plist, and generate a external_links config based upon it
7534
mk_auto_ext_linksfile() {
7535
	# Get ports name
7536
	get_pkgname "${PBI_MAKEPORT}"
7537
	_pname="${PKGNAME}"
7538

    
7539
 	pkg info -l ${_pname} | sed "s|/usr/local/||g" \
7540
		| grep -v -e "^Information for" -e "^Files:" -e "owns the following" \
7541
		| tr -s '\t' ' ' \
7542
		| tr -d ' ' \
7543
		 > "${PBI_TMPDIR}/.pkg_flist.$$"
7544

    
7545
	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then
7546
		mkdir -p "${PBI_PROGDIRPATH}"
7547
	fi
7548
	_ef="${PBI_TMPDIR}/${MOD_AUTOEXTLINKFILE}"
7549

    
7550
	[ -e "$_ef" ] && rm "$_ef"
7551

    
7552
	while read f
7553
	do
7554
		bin="NO"
7555
		[ -z "${f}" ] && continue
7556
		[ -e "/usr/local/${f}" ] || continue
7557

    
7558
		# Strip out anything not in:
7559
		dirname ${f} | grep -q -e "^bin" -e "^sbin" -e "^etc/rc.d" -e "^man" -e "^info"
7560
		[ $? -ne 0 ] && continue
7561

    
7562
		# See if this is executable and set it as binary
7563
		dirname ${f} | grep -q -e "^bin" -e "^sbin" -e "^etc/rc.d"
7564
		if [ -x "/usr/local/${f}" -a $? -eq 0 ] ; then
7565

    
7566
		   # Check this executable, if Linux binary, flag it
7567
		   file "/usr/local/${f}" | grep -iq "Linux"
7568
		   if [ $? -ne 0 ] ; then
7569
	  	      echo "${f}	${f}	binary,nocrash" >> "$_ef"
7570
		   else
7571
	  	      echo "${f}	${f}	linux,nocrash" >> "$_ef"
7572
 		   fi
7573
		else
7574
			echo "${f}	${f}	replace" >> "$_ef"
7575
		fi
7576
	done < ${PBI_TMPDIR}/.pkg_flist.$$
7577
	rm "${PBI_TMPDIR}/.pkg_flist.$$"
7578
}
7579

    
7580
# Init the crash handler routine
7581
pbi_crash_init() {
7582
	which "pbi-crashhandler-gui" >/dev/null 2>/dev/null
7583
	if [ "$?" = "0" -a -n "${DISPLAY}" ] ; then
7584
		#pbi-crashhandler-gui "$@"
7585
	fi
7586
}
7587

    
7588
# Get the hard-link counter for the specified file
7589
get_hard_link_count() {
7590
	HLINKS=`stat -f %l "${1}"`
7591
}
7592

    
7593
# Cleanup after caught exit
7594
exit_trap() {
7595
	# If a download is running, kill it
7596
	if [ -n  "${FETCH_PID}" ] ; then 
7597
	   echo "Killing ${FETCH_PID}"
7598
	   kill -s INT ${FETCH_PID}
7599
           sleep 2
7600
	fi
7601

    
7602
	# If we are running as an auto-build service we need to cleanup
7603
	if [ "`basename ${0}`" = "pbi_autobuild" ] ; then
7604
	   for j in `ls ${PBI_TMPDIR}/*.pid 2>/dev/null`
7605
	   do
7606
	      bNum=`basename $j | cut -d '.' -f 1 `
7607
	      if pgrep -qF "${j}" >/dev/null 2>&1; then 
7608
	         echo "===>Cleaning up processes [$bNum]"
7609
		 pkill -9 -P "`cat ${j}`"
7610
		 sleep 10 
7611
		 pkill -9 -F ${j}
7612
 		 sleep 10 
7613
		 # Do the ZFS destroy here, since running zfs destroy concurrently as we cleanup can cause a panic
7614
		 check_zfs_ab_destroy "$bNum"
7615
	      fi
7616
	   done
7617
	fi
7618

    
7619
        chroot_make_cleanup
7620
	rm_pbipatchfiles
7621
	rm_tmpdir
7622
	exit 0
7623
}
7624

    
7625
# Read in the global pbi.conf
7626
load_pbi_etcconf() {
7627

    
7628
	# FTP_PASSIVE_MODE needs to be enabled by default
7629
	FTP_PASSIVE_MODE=YES
7630
	export FTP_PASSIVE_MODE
7631

    
7632
	PBI_PUBKEYS="`ls ${PBI_DBKEYDIR}/*.ssl 2>/dev/null`"
7633

    
7634
	[ -e "${PBI_ETCCONF}" ] || return 0
7635

    
7636
	# See if we have a custom index refresh rate
7637
	_ckPBIIR="`sed -n 's/^PBI_INDEXREFRESH: //gp' ${PBI_ETCCONF}`"
7638
	if [ -n "${_ckPBIIR}" -a $(is_num "$_ckPBIIR") ] ; then 
7639
		PBI_INDEXREFRESH="${_ckPBIIR}"
7640
	fi
7641

    
7642
	# Check for a custom FBSDMAJOR version
7643
	_ckPBIMAJOR="`sed -n 's/^PBI_FBSDMAJOR: //gp' ${PBI_ETCCONF}`"
7644
	if [ -n "${_ckPBIMAJOR}" -a $(is_num "$_ckPBIMAJOR") ] ; then 
7645
		PBI_FBSDMAJOR="${_ckPBIMAJOR}"
7646
	fi
7647

    
7648
	# See if we have a custom pbid refresh time
7649
	_ckPBID="`cat ${PBI_ETCCONF} | grep '^PBID_REFRESH: ' | sed 's|PBID_REFRESH: ||g'`"
7650
	if [ -n "${_ckPBID}" -a $(is_num "$_ckPBID") ] ; then 
7651
		PBIDSLEEP="${_ckPBID}"
7652
	fi
7653

    
7654
}
7655

    
7656
# If the loaded file is a PBI PatchFile
7657
is_pbi_patch() {
7658
	if [ -z "$PBI_PATCHVERSION" ] ; then
7659
		return 1
7660
	else
7661
		return 0
7662
	fi
7663
}
7664

    
7665

    
7666
# Build the specified port
7667
do_port_build()
7668
{
7669
  local _lPortRaw="$1"
7670
  local pkgName=""
7671

    
7672
  # Remove any trailing '/'
7673
  echo $_lPortRaw | grep -q "/$"
7674
  if [ $? -eq 0 ] ; then
7675
     _lPortRaw="`echo $_lPortRaw | sed 's|/$||g'`"
7676
  fi
7677

    
7678
  local _lPort="/usr/ports/$_lPortRaw"
7679

    
7680
  echo "Checking port: $_lPort"
7681

    
7682
  if [ -n "$PBI_PKGNGBUILD" ] ; then
7683
     pkgName=`pkg-static rquery '%n' $_lPortRaw`
7684
  else
7685
     pkgName=`make -V PKGNAME -C $_lPort PORTSDIR=${PORTSDIR}`
7686
  fi
7687

    
7688
  # Make sure this port isn't already loaded
7689
  pkg info -e ${pkgName}
7690
  if [ $? -eq 0 ] ; then return ; fi
7691

    
7692
  # Are we doing a PKGNG build?
7693
  if [ -n "$PBI_PKGNGBUILD" ] ; then
7694
	pkg install -y "$_lPortRaw"
7695
	if [ $? -ne 0 ] ; then
7696
	   exit_err "Failed installing $_lPortRaw"
7697
	fi
7698

    
7699
	# Did it install?
7700
    	pkg info -e ${_lPortRaw}
7701
    	if [ $? -ne 0 ] ; then exit_err "Failed to install $_lPortRaw" ; fi
7702

    
7703
  	# Save any users / groups we need to create later
7704
  	local pUsers="`pkg query "%U" $_lPortRaw`"
7705
  	local pGroups="`pkg query "%G" $_lPortRaw`"
7706
  	if [ -n "$pUsers" ] ; then
7707
     		PBI_BUILD_USERS="$PBI_BUILD_USERS $pUsers"
7708
  	fi
7709
  	if [ -n "$pGroups" ] ; then
7710
     		PBI_BUILD_GROUPS="$PBI_BUILD_GROUPS $pGroups"
7711
  	fi
7712

    
7713
	return 0
7714
  fi
7715

    
7716
  # Lets do old-fashioned build
7717

    
7718
  # Save any users / groups we need to create later
7719
  local pUsers="`make -V USERS -C $_lPort PORTSDIR=${PORTSDIR}`"
7720
  local pGroups="`make -V GROUPS -C $_lPort PORTSDIR=${PORTSDIR}`"
7721
  if [ -n "$pUsers" ] ; then
7722
     PBI_BUILD_USERS="$PBI_BUILD_USERS $pUsers"
7723
  fi
7724
  if [ -n "$pGroups" ] ; then
7725
     PBI_BUILD_GROUPS="$PBI_BUILD_GROUPS $pGroups"
7726
  fi
7727

    
7728
  # Parse the pkg deps 
7729
  for _port in `make -C $_lPort PORTSDIR=${PORTSDIR} missing`
7730
  do
7731
    if [ -z "${_port}" ] ; then continue ; fi
7732

    
7733
    # is this installed?
7734
    pkg info -e ${_port}
7735
    if [ $? -eq 0 ] ; then continue ; fi
7736

    
7737
    # Not installed, do this one now until we drill down to the base
7738
    do_port_build "${_port}" >&1 2>&1
7739
  done
7740

    
7741
  echo "Compiling port: ${_lPort}"
7742
  cd ${_lPort}
7743
  make rmconfig
7744
  make clean
7745
  make install
7746
  if [ "$?" != "0" ] ; then
7747
     echo "BUILDERROR1!!"
7748
     sleep 2
7749
     make install
7750
     if [ "$?" != "0" ] ; then
7751
	if [ "$MKDEBUG" = "YES" ] ; then
7752
  	  echo "Failed! Running /bin/sh for debugging, type 'exit' to finish."
7753
  	  /bin/sh
7754
	fi
7755
	make clean
7756
	exit_err "make install of ${PBI_MAKEPORT} failed!"
7757
     fi
7758
  fi
7759
  make clean
7760

    
7761
};
7762

    
7763
# Check if the target directory is on ZFS
7764
# Arg1 = The dir to check
7765
# Arg2 = If set to 1, don't dig down to lower level directory
7766
isDirZFS() {
7767
  local _chkDir="$1"
7768
  while :
7769
  do
7770
     # Is this dir a ZFS mount
7771
     mount | grep -w "on $_chkDir " | grep -qw "(zfs," && return 0
7772
        
7773
     # Quit if not walking down
7774
     if [ "$2" = "1" ] ; then return 1 ; fi
7775
        
7776
     if [ "$_chkDir" = "/" ] ; then break ; fi
7777
     _chkDir=`dirname $_chkDir`
7778
  done
7779
 
7780
  return 1
7781
}
7782

    
7783
# Get the ZFS tank name for a directory
7784
# Arg1 = Directory to check
7785
getZFSTank() {
7786
  local _chkDir="$1"
7787
  _chkdir=${_chkDir%/}
7788
  while :
7789
  do
7790
     zpath=`zfs list | awk -v path="${_chkDir}" '$5 == path { print $1 }'`
7791
     if [ -n "${zpath}" ] ; then
7792
        echo $zpath | cut -f1 -d '/'
7793
        return 0
7794
     fi
7795

    
7796
     if [ "$_chkDir" = "/" ] ; then return 1 ; fi
7797
     _chkDir=`dirname $_chkDir`
7798
  done
7799

    
7800
  return 1
7801
}
7802

    
7803
app_init()
7804
{
7805
  cmd=$1
7806

    
7807
  # Alias install -> add
7808
  if [ "$cmd" = "install" ] ; then cmd="add" ; fi
7809

    
7810
  which -s "pbi_${cmd}" 
7811
  if [ $? -ne 0 ] ; then usage_app; fi
7812

    
7813
  shift
7814
  pbi_${cmd} $*
7815
  exit $?
7816
}
7817

    
7818
usage_app()
7819
{
7820
   cat <<EOF
7821
usage: `basename $0` <subcommand>
7822

    
7823
Available sub-commands:
7824

    
7825
  add
7826
  addrepo
7827
  autobuild
7828
  browser
7829
  create
7830
  deleterepo
7831
  delete
7832
  icon
7833
  indextool
7834
  info
7835
  install
7836
  listrepo
7837
  makeport
7838
  makepatch
7839
  makerepo
7840
  metatool
7841
  patch
7842
  update  
7843

    
7844
EOF
7845
   exit 1
7846
}
7847

    
7848
# Source our shared PCBSD functions
7849
. /usr/local/share/pcbsd/scripts/functions.sh
7850

    
7851
# Set the default umask
7852
umask 022
7853

    
7854
# Main program operation
7855
##############################################################
7856
init_vars
7857
mk_required_dirs
7858

    
7859
trap exit_trap 1 2 3 9 15
7860

    
7861
# Figure out which mode we are running in
7862
case `basename ${0}` in
7863
   pbi_add) pbi_add_init "$@" ;;
7864
   pbi_addrepo) pbi_addrepo_init "$@" ;;
7865
   pbi_autobuild) pbi_autob_init "$@" ;;
7866
   pbi_browser) pbi_browser_init "$@" ;;
7867
   pbi_create) pbi_create_init "$@" ;;
7868
   pbi_deleterepo) pbi_deleterepo_init "$@" ;;
7869
   pbi_delete) pbi_delete_init "$@" ;;
7870
   pbi_icon) pbi_icon_init "$@" ;;
7871
   pbi_indextool) pbi_it_init "$@" ;;
7872
   pbi_info) pbi_info_init "$@" ;;
7873
   pbi_listrepo) pbi_listrepo_init "$@" ;;
7874
   pbi_makeport) pbi_make_init "$@" ;;
7875
   pbi_makeport_chroot) pbi_make_init "$@" ;;
7876
   pbi_makepatch) pbi_makepatch_init "$@" ;;
7877
   pbi_makerepo) pbi_makerepo_init "$@" ;;
7878
   pbi_metatool) pbi_mt_init "$@" ;;
7879
   pbi_patch) pbi_patch_init "$@" ;;
7880
   pbi_update) pbi_update_init "$@" ;;
7881
   pbi_update_hashdir) pbi_update_hashdir_init "$@" ;;
7882
   pbi-crashhandler) pbi_crash_init "$@" ;;
7883
   app) app_init "$@" ;;
7884
   pbi) app_init "$@" ;;
7885
   pbid) pbid_init "$@" ;;
7886
   *) echo "Error: Called with invalid basename!" ; exit_trap ;;
7887
esac
7888

    
7889
rm_tmpdir
7890
exit 0
(12-12/36)