Project

General

Profile

Download (214 KB) Statistics
| Branch: | Tag: | Revision:
1
#!/bin/sh
2
#
3
# Copyright 2011 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
  --no-checksum  -- Skip the checksum verification during installation
44
  --no-checksig  -- Ignore signature verification and force install
45
  --no-hash      -- Disable using shared hash folder for PBI
46
  --rArch arch   -- Used with -r to specify the specific PBI machine type
47
  --rVer ver     -- Used with -r to specify the specific PBI version
48
  --repo repoid  -- Used with -r to specify the specific repo to pull from
49

    
50
EOF
51
        exit_trap
52
}
53

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

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

    
72
EOF
73
        exit_trap
74
}
75

    
76

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

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

    
95
EOF
96
        exit_trap
97
}
98

    
99
usage_delete_pbi() {
100
        cat <<EOF
101
usage: `basename $0` [options] pbi
102

    
103
Options:
104
  -v             -- Enable verbose output
105
  --clean-hdir   -- Perform a full cleaning of hash dir (Does not remove any PBIs)
106

    
107
EOF
108
        exit_trap
109
}
110

    
111
usage_make_pbi() {
112
        cat <<EOF
113
usage: `basename $0` [options] port
114

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

    
130
EOF
131
        exit_trap
132
}
133

    
134
usage_icon_pbi() {
135
        cat <<EOF
136
usage: `basename $0` [options] pbi
137

    
138
Options:
139
  add-desktop          -- Add desktop icons
140
  add-menu             -- Add menu icons
141
  add-mime             -- Add mime registration
142
  add-pathlnk          -- Add PATH links
143
  del-desktop          -- Remove desktop icons
144
  del-menu             -- Remove menu icons
145
  del-mime             -- Remove mime registration
146
  del-pathlnk          -- Remove PATH links
147

    
148
EOF
149
        exit_trap
150
}
151

    
152
usage_info_pbi() {
153
        cat <<EOF
154
usage: `basename $0` [options] pbi
155

    
156
Options:
157
  -a             -- Show all installed PBIs
158
  -v             -- Enable verbose output
159

    
160
EOF
161
        exit_trap
162
}
163

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

    
174

    
175
EOF
176
        exit_trap
177
}
178

    
179
usage_addrepo_pbi() {
180
        cat <<EOF
181
usage: `basename $0` <Repo File>
182
                
183
EOF
184
        exit_trap
185
}
186

    
187
usage_deleterepo_pbi() {
188
        cat <<EOF
189
usage: `basename $0` <Repo ID>
190
                
191
EOF
192
        exit_trap
193
}
194

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

    
215
EOF
216
	exit_trap
217
}
218

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

    
230
EOF
231
	exit_trap
232
}
233

    
234
usage_mt_rem() {
235
        cat <<EOF
236
usage: `basename $0` rem [options] metafile
237
                
238
Options:
239
  --cat		-- Removing category metadata
240
  --app		-- Removing application metadata
241
  -n name   	-- The name we are removing from the metafile (Required)
242

    
243
EOF
244
	exit_trap
245
}
246

    
247

    
248
usage_it_rem() {
249
        cat <<EOF
250
usage: `basename $0` rem [options] indexfile
251
                
252
Options:
253
  -m arch   	-- The PBI architecture to remove (Required)
254
		   I.E. (i386,amd64,etc)
255
  -n pbiname   	-- The PBI name we are removing from the index (Required)
256
  -v version   	-- The version of the PBI to remove (Required) 
257

    
258
EOF
259
	exit_trap
260
}
261

    
262
usage_mt_unknown() {
263
        cat <<EOF
264
usage: `basename $0` [options] metafile
265
                
266
Options:
267
  add   	-- Add a new entry to the specified metafile
268
  rem    	-- Remove an entry in the metafile
269

    
270
EOF
271
	exit_trap
272
}
273

    
274
usage_it_unknown() {
275
        cat <<EOF
276
usage: `basename $0` [options] indexfile
277
                
278
Options:
279
  add   	-- Add a new entry to the specified indexfile
280
  rem    	-- Remove an entry in the indexfile
281

    
282
EOF
283
	exit_trap
284
}
285

    
286
usage_browse_pbi() {
287
        cat <<EOF
288
usage: `basename $0` [options] [repoid]
289
                
290
Options:
291
  -c category  	-- List PBIs from the specified category
292
  -s search 	-- Search for the specified string
293
  --listcats  	-- List the available categories in this repository
294

    
295
EOF
296
        exit_trap
297
}
298

    
299
usage_listrepo_pbi() {
300
        cat <<EOF
301
usage: `basename $0` [options] [repoid]
302
                
303
Options:
304
  --down   	-- Move the specified repoid down in priority
305
  --mirror url 	-- Change the target repoid's mirror url
306
  --up  	-- Move the specified repoid up in priority
307

    
308
EOF
309
        exit_trap
310
}
311

    
312
usage_makerepo_pbi() {
313
        cat <<EOF
314
usage: `basename $0` [options] [outdir]
315
                
316
Options:
317
  --desc description   	-- Description for this new repo
318
  --key key    		-- Path to the public key file for this repo
319
  --url url    		-- Base URL for fetching the INDEX files
320
  --mirror mirrorurl 	-- Mirror url(s) for fetching PBIs, use ',' as 
321
			   seperator for multiple
322

    
323
EOF
324
        exit_trap
325
}
326

    
327
usage_patch_pbi() {
328
        cat <<EOF
329
usage: `basename $0` [options] pbp
330
                
331
Options:
332
  -e             -- Extract Only
333
  -g             -- Get and show path to icon / images for gui installer
334
  -i             -- Display information about this PBI
335
  -o outdir      -- Extract to target directory
336
  --checkscript  -- Display any custom install / removal scripts
337
  --no-checksig  -- Ignore signature verification and force install
338
  --no-hash      -- Disable using shared hash folder for PBI
339

    
340
EOF
341
        exit_trap
342
}
343

    
344
# update usage
345
usage_update_pbi() {
346
        cat <<EOF
347
usage: `basename $0` [options] pbi
348

    
349
Options:
350
  -c              -- Check-only, do not update target PBI
351
  --check-all     -- Perform a full check of all PBIs for updates
352
  --disable-auto  -- Disable auto-updating for the target PBI
353
  --enable-auto   -- Enable auto-updating for the target PBI
354
  --update-all    -- Update all PBIs to latest versions
355

    
356
EOF
357
        exit_trap
358
}
359

    
360
# Parse the command line for info
361
parse_delete_pbi_cmdline() {
362
        while [ $# -gt 0 ]; do
363
                case "$1" in
364
                -v)     PBI_VERBOSE="YES" 
365
                        ;;
366
      --clean-hdir)     pbi_clean_hashdir
367
			exit_trap
368
			;;
369
                 *)     if [ $# -gt 1 ]; then usage_delete_pbi; fi
370
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
371
                                exit_err "can't find installed pbi (${1})"
372
                        fi
373
                        PBI_DELETENAME="$1"
374
                        ;;
375
                esac
376
                shift
377
        done
378
	if [ -z "${PBI_DELETENAME}" ];then usage_delete_pbi; fi
379
}
380

    
381
# Parse the command line for icon
382
parse_icon_pbi_cmdline() {
383
        while [ $# -gt 0 ]; do
384
                case "$1" in
385
                add-desktop)	PBI_DESKADD="YES" ;;
386
                add-menu)	PBI_MENUADD="YES" ;;
387
                add-mime)	PBI_MIMEADD="YES" ;;
388
                add-pathlnk)	PBI_PATHADD="YES" ;;
389
                del-desktop)	PBI_DESKDEL="YES" ;;
390
                del-menu)	PBI_MENUDEL="YES" ;;
391
                del-mime)	PBI_MIMEDEL="YES" ;;
392
                del-pathlnk)	PBI_PATHDEL="YES" ;;
393
                 *)
394
                        if [ $# -gt 1 ]; then usage_icon_pbi; fi
395
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
396
                                exit_err "can't find installed pbi (${1})"
397
                        fi
398
                        PBI_ICONTARGETAPP="$1"
399
                        ;;
400
                esac
401
                shift
402
        done
403
	if [ -z "${PBI_ICONTARGETAPP}" ] ; then 
404
		usage_icon_pbi
405
	fi
406
}
407

    
408
# Parse the command line for pbid
409
parse_pbid_cmdline() {
410
        while [ $# -gt 0 ]; do
411
                case "$1" in
412
                -v)     PBI_VERBOSE="YES" 
413
                        ;;
414
         --refresh)     # Schedule us to refresh the index
415
			echo "Your meta and index files will begin refreshing in a moment..."
416
			echo "Details available in /var/log/pbid.log"
417
			rm ${PBI_DBINDEXDIR}/*.time >/dev/null 2>/dev/null
418
			if [ -e "${PROGBASE}/etc/rc.d/pbid" ]; then
419
			   ${PROGBASE}/etc/rc.d/pbid restart >/dev/null 2>/dev/null
420
			fi
421
			exit 0
422
                        ;;
423
		esac
424
		shift
425
	done
426
}
427

    
428
# Parse the command line for info
429
parse_info_pbi_cmdline() {
430
        while [ $# -gt 0 ]; do
431
                case "$1" in
432
                -a)     PBI_INFONAME="--ALL--"
433
                        ;;
434
		-i) 	PBI_INFOINDEX="YES"	
435
			;;
436
                -v)     PBI_VERBOSE="YES" 
437
                        ;;
438
                 *)
439
                        if [ $# -gt 1 ]; then usage_info_pbi; fi
440
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
441
                                exit_err "can't find installed pbi (${1})"
442
                        fi
443
                        PBI_INFONAME="$1"
444
                        ;;
445
                esac
446
                shift
447
        done
448
	if [ -z "${PBI_INFONAME}" ] ; then 
449
		PBI_INFONAME="--ALL--" 
450
	fi
451
}
452

    
453
# Parse the command line for patching
454
parse_makepatch_pbi_cmdline() {
455
        while [ $# -gt 0 ]; do
456
                case "$1" in
457
                -o)     if [ $# -eq 1 ]; then usage_makepatch_pbi; fi
458
                        shift; PBI_PATCHOUTDIR="$1"
459
                        ;;
460
            --sign)     if [ $# -eq 1 ]; then usage_makepatch_pbi; fi
461
                        shift; PBI_SSLPRIVKEY="$1"
462
                        ;;
463
           --tmpfs)     PBI_MP_TMPFS="YES" 
464
                        ;;
465
     --no-checksig)     PBI_SKIPSIGVERIFY="YES" ;;
466
                 *)	if [ $# -gt 2  ]; then usage_makepatch_pbi; fi
467
                       	PBI_OLDFILENAME="$1"
468
			shift
469
                       	PBI_FILENAME="$1"
470
                        ;;
471
                esac
472
                shift
473
        done
474

    
475
        if [ -z "${PBI_FILENAME}" ]; then usage_makepatch_pbi ; fi
476
        if [ -z "${PBI_OLDFILENAME}" ]; then usage_makepatch_pbi ; fi
477
        if [ -z "${PBI_PATCHOUTDIR}" ]; then PBI_PATCHOUTDIR=`pwd` ; fi
478

    
479
        # Load all the information about this PBI / PBP
480
        load_info_from_header
481
}
482

    
483
# Parse the command line for editing a meta file
484
parse_mt_pbi_cmdline() {
485

    
486
	case $1 in
487
  	   add)	PBI_MT_MODE="ADD" ; shift ; 
488
		while [ $# -gt 0 ]; do
489
                	case "$1" in
490
            	      --cat) PBI_MT_TYPE="CAT" ;;
491
            	      --app) PBI_MT_TYPE="APP" ;;
492
          		-n) if [ $# -eq 1  ]; then usage_mt_add; fi
493
                       	    shift; PBI_MT_ADDNAME="$1"
494
			    ;;
495
          		-i) if [ $# -eq 1  ]; then usage_mt_add; fi
496
                       	    shift; PBI_MT_ADDICON="$1"
497
			    ;;
498
          		-d) if [ $# -eq 1  ]; then usage_mt_add; fi
499
                       	    shift; PBI_MT_ADDDESC="$1"
500
			    ;;
501
          		-c) if [ $# -eq 1  ]; then usage_mt_add; fi
502
                       	    shift; PBI_MT_ADDCAT="$1"
503
			    ;;
504
          		-a) if [ $# -eq 1  ]; then usage_mt_add; fi
505
                       	    shift; PBI_MT_ADDAUTHOR="$1"
506
			    ;;
507
          		-u) if [ $# -eq 1  ]; then usage_mt_add; fi
508
                       	    shift; PBI_MT_ADDURL="$1"
509
			    ;;
510
          		-l) if [ $# -eq 1  ]; then usage_mt_add; fi
511
                       	    shift; PBI_MT_ADDLIC="$1"
512
			    ;;
513
          		-t) if [ $# -eq 1  ]; then usage_mt_add; fi
514
                       	    shift; PBI_MT_ADDTYPE="$1"
515
			    ;;
516
          		-k) if [ $# -eq 1  ]; then usage_mt_add; fi
517
                       	    shift; PBI_MT_ADDKEYWORDS="$1"
518
			    ;;
519
          		-r) PBI_MT_REQUIRESROOT="YES"
520
			    ;;
521
                         *) if [ $# -gt 1  ]; then usage_mt_add; fi
522
                       	    PBI_MT_METAFILE="$1"
523
                            ;;
524
                	esac
525
                	shift
526
 	       	done
527
		if [ -z "${PBI_MT_METAFILE}" ] ; then usage_mt_add ; fi
528
	  	;;
529
  	   rem)	PBI_MT_MODE="REM" ; shift ; 
530
		while [ $# -gt 0 ]; do
531
                	case "$1" in
532
            	      --cat) PBI_MT_TYPE="CAT" ;;
533
            	      --app) PBI_MT_TYPE="APP" ;;
534
          		-n) if [ $# -eq 1  ]; then usage_mt_rem; fi
535
                       	    shift; PBI_MT_REMNAME="$1"
536
			    ;;
537
                         *) if [ $# -gt 1  ]; then usage_mt_rem; fi
538
                       	    PBI_MT_METAFILE="$1"
539
                            ;;
540
			esac
541
			shift
542
		done
543
		if [ -z "${PBI_MT_METAFILE}" ] ; then usage_mt_rem ; fi
544
		;;
545
  	     *) usage_mt_unknown ;;
546
	esac
547

    
548
 	if [ ! -f "${PBI_MT_METAFILE}" ] ; then 
549
		exit_err "No such file ${PBI_MT_METAFILE}"
550
        fi
551

    
552
	# Sanity check the values
553
	case ${PBI_MT_MODE} in
554
		ADD) # Check the common values 
555
		     if [ -z "${PBI_MT_ADDNAME}" ] ; then usage_mt_add ; fi
556
		     if [ -z "${PBI_MT_ADDICON}" ] ; then usage_mt_add ; fi
557
		     if [ -z "${PBI_MT_ADDDESC}" ] ; then usage_mt_add ; fi
558

    
559
	 	     if [ "$PBI_MT_TYPE" = "CAT" ]; then	      
560
		     elif [ "$PBI_MT_TYPE" = "APP" ]; then
561
		     	if [ -z "${PBI_MT_ADDCAT}" ]; then usage_mt_add ; fi
562
		     	if [ -z "${PBI_MT_ADDAUTHOR}" ]; then usage_mt_add ; fi
563
		     	if [ -z "${PBI_MT_ADDURL}" ]; then usage_mt_add ; fi
564
		     	if [ -z "${PBI_MT_ADDLIC}" ]; then usage_mt_add ; fi
565
		     	if [ -z "${PBI_MT_ADDTYPE}" ]; then usage_mt_add ; fi
566
		     	if [ -z "${PBI_MT_ADDKEYWORDS}" ]; then usage_mt_add;fi
567
		     else
568
		       usage_mt_add
569
		     fi
570
		;;
571
		REM) if [ "$PBI_MT_TYPE" != "CAT" -a "$PBI_MT_TYPE" != "APP" ]
572
		     then
573
		        usage_mt_rem
574
		     fi
575
		     if [ -z "${PBI_MT_REMNAME}" ] ; then usage_mt_rem ; fi
576
		;;
577
	esac
578

    
579
}
580

    
581
# Parse the command line for editing a index file
582
parse_it_pbi_cmdline() {
583

    
584
	case $1 in
585
  	   add)	PBI_IT_MODE="ADD" ; shift ; 
586
		while [ $# -gt 0 ]; do
587
                	case "$1" in
588
          		-b) if [ $# -eq 1  ]; then usage_it_add; fi
589
                       	    shift; PBI_IT_ADDBPVERS="$1"
590
			    ;;
591
          		-f) if [ $# -eq 1  ]; then usage_it_add; fi
592
                       	    shift; PBI_IT_ADDFILE="$1"
593
			    ;;
594
          		-k) if [ $# -eq 1  ]; then usage_it_add; fi
595
                       	    shift; PBI_IT_ADDKEEP="$1"
596
			    ;;
597
          		-u) if [ $# -eq 1  ]; then usage_it_add; fi
598
                       	    shift; PBI_IT_ADDURL="$1"
599
			    ;;
600
                         *) if [ $# -gt 1  ]; then usage_it_add; fi
601
                       	    PBI_IT_ADDINDEX="$1"
602
                            ;;
603
                	esac
604
                	shift
605
 	       	done
606
	  	;;
607
  	   rem)	PBI_IT_MODE="REM" ; shift ; 
608
		while [ $# -gt 0 ]; do
609
                	case "$1" in
610
          		-m) if [ $# -eq 1  ]; then usage_it_rem; fi
611
                       	    shift; PBI_IT_REMARCH="$1"
612
			    ;;
613
          		-n) if [ $# -eq 1  ]; then usage_it_rem; fi
614
                       	    shift; PBI_IT_REMNAME="$1"
615
			    ;;
616
          		-v) if [ $# -eq 1  ]; then usage_it_rem; fi
617
                       	    shift; PBI_IT_REMVER="$1"
618
			    ;;
619
                         *) if [ $# -gt 1  ]; then usage_it_rem; fi
620
                       	    PBI_IT_REMINDEX="$1"
621
                            ;;
622
			esac
623
			shift
624
		done
625
		;;
626
  	     *) usage_it_unknown ;;
627
	esac
628

    
629
	# Sanity check the values
630
	case ${PBI_IT_MODE} in
631
		ADD) if [ -z "${PBI_IT_ADDFILE}" ] ; then usage_it_add ; fi
632
		     if [ -z "${PBI_IT_ADDURL}" ] ; then usage_it_add ; fi
633
		     if [ -z "${PBI_IT_ADDINDEX}" ] ; then usage_it_add ; fi
634
		     if [ ! -f "${PBI_IT_ADDFILE}" ] ; then 
635
			exit_err "No such file ${PBI_IT_ADDFILE}"
636
		     fi
637
		     if [ ! -f "${PBI_IT_ADDINDEX}" ] ; then 
638
			exit_err "No such file ${PBI_IT_ADDINDEX}"
639
		     fi
640
		     if [ -n "${PBI_IT_ADDKEEP}" ] ; then 
641
			expr ${PBI_IT_ADDKEEP} + 1 >/dev/null 2>/dev/null
642
			if [ "$?" != "0" ] ; then
643
				exit_err "-k option must be a integer!"
644
			fi
645
		     fi
646
		;;
647
		REM) if [ -z "${PBI_IT_REMNAME}" ] ; then usage_it_rem ; fi
648
		     if [ -z "${PBI_IT_REMVER}" ] ; then usage_it_rem ; fi
649
		     if [ -z "${PBI_IT_REMARCH}" ] ; then usage_it_rem ; fi
650
		     if [ -z "${PBI_IT_REMINDEX}" ] ; then usage_it_rem ; fi
651
		;;
652
	esac
653

    
654
}
655

    
656
# Parse the command line for browsing a repo
657
parse_browse_pbi_cmdline() {
658
        while [ $# -gt 0 ]; do
659
                case "$1" in
660
        --listcats)     PBI_BROWSE_LISTCATS="YES" ;; 
661
         --viewall)     PBI_BROWSE_LISTALLPBI="YES" ;; 
662
                -c)	if [ $# -eq 1  ]; then usage_browse_pbi; fi
663
                       	shift; PBI_BROWSE_CAT="$1"
664
			;;
665
                -s)	if [ $# -eq 1  ]; then usage_browse_pbi; fi
666
                       	shift; PBI_BROWSE_SEARCH="$1"
667
			;;
668
                 *)	if [ $# -gt 1  ]; then usage_browse_pbi; fi
669
                       	PBI_BROWSE_RID="$1"
670
                        ;;
671
                esac
672
                shift
673
        done
674

    
675
	# Get / check the repoid
676
	if [ -n "${PBI_BROWSE_RID}" ] ; then
677
		ls ${PBI_DBREPODIR}/${PBI_BROWSE_RID}.* >/dev/null 2>/dev/null
678
		if [ "$?" != "0" ] ; then
679
			exit_err "The specified repoid ${PBI_BROWSE_RID} does not exist!"
680
		fi
681
	else
682
		for _repo in `ls ${PBI_DBREPODIR} 2>/dev/null`
683
		do
684
			PBI_BROWSE_RID=`echo $_repo | cut -d '.' -f 1`
685
			break;
686
		done
687
		if [ -z "$PBI_BROWSE_RID" ] ; then exit_err "No available repos!" ; fi
688
	fi
689

    
690
	PBI_BROWSE_REPOMD5=`ls ${PBI_DBREPODIR}/${PBI_BROWSE_RID}.* 2>/dev/null | cut -d '.' -f 2`
691
	PBI_BROWSE_METAFILE=`ls ${PBI_DBINDEXDIR}/${PBI_BROWSE_REPOMD5}*meta 2>/dev/null`
692
	if [ -z "${PBI_BROWSE_METAFILE}" ] ; then
693
		exit_err "The specified repo has no meta-file."
694
	fi
695

    
696
}
697

    
698
# Parse the command line for listing repos
699
parse_listrepo_pbi_cmdline() {
700
        while [ $# -gt 0 ]; do
701
                case "$1" in
702
              --up)     PBI_LISTREPO_UP="YES" ;; 
703
            --down)     PBI_LISTREPO_DOWN="YES" ;; 
704
          --mirror)	if [ $# -eq 1  ]; then usage_listrepo_pbi; fi
705
                       	shift; PBI_LISTREPO_MIRROR="$1"
706
			;;
707
                 *)	if [ $# -gt 1  ]; then usage_listrepo_pbi; fi
708
                       	PBI_LISTREPO_ID="$1"
709
                        ;;
710
                esac
711
                shift
712
        done
713

    
714
	if [ "${PBI_LISTREPO_UP}" = "YES" -a "${PBI_LISTREPO_DOWN}" = "YES" ]; then
715
		exit_err "Options --up and --down can't both be used at once!"
716
	fi
717
	if [ "${PBI_LISTREPO_UP}" = "YES" -a -z "${PBI_LISTREPO_ID}" ]; then
718
		exit_err "Missing Repo ID to move up in priority."
719
	fi
720
	if [ "${PBI_LISTREPO_DOWN}" = "YES" -a -z "${PBI_LISTREPO_ID}" ]; then
721
		exit_err "Missing Repo ID to move down in priority."
722
	fi
723
	if [ -n "${PBI_LISTREPO_MIRROR}" -a -z "${PBI_LISTREPO_ID}" ]; then
724
		exit_err "Missing Repo ID to change a specific mirror URL."
725
	fi
726

    
727
	if [ -n "${PBI_LISTREPO_ID}" ] ; then
728
		ls ${PBI_DBREPODIR}/${PBI_LISTREPO_ID}.* >/dev/null 2>/dev/null
729
		if [ "$?" != "0" ] ; then
730
			exit_err "The specified repoid ${PBI_LISTREPO_ID} does not exist!"
731
		fi
732
	fi
733
}
734

    
735
# Parse the command line for adding a new repo file
736
parse_addrepo_pbi_cmdline() {
737
        while [ $# -gt 0 ]; do
738
                case "$1" in
739
                 *)	if [ $# -gt 1  ]; then usage_addrepo_pbi; fi
740
                       	PBI_ADDREPO_FILE="$1"
741
                        ;;
742
                esac
743
                shift
744
        done
745

    
746
	if [ -z "$PBI_ADDREPO_FILE" ] ; then 
747
		usage_addrepo_pbi
748
	fi
749
	if [ ! -f "$PBI_ADDREPO_FILE" ] ; then 
750
		exit_err "Repo file ${PBI_ADDREPO_FILE} does not exist!"
751
	fi
752
}
753

    
754
# Parse the command line for deleting a repo
755
parse_deleterepo_pbi_cmdline() {
756
        while [ $# -gt 0 ]; do
757
                case "$1" in
758
                 *)	if [ $# -gt 1  ]; then usage_deleterepo_pbi; fi
759
                       	PBI_DELREPO_ID="$1"
760
                        ;;
761
                esac
762
                shift
763
        done
764

    
765
	if [ -z "$PBI_DELREPO_ID" ] ; then 
766
		usage_deleterepo_pbi
767
	fi
768
}
769

    
770

    
771
# Parse the command line for making a new repo file
772
parse_makerepo_pbi_cmdline() {
773
        while [ $# -gt 0 ]; do
774
                case "$1" in
775
             --key)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
776
                        shift; PBI_MKREPO_KEY="$1"
777
                        ;;
778
             --url)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
779
                        shift; PBI_MKREPO_URL="$1"
780
                        ;;
781
            --desc)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
782
                        shift; PBI_MKREPO_DESC="$1"
783
                        ;;
784
          --mirror)     if [ $# -eq 1 ]; then usage_makerepo_pbi; fi
785
                        shift; PBI_MKREPO_MIRROR="$1"
786
                        ;;
787
                 *)	if [ $# -gt 1  ]; then usage_makerepo_pbi; fi
788
                       	PBI_MKREPO_OUTDIR="$1"
789
                        ;;
790
                esac
791
                shift
792
        done
793

    
794
        if [ -z "${PBI_MKREPO_DESC}" ]; then usage_makerepo_pbi ; fi
795
        if [ -z "${PBI_MKREPO_KEY}" ]; then usage_makerepo_pbi ; fi
796
        if [ -z "${PBI_MKREPO_MIRROR}" ]; then usage_makerepo_pbi ; fi
797
        if [ -z "${PBI_MKREPO_URL}" ]; then usage_makerepo_pbi ; fi
798
        if [ -z "${PBI_MKREPO_OUTDIR}" ]; then PBI_MKREPO_OUTDIR="${HOME}"; fi
799
        if [ ! -f "${PBI_MKREPO_KEY}" ]; then exit_err "The key file ${PBI_MKREPO_KEY} does not exist." ; fi
800
	
801
	# Make sure we have a valid URL format
802
        echo "${PBI_MKREPO_URL}" | grep -q -e "^http://" -e "^https://" -e "^ftp://"
803
	if [ $? -ne 0 ] ; then
804
		exit_err "Repo URL must begin with http://, https://, or ftp://"
805
	fi
806
	
807

    
808
}
809

    
810
# Parse the command line for patching
811
parse_patch_pbi_cmdline() {
812
        while [ $# -gt 0 ]; do
813
                case "$1" in
814
                -e)     PBI_EXTRACTONLY="YES"
815
                        ;;
816
                -g)     PBI_ADD_GUIDISPLAY="YES" 
817
                        ;;
818
                -i)     PBI_ADD_INFODISPLAY="YES" 
819
                        ;;
820
                -o)
821
                        if [ $# -eq 1 ]; then usage_patch_pbi; fi
822
                        shift; PBI_ALTEXTRACT_DIR="$1"
823
                        ;;
824
     --checkscript)     PBI_CHECKSCRIPTS="YES" ;;
825
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
826
     --no-checksum)     PBI_SKIPCHECKSUM="YES" ;;
827
     --no-checksig)     PBI_SKIPSIGVERIFY="YES" ;;
828
                 *)	if [ $# -gt 1 ]; then usage_patch_pbi; fi
829
                        PBI_FILENAME="$1"
830
                        ;;
831
                esac
832
                shift
833
        done
834

    
835
        if [ -z "${PBI_FILENAME}" ]; then usage_patch_pbi ; fi
836

    
837
	# Get the absolute patch to the file
838
        get_abspath "$PBI_FILENAME"
839
	PBI_FILENAME="$_ABSPATH"
840

    
841
        if [ ! -e "${PBI_FILENAME}" ]; then usage_patch_pbi ; fi
842

    
843
        # Load all the information about this PBI / PBP
844
        load_info_from_header
845

    
846
	# Make sure this isn't a patch file
847
	is_pbi_patch
848
	if [ "$?" = "1" ] ; then
849
		exit_err "This is not a PBP patch file"
850
	fi
851

    
852
        if [ -z "${PBI_ORIGPROGDIRPATH}" ]; then usage_patch_pbi ; fi
853

    
854
        # Lastly set PBI_PROGDIRNAME
855
        PBI_PROGDIRNAME="`echo ${PBI_ORIGPROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
856
                        
857
        if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then
858
                # If extracting to a alt-outdir, set it now
859
                PBI_PROGDIRPATH="`pwd`/${PBI_PROGDIRNAME}"
860
        
861
                if [ -n "${PBI_ALTEXTRACT_DIR}" ]; then
862
                        PBI_PROGDIRPATH="${PBI_ALTEXTRACT_DIR}/${PBI_PROGDIRNAME}"
863
                fi      
864
        else
865
                # Set the extraction dir
866
                PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}-patch"
867
        fi
868
}
869

    
870
# Parse the command line for adding
871
parse_add_pbi_cmdline() {
872
        while [ $# -gt 0 ]; do
873
                case "$1" in
874
                -e)     PBI_EXTRACTONLY="YES"
875
                        ;;
876
                -f)     PBI_FORCEADD="YES"
877
                        ;;
878
                -g)     PBI_ADD_GUIDISPLAY="YES" 
879
                        ;;
880
                -i)     PBI_ADD_INFODISPLAY="YES" 
881
                        ;;
882
                -l)     PBI_ADD_LICDISPLAY="YES" 
883
                        ;;
884
                -o)     if [ $# -eq 1 ]; then usage_add_pbi; fi
885
                        shift; PBI_ALTEXTRACT_DIR="$1"
886
                        ;;
887
                -r)     PBI_REMOTEFETCH="YES" 
888
			;;
889
                -R)     PBI_REMOTEFETCH="YES" 
890
			PBI_REMOTEFETCHONLY="YES"
891
			;;
892
                -v)     PBI_VERBOSE="YES" 
893
                        ;;
894
           --rArch)     
895
                        if [ $# -eq 1 ]; then usage_add_pbi; fi
896
                        shift; PBI_ADD_ALTARCH="$1"
897
                        ;;
898
           --rVer)     
899
                        if [ $# -eq 1 ]; then usage_add_pbi; fi
900
                        shift; PBI_ADD_ALTVER="$1"
901
                        ;;
902
     --checkscript)     PBI_CHECKSCRIPTS="YES" ;;
903
        --licagree)     PBI_LICAGREE="YES" ;;
904
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
905
     --no-checksum)     PBI_SKIPCHECKSUM="YES" ;;
906
     --no-checksig)     PBI_SKIPSIGVERIFY="YES" ;;
907
            --repo)     if [ $# -eq 1 ]; then usage_add_pbi; fi
908
                        shift; PBI_ADDREPO_ID="$1"
909
                        ;;
910
                 *)
911
                        if [ $# -gt 1 ]; then usage_add_pbi; fi
912
                        if [ ! -e "${1}" -a -z "$PBI_REMOTEFETCH" ] ; then
913
                                exit_err "PBI file not found: (${1})"
914
                        fi
915
                        PBI_FILENAME="$1"
916
                        ;;
917
                esac
918
                shift
919
        done
920

    
921
        if [ -z "${PBI_FILENAME}" ]; then usage_add_pbi ; fi
922

    
923
	# If we are doing a remote fetch / install then do it now
924
	if [ "$PBI_REMOTEFETCH" = "YES" ] ; then
925
		if [ -z "${PBI_ADDREPO_ID}" ] ; then
926
			PBI_ADDREPO_ID="AUTO"
927
		else
928
			ls ${PBI_DBREPODIR}/${PBI_ADDREPO_ID}.* >/dev/null 2>/dev/null
929
			if [ "$?" != "0" ] ; then
930
				exit_err "No such repo ID: ${PBI_DELREPO_ID}"
931
			fi
932
		fi
933

    
934
		# Start fetching file
935
		pbi_add_fetch_remote
936
	
937
	fi
938

    
939
        # Load all the information about this PBI
940
        load_info_from_header
941

    
942
        if [ -z "${PBI_ORIGPROGDIRPATH}" ]; then usage_add_pbi ; fi
943

    
944
	# Make sure this isn't a patch file
945
	is_pbi_patch
946
	if [ "$?" = "0" ] ; then
947
		exit_err "This is a PBP patch file, use 'pbi_patch' instead"
948
	fi
949

    
950
        # Lastly set PBI_PROGDIRNAME
951
        PBI_PROGDIRNAME="`echo ${PBI_ORIGPROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
952

    
953

    
954
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then
955
		# If extracting to a alt-outdir, set it now
956
		PBI_PROGDIRPATH="`pwd`/${PBI_PROGDIRNAME}"
957

    
958
		if [ -n "${PBI_ALTEXTRACT_DIR}" ]; then
959
			PBI_PROGDIRPATH="${PBI_ALTEXTRACT_DIR}/${PBI_PROGDIRNAME}"
960
		fi
961
	else
962
		# Set the installation dir
963
		PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}"
964
	fi
965
}
966

    
967
# Parse the command line
968
parse_autob_pbi_cmdline() {
969
        while [ $# -gt 0 ]; do
970
                case "$1" in
971
                -c)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
972
                        if [ -n "${PBI_AB_CONFDIR}" ]; then usage_autob_pbi; fi
973
                        shift
974
                        get_abspath "$1"
975
                        PBI_AB_CONFDIR="$_ABSPATH"
976
                        if [ ! -d "${PBI_AB_CONFDIR}" ] ; then
977
                                exit_err "Invalid confdir (${PBI_AB_CONFDIR})"
978
                        fi
979
                        ;;
980
                -d)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
981
                        shift
982
                        get_abspath "$1"
983
                        PORTSDIR="$_ABSPATH"
984
                        ;;
985
                -o)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
986
                        shift
987
                        get_abspath "$1"
988
                        PBI_AB_OUTDIR="$_ABSPATH"
989
                        ;;
990
                -p)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
991
                        shift
992
                        PBI_AB_BUILDERS="$1"
993
			if [ ! $(is_num "$PBI_AB_BUILDERS") ] ; then 
994
				exit_err "Invalid process number specifed!"
995
			fi
996
                        ;;
997
                -h)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
998
                        shift
999
                        get_abspath "$1"
1000
                        PBI_AB_HELPS="$_ABSPATH"
1001
                        ;;
1002
                -32)    if [ "$REALARCH" != "amd64" ] ; then 
1003
				exit_err "-32 can only be used on amd64 host"
1004
			fi	
1005
			PBI_AB32="YES"
1006
			ARCH=i386
1007
                        ;;
1008

    
1009
        --genpatch)     PBI_AB_GENPATCH="YES" 
1010
                        ;;
1011
        --pkgcache)     PBI_AB_PKGCACHE="YES" 
1012
                        ;;
1013
            --keep)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
1014
                        shift; PBI_AB_ARCHIVENUM="$1"
1015
			expr $PBI_AB_ARCHIVENUM + 1 >/dev/null 2>/dev/null
1016
			if [ $? != 0 ] ; then usage_autob_pbi; fi
1017
                        ;;
1018
           --prune)     PBI_AB_PRUNE="YES" 
1019
                        ;;
1020
           --tmpfs)     PBI_AB_TMPFS="YES" 
1021
                        ;;
1022
            --sign)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
1023
                        shift; PBI_AB_SSLPRIVKEY="$1"
1024
                        ;;
1025
                 *)     usage_autob_pbi ;;
1026
                esac
1027
                shift
1028
        done
1029

    
1030
	if [ -z "$PBI_AB_OUTDIR" ] ; then usage_autob_pbi ; fi
1031
	if [ -z "$PBI_AB_CONFDIR" ] ; then usage_autob_pbi ; fi
1032
}
1033

    
1034

    
1035
# Parse the command line
1036
parse_create_pbi_cmdline() {
1037
        while [ $# -gt 0 ]; do
1038
                case "$1" in
1039
                -a)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1040
                        shift; PBI_CAUTHOR="$1"
1041
                        ;;
1042
                -b)     PBI_CBACKUP="YES"
1043
                        ;;
1044
                -c)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1045
                        shift; 
1046
			get_abspath "$1"
1047
			PBI_CONFDIR="$_ABSPATH"
1048
			if [ ! -d "${PBI_CONFDIR}" ] ; then
1049
				exit_err "Invalid confdir (${PBI_CONFDIR})"
1050
			fi
1051
			load_pbi_conffile
1052
                        ;;
1053
                -d)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1054
                        shift; PORTSDIR="$1"
1055
                        ;;
1056
                -i)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1057
                        shift; PBI_CICON="$1"
1058
                        ;;
1059
                -n)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1060
                        shift; PBI_CNAME="$1"
1061
                        ;;
1062
                -o)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1063
                        shift; PBI_CREATE_OUTDIR="$1"
1064
                        ;;
1065
                -p)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1066
                        shift; PBI_MAKEPORT="$1"
1067
                        ;;
1068
                -r)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1069
                        shift; PBI_CVERSION="$1"
1070
                        ;;
1071
                -w)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1072
                        shift; PBI_CWEB="$1"
1073
                        ;;
1074
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
1075
            --sign)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1076
                        shift; PBI_SSLPRIVKEY="$1"
1077
                        ;;
1078
                 *)
1079
                        if [ $# -gt 1 ]; then usage_create_pbi; fi
1080
			if [ "$PBI_CBACKUP" = "YES" ] ; then
1081
				if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
1082
                       	        	exit_err "can't find installed pbi (${1})"
1083
                        	fi
1084
				PBI_CBACKUPTARGET="${1}"
1085
				PBI_PROGDIRPATH="${1}"
1086
			else
1087
				get_abspath "$1"
1088
				PBI_PROGDIRPATH="$_ABSPATH"
1089
                        	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then
1090
                                	exit_err "Invalid pbidir (${1})"
1091
                          	fi
1092
			fi
1093
                        ;;
1094
                esac
1095
                shift
1096
        done
1097

    
1098
	# Make sure this port exists
1099
        if [ -n "${PBI_MAKEPORT}" -a ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ]; then
1100
		exit_err "No port (${PORTSDIR}/${PBI_MAKEPORT})"
1101
	fi
1102

    
1103
	# Load the name / version from specified port
1104
        if [ -n "${PBI_MAKEPORT}" ]; then
1105
		get_pbi_progversion
1106
		get_pbi_progname
1107
        fi
1108

    
1109
        if [ -z "${PBI_PROGDIRPATH}" ]; then usage_create_pbi ; fi
1110

    
1111
	# Lastly set PBI_PROGDIRNAME
1112
	PBI_PROGDIRNAME="`echo ${PBI_PROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
1113
}
1114

    
1115
# Override any pbi.conf values with passed command-line values
1116
parse_cmdline_overrides() {
1117
	if [ -n "${PBI_CNAME}" ] ; then PBI_PROGNAME="${PBI_CNAME}" ; fi
1118
	if [ -n "${PBI_CVERSION}" ] ; then PBI_PROGVERSION="${PBI_CVERSION}" ; fi
1119
	if [ -n "${PBI_CWEB}" ] ; then PBI_PROGWEB="${PBI_CWEB}" ; fi
1120
	if [ -n "${PBI_CAUTHOR}" ] ; then PBI_PROGAUTHOR="${PBI_CAUTHOR}" ; fi
1121
	if [ -n "${PBI_CICON}" ] ; then PBI_PROGICON="${PBI_CICON}" ; fi
1122
}
1123

    
1124
# Parse the command line
1125
parse_make_pbi_cmdline() {
1126
        while [ $# -gt 0 ]; do
1127
                case "$1" in
1128
                -B)	PBI_BUILDONLY="YES"
1129
                        ;;
1130
                -c)
1131
                        if [ $# -eq 1 ]; then usage_make_pbi; fi
1132
                        if [ -n "${PBI_CONFDIR}" ]; then usage_make_pbi; fi
1133
                        shift
1134
			get_abspath "$1"
1135
			PBI_CONFDIR="$_ABSPATH"
1136
                        ;;
1137
                -d)
1138
                        if [ $# -eq 1 ]; then usage_make_pbi; fi
1139
                        shift; PORTSDIR="$1" ; export PORTSDIR
1140
                        ;;
1141

    
1142
                -32)    if [ "$REALARCH" != "amd64" -a "`basename $0`" != "pbi_makeport_chroot" ] ; then 
1143
				exit_err "-32 can only be used on amd64 host"
1144
			fi	
1145
			ARCH=i386
1146
                        ;;
1147

    
1148
                -k)	PBI_KEEPBUILDFILES="YES"
1149
                        ;;
1150

    
1151
                --delbuild)	MKDELBUILD="YES"
1152
                        ;;
1153
                --no-prune)	PBI_PRUNEBUILDPORTS="NO"
1154
                        ;;
1155
                --mkdebug)	MKDEBUG="YES"
1156
                        ;;
1157
                --tmpfs)	MKTMPFS="YES"
1158
                        ;;
1159
                -o)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1160
                        shift
1161
			get_abspath "$1"
1162
			PBI_CREATE_OUTDIR="$_ABSPATH"
1163
                        ;;
1164
                -p)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1165
                        if [ -n "${PBI_MAKEPREFIX}" ]; then usage_make_pbi; fi
1166
                        shift; PBI_MAKEPREFIX="$1"
1167
                        ;;
1168
            --pkgdir)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1169
			shift
1170
			get_abspath "$1"
1171
			PBI_PKGCACHEDIR="$_ABSPATH"
1172
			PBI_PKGCACHE="YES"
1173
                        ;;
1174
            --sign)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1175
			shift
1176
			get_abspath "$1"
1177
			PBI_SSLPRIVKEY="$_ABSPATH"
1178
                        ;;
1179
                 *)
1180
                        if [ $# -gt 1 ]; then usage_make_pbi; fi
1181
                        PBI_MAKEPORT="$1"
1182
                        ;;
1183
                esac
1184
                shift
1185
        done
1186

    
1187
	# Override some locations if working in chroot environment
1188
	if [ "`basename $0`" = "pbi_makeport_chroot" ] ; then 
1189
		if [ -n "${PBI_CONFDIR}" ] ; then PBI_CONFDIR="/pbimodule" ; fi
1190
		if [ -n "${PBI_SSLPRIVKEY}" ] ; then PBI_SSLPRIVKEY="/privkey.pem" ; fi
1191
		if [ -n "${PBI_CREATE_OUTDIR}" ] ; then PBI_CREATE_OUTDIR="/pbiout" ; fi
1192
		if [ -n "${PORTSDIR}" ] ; then PORTSDIR="/usr/ports" ; fi
1193
	else
1194
	# If running as pbi_makeport
1195

    
1196
		# Make sure the PBI_PKGCACHEDIR exists
1197
		if [ -n "${PBI_PKGCACHEDIR}" -a ! -d "${PBI_PKGCACHEDIR}" ] ; then
1198
			exit_err "No such directory: ${PBI_PKGCACHEDIR}"
1199
		fi
1200
	fi
1201

    
1202

    
1203
	# Make sure this port exists
1204
	if [ ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ] ; then
1205
		exit_err "No port (${PORTSDIR}/${PBI_MAKEPORT})"
1206
	fi
1207

    
1208
	# Make sure we have a valid PBI_CONFDIR
1209
	if [ -n "${PBI_CONFDIR}" -a ! -d "${PBI_CONFDIR}" ] ; then
1210
		exit_err "Invalid confdir (${PBI_CONFDIR})"
1211
	fi
1212

    
1213
	# Source the config file
1214
	if [ -n "${PBI_CONFDIR}" ]; then load_pbi_conffile ; fi
1215

    
1216
        if [ -z "${PBI_MAKEPORT}" ]; then
1217
                usage_make_pbi
1218
        fi
1219
}
1220

    
1221
# Parse the update command line
1222
parse_update_pbi_cmdline() {
1223
        while [ $# -gt 0 ]; do
1224
                case "$1" in
1225
                -c)	PBI_UPCHECK="YES" ;; 
1226
       --check-all)	PBI_UPCHECK="ALL" ;; 
1227
    --disable-auto)	PBI_UPENABLEAUTO="NO" ;; 
1228
     --enable-auto)	PBI_UPENABLEAUTO="YES" ;; 
1229
      --update-all)	PBI_UPDATEAPP="ALL" ;; 
1230
                 *)     if [ $# -gt 1 ]; then usage_update_pbi; fi
1231
			if [ -n "$PBI_UPDATEAPP" ] ; then usage_update_pbi ; fi
1232
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
1233
                                exit_err "can't find installed pbi (${1})"
1234
                        fi
1235
                        PBI_UPDATEAPP="$1"
1236
                        ;;
1237
                esac
1238
                shift
1239
        done
1240

    
1241
	if [ "${PBI_UPDATEAPP}" = "ALL" -a -n "${PBI_UPCHECK}" ] ; then
1242
                usage_update_pbi
1243
        fi
1244

    
1245
	# Make sure we aren't trying to enable auto-updating for ALL
1246
	if [ "${PBI_UPDATEAPP}" = "ALL" -a -n "${PBI_UPENABLEAUTO}" ] ; then
1247
                usage_update_pbi
1248
        fi
1249
	if [ -z "${PBI_UPDATEAPP}" -a -n "${PBI_UPENABLEAUTO}" ] ; then
1250
                usage_update_pbi
1251
        fi
1252

    
1253
        if [ -z "${PBI_UPDATEAPP}" -a "${PBI_UPCHECK}" != "ALL" ]; then
1254
                usage_update_pbi
1255
        fi
1256
}
1257

    
1258
# Make some of our required PBI dirs
1259
mk_required_dirs() {
1260
	if [ ! -d "${PBI_APPDIR}" ] ; then mkdir -p ${PBI_APPDIR} >/dev/null 2>/dev/null ; fi
1261
	if [ ! -d "${PBI_XDGCFGDIR}" ] ; then mkdir -p ${PBI_XDGCFGDIR} >/dev/null 2>/dev/null ; fi
1262
	if [ ! -d "${PBI_XDGAPPDIR}" ] ; then mkdir -p ${PBI_XDGAPPDIR} >/dev/null 2>/dev/null ; fi
1263
	if [ ! -d "${PBI_XDGDIRDIR}" ] ; then mkdir -p ${PBI_XDGDIRDIR} >/dev/null 2>/dev/null ; fi
1264
	if [ ! -d "${PBI_XDGICONDIR}" ] ; then mkdir -p ${PBI_XDGICONDIR} >/dev/null 2>/dev/null ; fi
1265
	if [ ! -d "${PBI_XDGMIMEDIR}" ] ; then mkdir -p ${PBI_XDGMIMEDIR} >/dev/null 2>/dev/null ; fi
1266
	if [ ! -d "${PBI_RCDIR}" ] ; then mkdir -p ${PBI_RCDIR} >/dev/null 2>/dev/null ; fi
1267
	if [ ! -d "${PBI_HASHDIR}" ] ; then mkdir -p ${PBI_HASHDIR} >/dev/null 2>/dev/null ; fi
1268
	if [ ! -d "${PBI_DBAPPDIR}" ] ; then mkdir -p ${PBI_DBAPPDIR} >/dev/null 2>/dev/null ; fi
1269
	if [ ! -d "${PBI_DBKEYDIR}" ] ; then mkdir -p ${PBI_DBKEYDIR} >/dev/null 2>/dev/null ; fi
1270
	if [ ! -d "${PBI_DBMIRRORDIR}" ] ; then mkdir -p ${PBI_DBMIRRORDIR} >/dev/null 2>/dev/null ; fi
1271
	if [ ! -d "${PBI_DBICONDIR}" ] ; then mkdir -p ${PBI_DBICONDIR} >/dev/null 2>/dev/null ; fi
1272
	if [ ! -d "${PBI_DBINDEXDIR}" ] ; then mkdir -p ${PBI_DBINDEXDIR} >/dev/null 2>/dev/null ; fi
1273
	if [ ! -d "${PBI_DBREPODIR}" ] ; then mkdir -p ${PBI_DBREPODIR} >/dev/null 2>/dev/null ; fi
1274
	if [ ! -d "${PBI_DBHASHQUEUEDIR}" ] ; then mkdir -p ${PBI_DBHASHQUEUEDIR} >/dev/null 2>/dev/null ; fi
1275

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

    
1279
	for cDir in $PBI_APPDIR $PBI_DBAPPDIR $PBI_DBHASHQUEUEDIR $PBI_XDGCFGDIR $PBI_XDGAPPDIR $PBI_XDGDIRDIR $PBI_XDGICONDIR $PBI_XDGMIMEDIR
1280
	do	
1281
		chown root:${PBI_INSTALLGROUP} ${cDir}
1282
		chmod 775 ${cDir}
1283
	done
1284

    
1285
	# Make sure the hash-dirty file can be written to by all
1286
	touch ${PBI_DBDIRTYFILE}
1287
	chown root:${PBI_INSTALLGROUP} ${PBI_DBDIRTYFILE}
1288
	chmod 664 ${PBI_DBDIRTYFILE}
1289
}
1290

    
1291
# Get the absolute path of a dir, even a realative dir. 'realpath' doesn't work here
1292
get_abspath() {
1293
	D=`dirname "$1"`
1294
	B=`basename "$1"`
1295
	if [ "$D" = "/" ] ; then
1296
		_ABSPATH="/$B"
1297
	else
1298
		_ABSPATH="`cd \"$D\" 2>/dev/null && pwd || echo \"$D\"`/$B"
1299
	fi
1300
}
1301

    
1302

    
1303
# Initialize some vars
1304
init_vars() {
1305

    
1306
	# Set sys vars
1307
	REALARCH="`uname -m`"
1308
	ARCH="$REALARCH"
1309

    
1310
        # Where is pbi-manager installed?
1311
        PROGBASE=/usr/local
1312
	SYS_LOCALBASE=/usr/local
1313
	if [ -z "${PBI_APPDIR}" -o "`basename $0`" = "pbi_makeport_chroot" ] ; then
1314
		PBI_APPDIR="/usr/pbi"
1315
        fi
1316
	# Set the FreeBSD Major & Release
1317
  	FBSDREL=`uname -r`
1318
	FBSDMAJOR=${FBSDREL%%.*}
1319

    
1320
	PBI_CHROOTFILE="${PBI_APPDIR}/.pbi-world-$ARCH.txz"
1321
	if [ `id -u` = "0" ] ; then 
1322
		PBI_HASHDIR="${PBI_APPDIR}/.hashdir"
1323
	else
1324
		PBI_HASHDIR="${PBI_APPDIR}/.hashdir-`whoami`"
1325
	fi
1326
	PBI_AB_BUILDERS=1
1327
	PBI_XDGCFGDIR="${PBI_APPDIR}/etc/xdg/menus"
1328
	PBI_XDGAPPDIR="${PBI_APPDIR}/share/applications"
1329
	PBI_XDGDIRDIR="${PBI_APPDIR}/share/desktop-directories"
1330
	PBI_XDGICONDIR="${PBI_APPDIR}/share/icons/hicolor"
1331
	PBI_XDGMIMEDIR="${PBI_APPDIR}/share/mime/packages"
1332
	PBI_RCDIR="${SYS_LOCALBASE}/etc/rc.d"
1333
	PBI_ETCCONF="${SYS_LOCALBASE}/etc/pbi.conf"
1334
	PCBSD_ETCCONF="${SYS_LOCALBASE}/etc/pcbsd.conf"
1335
	PBI_DEFAULT_ICON="${PROGBASE}/share/pbi-manager/icons/default.png"
1336
	PBI_DEFAULT_ICON_CHROOT="/default.png"
1337
	PBI_PATCH_ICON="${PROGBASE}/share/pbi-manager/icons/patch.png"
1338
	PBI_LDCONFIGFILE="${PROGBASE}/etc/ldpbiconfig"
1339
	PBI_LDCONFIGRC="${PROGBASE}/etc/rc.d/ldpbiconfig"
1340
	PROGVERSION="1.0"
1341
	PBIDSLEEP="300"		# Amount of time to sleep before waking up pbid
1342
	PBI_LOG_LINES="500"
1343
	PBI_INSTALLGROUP="operator"
1344

    
1345
	# What dirs do we build hash-lists of
1346
	HASH_SEARCH_DIRS="lib kde4/lib share include info man"
1347

    
1348
	# What dbus dirs do we parse for setting up services
1349
	DBUS_SEARCH_DIRS="share/dbus-1 kde4/share/dbus-1 gnome/share/dbus-1"
1350

    
1351
	# Don't modify unless you know what your doing!
1352
	MOD_PREINS="pre-install.sh"
1353
	MOD_POSTINS="post-install.sh"
1354
	MOD_PREREM="pre-remove.sh"
1355
	MOD_XDGDESK_DIR="xdg-desktop"
1356
	MOD_XDGMENU_DIR="xdg-menu"
1357
	MOD_XDGMIME_DIR="xdg-mime"
1358
	MOD_EXTLINKFILE="external-links"
1359
	MOD_AUTOEXTLINKFILE=".auto-external-links"
1360
	PBI_ADD_GUIDISPLAY="NO"
1361
	PBI_ADD_INFODISPLAY="NO"
1362
	PBI_ADD_LICDISPLAY="NO"
1363
	PBI_APPDESK_DIR=".${MOD_XDGDESK_DIR}"
1364
	PBI_APPMENU_DIR=".${MOD_XDGMENU_DIR}"
1365
	PBI_APPMIME_DIR=".${MOD_XDGMIME_DIR}"
1366
	PBI_BUILD_USERS=""
1367
	PBI_BUILD_GROUPS=""
1368
	PBI_INS_USERSFILE=".pbi-uids"
1369
	PBI_INS_GROUPSFILE=".pbi-gids"
1370
	PBI_DESKADD="NO"
1371
	PBI_MENUADD="NO"
1372
	PBI_MIMEADD="NO"
1373
	PBI_PATHADD="NO"
1374
	PBI_DESKDEL="NO"
1375
	PBI_MAKECONF="/etc/pbi-make.conf"
1376
	PBI_MENUDEL="NO"
1377
	PBI_MIMEDEL="NO"
1378
	PBI_PATHDEL="NO"
1379
	PBI_DELETENAME=""
1380
	PBI_FAKEBIN_DIR=".sbin"
1381
	PBI_FILENAME=""
1382
	PBI_FORCEADD="NO"
1383
	PBI_HASHLIST=".pbi-hash-list"
1384
	PBI_INDEXREFRESH="24" # Hours to wait until we re-download PBI indexes
1385
	PBI_INDEXUPFILE="pbi-index-$FBSDMAJOR"
1386
	PBI_METAUPFILE="pbi-meta-$FBSDMAJOR"
1387
	PBI_INFONAME=""
1388
	PBI_INS_DESKSCRIPT="install-desktop-icons.sh"
1389
	PBI_INS_MENUSCRIPT="install-menu-icons.sh"
1390
	PBI_INS_MIMESCRIPT="install-mime.sh"
1391
	PBI_INS_PATHSCRIPT="install-pathlinks.sh"
1392
	PBI_ICDIR="pbi-shared-icons"
1393
	PBI_LISTREPO_UP=""
1394
	PBI_LISTREPO_DOWN=""
1395
	PBI_LISTREPO_MIRROR=""
1396
	PBI_LICAGREE="NO"
1397
	PBI_LICENSEFILE="LICENSE"
1398
	PBI_PATCHVERSION=""
1399
	PBI_PATCHTARGET=""
1400
	PBI_REMOTEFETCH=""
1401
	PBI_REMOTEFETCHONLY=""
1402
	PBI_RESOURCE_DIR="resources"
1403
	PBI_SS_ICON="__PBI_ICON__"
1404
	PBI_SS_ARCHIVE="__PBI_ARCHIVE__"
1405
	PBI_SSLPRIVKEY=""
1406
	PBI_TMPDIR="/tmp/.PBI.$$"
1407
	PBI_TMPHASHLIST=""
1408
	PBI_UPCHECK=""
1409
	PBI_UPDATEAPP=""
1410
	PBI_UNINS_DESKSCRIPT="uninstall-desktop-icons.sh"
1411
	PBI_UNINS_MENUSCRIPT="uninstall-menu-icons.sh"
1412
	PBI_UNINS_MIMESCRIPT="uninstall-mime.sh"
1413
	PBI_UNINS_PATHSCRIPT="uninstall-pathlinks.sh"
1414

    
1415
        # User overridable variables
1416
	MKDELBUILD=""
1417
	MKDEBUG=""
1418
	MKTMPFS=""
1419
	PBI_AB_ARCHIVENUM=""
1420
	PBI_AB_CONFDIR=""
1421
	PBI_AB_GENPATCH="NO"
1422
	PBI_AB_HELPS=""
1423
	PBI_AB_OUTDIR=""
1424
	PBI_AB_SSLPRIVKEY=""
1425
	PBI_AB_PRUNE=""
1426
	PBI_AB_TMPFS=""
1427
	PBI_BUILDONLY="NO"
1428
	PBI_CAUTHOR=""
1429
	PBI_CBACKUP=""
1430
	PBI_CBACKUPTARGET=""
1431
	PBI_CHECKSCRIPTS=""
1432
	PBI_CICON=""
1433
	PBI_CNAME=""
1434
        PBI_CONFDIR=""
1435
	PBI_CONFFILE="pbi.conf"
1436
        PBI_CONF_SCRIPTSDIR="scripts/"
1437
	PBI_CREATE_OUTDIR="$HOME"
1438
	PBI_CREATE_HASHLIST="YES"
1439
	PBI_CUPDATE=""
1440
	PBI_CWEB=""
1441
	if [ -z "${PBI_DBDIR}" ] ; then
1442
		PBI_DBDIR="/var/db/pbi"
1443
	fi
1444
	PBI_DBAPPDIR="${PBI_DBDIR}/installed"
1445
	PBI_DBDIRTYFILE="${PBI_DBDIR}/.hashdirty"
1446
	PBI_DBHASHQUEUEDIR="${PBI_DBDIR}/.hashqueue"
1447
	PBI_DBICONDIR="${PBI_DBDIR}/repo-icons"
1448
	PBI_DBINDEXDIR="${PBI_DBDIR}/index"
1449
	PBI_DBKEYDIR="${PBI_DBDIR}/keys"
1450
	PBI_DBMIRRORDIR="${PBI_DBDIR}/mirrors"
1451
	PBI_DBREPODIR="${PBI_DBDIR}/repos"
1452
	PBI_DISABLEHASHDIR="NO"
1453
	PBI_GUITOPBANNER="gui_banner.png"
1454
	PBI_GUISIDEBANNER="gui_sidebanner.png"
1455
	PBI_KEEPBUILDFILES="NO"
1456
	PBI_MAKEPORT=""
1457
	PBI_MAKEPREFIX=""
1458
	PBI_MAKEOPTS=""
1459
	PBI_MKPORTBEFORE=""
1460
	PBI_MKPORTAFTER=""
1461
	PBI_PORTSDIR=""
1462
	PBI_PROGAUTHOR=""
1463
	PBI_PROGMDATE=""
1464
	PBI_PROGEPOCH=""
1465
	PBI_PROGNAME=""
1466
	PBI_PROGDIRNAME=""
1467
	PBI_PROGDIRPATH=""
1468
	PBI_PROGICON=""
1469
	PBI_PROGREVISION=""
1470
	PBI_PROGVERSION=""
1471
	PBI_PROGWEB=""
1472
	PBI_PRUNEBUILDPORTS="YES"
1473
	PBI_SKIPCHECKSUM=""
1474
	PBI_SKIPSIGVERIFY=""
1475
	PBI_USESYSGL="YES"
1476
	PBI_USESYSFONTS="YES"
1477
	PBI_VERBOSE="NO"
1478
	PORTSDIR="/usr/ports"
1479

    
1480
}
1481

    
1482
detect_pkgng()
1483
{
1484
	export PORTSDIR
1485
	# Are we using pkgng?
1486
	WITH_PKGNG=$(make -f ${PORTSDIR}/Mk/bsd.port.mk -V WITH_PKGNG)
1487
        if [ -n "${WITH_PKGNG}" ]; then
1488
                export PKGNG=1
1489
                export PKG_ADD="pkg add"
1490
                export PKG_DELETE="pkg delete -y -f"
1491
        else
1492
                export PKGNG=0
1493
                export PKG_ADD=pkg_add
1494
                export PKG_DELETE=pkg_delete
1495
        fi
1496

    
1497
}
1498

    
1499
# Set and export vars used by module scripts
1500
export_script_vars() {
1501
	# Load some initial values
1502
	get_pbi_progdir
1503
	get_pbi_progversion
1504

    
1505
	export PBI_PROGNAME PBI_PROGDIRNAME PBI_PROGDIRPATH PBI_PROGVERSION PBI_RCDIR 
1506
	export SYS_LOCALBASE PBI_FAKEBIN_DIR
1507
}
1508

    
1509
# init tmpdir
1510
init_tmpdir() {
1511
	if [ -d "${PBI_TMPDIR}" ] ; then return; fi
1512
	if [ -z "${PBI_TMPDIR}" ] ; then return ; fi
1513
	if [ "${PBI_TMPDIR}" = "/" ] ; then return ; fi
1514
	if [ -e "${PBI_TMPDIR}" ] ; then rm -rf "${PBI_TMPDIR}" ; fi
1515
	mkdir -p "${PBI_TMPDIR}"
1516
}
1517

    
1518
# rm tmpdir
1519
rm_tmpdir() {
1520
	if [ -z "${PBI_TMPDIR}" -o "${PBI_TMPDIR}" = "/" ] ; then return 0; fi
1521
	if [ -e "${PBI_TMPDIR}" ] ; then rm -rf "${PBI_TMPDIR}" ; fi
1522
}
1523

    
1524
# rm tmpdir
1525
rm_buildfiles() {
1526
	if [ "${PBI_KEEPBUILDFILES}" = "YES" ] ; then return ; fi
1527
	if [ -z "$PBI_CHROOTDIR" ] ; then return ; fi
1528
	chroot_make_cleanup
1529
}
1530

    
1531
# Load PBI conf options
1532
load_pbi_conffile() {
1533
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
1534
  	if [ -e "${PBI_CONFDIR}/${PBI_CONFFILE}" ] ; then
1535
		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
1536
		. ${PBI_CONFDIR}/${PBI_CONFFILE}
1537
	fi
1538
}
1539

    
1540
# Get the PBI_PROGVERSION
1541
get_pbi_progversion() {
1542

    
1543
	if [ -z "${PBI_PROGVERSION}" ] ; then
1544
		load_pbi_conffile
1545

    
1546
		# If we have PBI_PROGVERSION now set
1547
		if [ -n "${PBI_PROGVERSION}" ] ; then return 0 ; fi
1548
	else
1549
		return 0
1550
	fi
1551

    
1552
	if [ -z "${PBI_PROGVERSION}" -a -n "${PORTSDIR}" -a -n "${PBI_MAKEPORT}" ] ; then
1553
		PORTVER="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V DISTVERSION PORTSDIR=${PORTSDIR} 2>/dev/null`"
1554

    
1555
  		# Check if we have a portrevision to use in version number
1556
  		PORTREV=""
1557
  		PORTREV="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PORTREVISION PORTSDIR=${PORTSDIR} 2>/dev/null`"
1558
  		if [ -n "${PORTREV}" -a "${PORTREV}" != "0" ]
1559
 		then
1560
			PBI_PROGVERSION="${PORTVER}_${PORTREV}"
1561
		else
1562
			PBI_PROGVERSION="${PORTVER}"
1563
		fi
1564

    
1565
		if [ -z "${PBI_PROGVERSION}" ] ; then
1566
			echo "Warning: Unable to set PBI_PROGVERSION with:"
1567
		        echo "make -C ${PORTSDIR}/${PBI_MAKEPORT} -V DISTVERSION PORTSDIR=${PORTSDIR}"
1568
		fi
1569
	else
1570
		echo "PBI_PROGVERSION - $PBI_PROGVERSION - PORTSDIR - ${PORTSDIR} - $PBI_MAKEPORT - $PBI_MAKE_PORT - pbi - $pbi"
1571
		exit_err "Failed to locate PBI_PROGVERSION"
1572
	fi
1573

    
1574
	# If we have a REVISION, use it as well
1575
	if [ -n "$PBI_PROGREVISION" ] ; then
1576
		PBI_PROGVERSION="${PBI_PROGVERSION}_${PBI_PROGREVISION}"
1577
	fi
1578
}
1579

    
1580

    
1581
# Get the PBI_PROGNAME
1582
get_pbi_progname() {
1583
	if [ -z "${PBI_PROGNAME}" -o "${PBI_PROGNAME}" = " " ] ; then
1584
		load_pbi_conffile
1585
	else
1586
		return 0
1587
	fi
1588

    
1589
	if [ -z "${PBI_PROGNAME}" -a -n "${PORTSDIR}" -a -n "${PBI_MAKEPORT}" ] ; then
1590
		# Get the proper package name from the prefix + name + suffix
1591
		local pkgPrefix="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PKGNAMEPREFIX PORTSDIR=${PORTSDIR}`"
1592
		local pkgName="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PORTNAME PORTSDIR=${PORTSDIR}`"
1593
		local pkgSuffix="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PKGNAMESUFFIX PORTSDIR=${PORTSDIR}`"
1594
		PBI_PROGNAME="${pkgPrefix}${pkgName}${pkgSuffix}"
1595
	else
1596
		exit_err "Failed to locate PBI_PROGNAME"
1597
	fi
1598
}
1599

    
1600
# Get the PBI PROGDIR Name
1601
get_pbi_progdir() {
1602
	if [ -z "${PBI_PROGNAME}" ] ; then
1603
		get_pbi_progname
1604
	fi
1605

    
1606
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
1607
	if [ -z "${PBI_PROGDIRNAME}" ] ; then
1608
		PBI_PROGDIRNAME="${tmp}-${ARCH}"
1609
	fi
1610
	if [ -z "${PBI_PROGDIRPATH}" ] ; then
1611
		PBI_PROGDIRPATH="${PBI_APPDIR}/${PBI_PROGDIRNAME}"
1612
	fi
1613
}
1614

    
1615
# Helper function to exit after a error, and do some cleanup
1616
exit_err() {
1617
	echo -e "`basename ${0}`: ${1}"
1618
	rm_tmpdir
1619
	rm_buildfiles
1620
	rm_pbipatchfiles
1621
	chroot_make_cleanup
1622
	clean_remote_dl
1623
	exit 255
1624
}
1625

    
1626
# Check if we need to cleanup patch files
1627
rm_pbipatchfiles() {
1628
	if [ -z "${_pbiNewDir}${_pbiOldDir}${_pbiPatchDir}" ] ; then
1629
		return
1630
	else
1631
		echo "Cleaning up patch data..."
1632
	fi
1633

    
1634
	# If we used tmpfs, unmount the dirs
1635
        if [ "$PBI_MP_TMPFS" = "YES" ] ; then
1636
		umount "${_pbiNewDir}" 2>/dev/null
1637
		umount "${_pbiOldDir}" 2>/dev/null
1638
		umount "${_pbiPatchDir}" 2>/dev/null
1639
	fi
1640

    
1641
	if [ -n "${_pbiNewDir}" -a -d "${_pbiNewDir}" -a "${_pbiNewDir}" != "/" ] ; then
1642
	 	rm -rf "${_pbiNewDir}" >/dev/null 2>/dev/null
1643
	 	chflags -R noschg "${_pbiNewDir}" >/dev/null 2>/dev/null
1644
	 	rm -rf "${_pbiNewDir}" >/dev/null 2>/dev/null
1645
	fi
1646
	if [ -n "${_pbiOldDir}" -a -d "${_pbiOldDir}" -a "${_pbiOldDir}" != "/" ] ; then
1647
	 	rm -rf "${_pbiOldDir}" >/dev/null 2>/dev/null
1648
	 	chflags -R noschg "${_pbiOldDir}" >/dev/null 2>/dev/null
1649
	 	rm -rf "${_pbiOldDir}" >/dev/null 2>/dev/null
1650
	fi
1651
	if [ -n "${_pbiPatchDir}" -a -d "${_pbiPatchDir}" -a "${_pbiPatchDir}" != "/" ] ; then
1652
	 	rm -rf "${_pbiPatchDir}" >/dev/null 2>/dev/null
1653
	 	chflags -R noschg "${_pbiPatchDir}" >/dev/null 2>/dev/null
1654
	 	rm -rf "${_pbiPatchDir}" >/dev/null 2>/dev/null
1655
	fi
1656
}
1657

    
1658
# Check if we need to delete a remotely dl'd file
1659
clean_remote_dl() {
1660
	# If this was a remote fetch, remove dl'd file
1661
	if [ "$PBI_REMOTEFETCH" = "YES" -a -n "$PBI_FILENAME" ]; then 
1662
		rm "$PBI_FILENAME" >/dev/null 2>/dev/null
1663
	fi
1664
}
1665

    
1666
# Set port make options from config
1667
set_make_options() {
1668

    
1669
	# Set the LOCALBASE
1670
	LOCALBASE="${PBI_PROGDIRPATH}"
1671
	if [ -e "${LOCALBASE}" ] ; then 
1672
		if [ "$MKDELBUILD" != "YES" ] ; then
1673
			exit_err "${LOCALBASE} already exists! Delete it before doing a rebuild"
1674
		else
1675
			if [ -z "${LOCALBASE}" ] ; then
1676
				exit_err "null LOCALBASE, this shouldn't happen"
1677
			fi
1678
			rm -rf "${LOCALBASE}"
1679
		fi
1680
	fi
1681

    
1682
	local MAKE_CONF="/etc/make.conf"
1683

    
1684
	echo "LOCALBASE=${LOCALBASE}" >> ${MAKE_CONF}
1685
	echo "PACKAGE_BUILDING=yes" >> ${MAKE_CONF}
1686
	echo "BATCH=yes" >> ${MAKE_CONF}
1687
	echo "NO_IGNORE=yes" >> ${MAKE_CONF}
1688
	echo "PACKAGE_BUILDING=yes" >> ${MAKE_CONF}
1689

    
1690
	echo "WRKDIRPREFIX=/usr/wrkdirprefix" >> ${MAKE_CONF}
1691
	echo "DEPENDS_CLEAN=YES" >> ${MAKE_CONF}
1692

    
1693
	if [ -n "$PBI_MAKEOPTS" ] ; then
1694
		# Check if we have custom make opts
1695
		echo "${PBI_MAKEOPTS}" >> ${MAKE_CONF}
1696
	fi
1697

    
1698
	# Link LOCALBASE -> /usr/local
1699
	mkdir -p ${LOCALBASE}
1700
	rm -rf /usr/local
1701
	ln -s ${LOCALBASE} /usr/local
1702

    
1703
	# Make sure ldconfig is primed
1704
	/etc/rc.d/ldconfig start
1705

    
1706
	# Check if using ccache directory
1707
	if [ -d "/.ccache" ] ; then
1708
		echo "Enabling ccache..."
1709
		cd /usr/ports/devel/ccache 
1710
		make install clean
1711
		if [ $? -eq 0 ] ; then
1712
			# Setup environment variables
1713
			CCACHE_PATH="/usr/bin:${LOCALBASE}/bin"
1714
			export CCACHE_PATH
1715
			CCACHE_DIR="/.ccache"
1716
			export CCACHE_DIR
1717
			PATH="${LOCALBASE}/libexec/ccache:${PATH}"
1718
			export PATH
1719

    
1720
			# Setup make configuration
1721
			echo ".if !defined(NO_CCACHE)" >> ${MAKE_CONF}
1722
			echo "  CC=${LOCALBASE}/libexec/ccache/world/cc" >> ${MAKE_CONF}
1723
			echo "  CXX=${LOCALBASE}/libexec/ccache/world/c++" >> ${MAKE_CONF}
1724
			echo ".endif" >> ${MAKE_CONF}
1725
		else
1726
			echo "Failed installing ccache! Continuing without it..."
1727
		fi
1728
	fi
1729

    
1730
	PATH="${PATH}:/usr/local/bin:/usr/local/sbin:${LOCALBASE}/bin:${LOCALBASE}/sbin"
1731
	export PATH
1732

    
1733
	FORCE_PKG_REGISTER="Y"
1734
	export FORCE_PKG_REGISTER
1735

    
1736
}
1737

    
1738
# Confirm we are running as root
1739
require_root() {
1740
  if [ `id -u` != "0" ] ; then
1741
     exit_err "Must be run as root!"
1742
  fi 
1743
}
1744

    
1745
# Confirm we are running as root or the proper group for installation
1746
require_root_or_group() {
1747
  if [ `id -u` = "0" ] ; then return 0 ; fi 
1748
  touch ${PBI_APPDIR}/.ptest.$$ >/dev/null 2>/dev/null
1749
  if [ "$?" = "0" ] ; then 
1750
	rm ${PBI_APPDIR}/.ptest.$$ >/dev/null 2>/dev/null
1751
	return 0
1752
  fi
1753
  exit_err "Must be run as root or a member of the $PBI_INSTALLGROUP group!"
1754
}
1755

    
1756
# Function to get the username from a file
1757
get_username_from_file() {
1758
	if [ -f "${1}" ] ; then 
1759
		FILEUSER=`ls -al ${1} | awk '{print $3}'`
1760
		export FILEUSER
1761
		return 0
1762
	fi
1763
	if [ -d "${1}" ] ; then 
1764
		FILEUSER=`ls -al ${1} | grep -v "total" | head -n 1 | awk '{print $3}'`
1765
		export FILEUSER
1766
		return 0
1767
	fi
1768
	exit_err "Invalid file for usercheck!"
1769
}
1770

    
1771
# Start the make patch process
1772
pbi_makepatch_init() {
1773
  	require_root
1774
	init_tmpdir
1775
	parse_makepatch_pbi_cmdline "$@"
1776

    
1777
	# Create a new patch file from the two PBIs specified
1778
	make_pbi_patchfile "${PBI_FILENAME}" "${PBI_OLDFILENAME}" "${PBI_PATCHOUTDIR}"
1779
}
1780

    
1781
# Remove a repo from the DB
1782
pbi_deleterepo_init() {
1783
  	require_root
1784
	parse_deleterepo_pbi_cmdline "$@"
1785

    
1786
	delete_pbi_repo
1787
}
1788

    
1789
# Do the removal of a PBI repo
1790
delete_pbi_repo() {
1791
	# Make sure this repo exists
1792
	ls ${PBI_DBREPODIR}/${PBI_DELREPO_ID}.* >/dev/null 2>/dev/null
1793
	if [ "$?" != "0" ] ; then
1794
		exit_err "No such repo ID: ${PBI_DELREPO_ID}"
1795
	fi
1796
	
1797
	_md5=`ls ${PBI_DBREPODIR}/${PBI_DELREPO_ID}.* | sed "s|^${PBI_DBREPODIR}/${PBI_DELREPO_ID}.||g"`
1798
	if [ -e "${PBI_DBREPODIR}/${PBI_DELREPO_ID}.${_md5}" ] ; then
1799
		rm "${PBI_DBREPODIR}/${PBI_DELREPO_ID}.${_md5}"
1800
	else
1801
		echo "Warning: ${PBI_DELREPO_ID}.${_md5} does not exist in the database."
1802
	fi
1803
	if [ -e "${PBI_DBKEYDIR}/${_md5}.ssl" ] ; then
1804
		rm "${PBI_DBKEYDIR}/${_md5}.ssl"
1805
	else
1806
		echo "Warning: ${_md5}.ssl does not exist in the keys database."
1807
	fi
1808
	if [ -e "${PBI_DBMIRRORDIR}/${_md5}" ] ; then
1809
		rm "${PBI_DBMIRRORDIR}/${_md5}"
1810
	else
1811
		echo "Warning: ${_md5} does not exist in the mirror database."
1812
	fi
1813
	
1814
	# See if we need to remove a downloaded index file
1815
	if [ -e "${PBI_DBINDEXDIR}/${_md5}-index" ] ; then
1816
		rm "${PBI_DBINDEXDIR}/${_md5}-index"
1817
		rm "${PBI_DBINDEXDIR}/${_md5}-index.time"
1818
	fi
1819

    
1820
	# Make sure we renumber the repos
1821
	renumber_repos
1822

    
1823
	echo "Deleted Repository ${PBI_DELREPO_ID}."
1824

    
1825
}
1826

    
1827
# After deleting a repo, this can be run to renumber the IDs
1828
renumber_repos() {
1829
	_rNum="1"
1830
	for i in `ls ${PBI_DBREPODIR} | sort`
1831
	do
1832
		case `echo ${_rNum} | wc -m | tr -d ' '` in
1833
			2) _rNum="00${_rNum}" ;;
1834
			3) _rNum="0${_rNum}" ;;
1835
			*) ;;
1836
		esac
1837

    
1838
		_md5=`echo ${i} | cut -d '.' -f 2`
1839
		mv "${PBI_DBREPODIR}/${i}" "${PBI_DBREPODIR}/${_rNum}.${_md5}"
1840

    
1841
		_rNum=`expr ${_rNum} + 1`
1842
	done
1843
}
1844

    
1845
# Add a new repo to the db
1846
pbi_addrepo_init() {
1847
  	require_root
1848
	parse_addrepo_pbi_cmdline "$@"
1849

    
1850
	# Create a new repo file
1851
	add_pbi_repo
1852
}
1853

    
1854
# Extract the repo and add it to the DB
1855
add_pbi_repo() {
1856
	init_tmpdir
1857
	tar xvf "${PBI_ADDREPO_FILE}" -C ${PBI_TMPDIR} >/dev/null 2>/dev/null
1858
	if [ "$?" != "0" ] ; then
1859
		exit_err "Failed to read ${PBI_ADDREPO_FILE}"
1860
	fi
1861
	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
1862
		exit_err "Improperly packaged repo file!"
1863
	fi
1864

    
1865
	# Make sure we don't have a duplicate repo key
1866
	for tr in ${PBI_PUBKEYS}
1867
	do
1868
		diff -q ${tr} ${PBI_TMPDIR}/repokey.ssl >/dev/null 2>/dev/null
1869
		if [ "$?" = "0" ] ; then
1870
			exit_err "Repo with identical key already registered!"
1871
		fi
1872
	done
1873

    
1874
	# Figure out the next repo number
1875
	get_next_repo_num
1876

    
1877
	_md5=`md5 -q ${PBI_TMPDIR}/repo-url`
1878
	_url=`cat ${PBI_TMPDIR}/repo-url`
1879
	_desc=`cat ${PBI_TMPDIR}/repo-desc`
1880
	echo "URL: ${_url}" > ${PBI_DBREPODIR}/${_rNum}.${_md5}
1881
	echo "Desc: ${_desc}" >> ${PBI_DBREPODIR}/${_rNum}.${_md5}
1882
	cp ${PBI_TMPDIR}/repo-mirror ${PBI_DBMIRRORDIR}/${_md5}
1883
	cp "${PBI_TMPDIR}/repokey.ssl" "${PBI_DBKEYDIR}/${_md5}.ssl"
1884
	chmod 755 "${PBI_DBKEYDIR}/${_md5}.ssl"
1885
	
1886
	rm_tmpdir
1887

    
1888
	echo "Added new repo: \"${_desc}\" to the database."
1889

    
1890
}
1891

    
1892
# Function to do listing of installed repos, and return next available number
1893
get_next_repo_num() {
1894
	_rNum="0"
1895
	for i in `ls ${PBI_DBREPODIR} | sort`
1896
	do
1897
		_rNum=`expr ${_rNum} + 1`
1898
	done
1899

    
1900
	_rNum=`expr ${_rNum} + 1`
1901

    
1902
	case `echo ${_rNum} | wc -m | tr -d ' '` in
1903
		2) _rNum="00${_rNum}" ;;
1904
		3) _rNum="0${_rNum}" ;;
1905
		*) ;;
1906
	esac
1907

    
1908
	export _rNum
1909
}
1910

    
1911
# Start the make patch process
1912
pbi_makerepo_init() {
1913
  	require_root
1914
	parse_makerepo_pbi_cmdline "$@"
1915

    
1916
	# Create a new repo file
1917
	make_pbi_repo
1918
}
1919

    
1920
# Create the repo .rpo file
1921
make_pbi_repo() {
1922
	init_tmpdir
1923

    
1924
	mkdir ${PBI_TMPDIR}/.mkrepo
1925
	cp ${PBI_MKREPO_KEY} ${PBI_TMPDIR}/.mkrepo/repokey.ssl
1926
	echo "${PBI_MKREPO_URL}" >  ${PBI_TMPDIR}/.mkrepo/repo-url
1927
	echo "${PBI_MKREPO_DESC}" >  ${PBI_TMPDIR}/.mkrepo/repo-desc
1928
	echo "${PBI_MKREPO_MIRROR}" | sed 's|,|\
1929
|g' > ${PBI_TMPDIR}/.mkrepo/repo-mirror
1930

    
1931

    
1932
	tar cvzf ${PBI_MKREPO_OUTDIR}/pbi-repo.rpo -C ${PBI_TMPDIR}/.mkrepo . >/dev/null 2>/dev/null
1933
	echo "New PBI Repo created: ${PBI_MKREPO_OUTDIR}/pbi-repo.rpo"
1934

    
1935
	rm_tmpdir
1936
}
1937

    
1938
# Init the metatool
1939
pbi_mt_init() {
1940
	parse_mt_pbi_cmdline "$@"
1941
	case $PBI_MT_MODE in
1942
		ADD) if [ "$PBI_MT_TYPE" = "CAT" ] ; then
1943
			do_pbi_mt_add_cat
1944
		     else
1945
			do_pbi_mt_add_app
1946
		     fi ;;
1947
		REM) if [ "$PBI_MT_TYPE" = "CAT" ] ; then
1948
			do_pbi_mt_rem_cat "${PBI_MT_REMNAME}" "${PBI_MT_METAFILE}"
1949
		     else
1950
			do_pbi_mt_rem_app "${PBI_MT_REMNAME}" "${PBI_MT_METAFILE}"
1951
		     fi ;;
1952
		  *) ;;
1953
	esac
1954
}
1955

    
1956
do_pbi_mt_add_cat() {
1957
	init_tmpdir
1958

    
1959
	# Remove any duplicate name
1960
	do_pbi_mt_rem_cat "${PBI_MT_ADDNAME}" "${PBI_MT_METAFILE}"
1961

    
1962
	cp ${PBI_MT_METAFILE} ${PBI_TMPDIR}/.meta.$$
1963
	echo "Cat=${PBI_MT_ADDNAME};${PBI_MT_ADDICON};${PBI_MT_ADDDESC};" \
1964
	>> ${PBI_TMPDIR}/.meta.$$
1965
	sort ${PBI_TMPDIR}/.meta.$$ > "${PBI_MT_METAFILE}"
1966
	rm ${PBI_TMPDIR}/.meta.$$
1967
	
1968
}
1969

    
1970
do_pbi_mt_add_app() {
1971
	init_tmpdir
1972
	# Remove any duplicate name
1973
	do_pbi_mt_rem_app "${PBI_MT_ADDNAME}" "${PBI_MT_METAFILE}"
1974

    
1975
	cp ${PBI_MT_METAFILE} ${PBI_TMPDIR}/.meta.$$
1976
	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;" \
1977
	>> ${PBI_TMPDIR}/.meta.$$
1978
	sort ${PBI_TMPDIR}/.meta.$$ > "${PBI_MT_METAFILE}"
1979
	rm ${PBI_TMPDIR}/.meta.$$
1980
}
1981

    
1982
do_pbi_mt_rem_cat() {
1983
	sed -i '' "\|^Cat=${1};|d" "${2}"
1984
}
1985

    
1986
do_pbi_mt_rem_app() {
1987
	sed -i '' "\|^App=${1};|d" "${2}"
1988
}
1989

    
1990
# Init the indextool
1991
pbi_it_init() {
1992
	parse_it_pbi_cmdline "$@"
1993
	case $PBI_IT_MODE in
1994
		ADD) do_pbi_it_add ;; 
1995
		REM) do_pbi_it_rem ;; 
1996
		  *) ;;
1997
	esac
1998
}
1999

    
2000
# Remove a target PBI from an index
2001
do_pbi_it_rem() {
2002
	init_tmpdir
2003
	_pbilow="`echo ${PBI_IT_REMNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2004

    
2005
	cat "${PBI_IT_REMINDEX}" | grep -v "^${_pbilow}:${PBI_IT_REMARCH}:${PBI_IT_REMVER}" \
2006
		> "${PBI_TMPDIR}/.indextmp"
2007
	sort ${PBI_TMPDIR}/.indextmp > "${PBI_IT_REMINDEX}"
2008

    
2009
	rm_tmpdir
2010
}
2011

    
2012
# Add a new PBI to the specified INDEX file
2013
do_pbi_it_add() {
2014
	init_tmpdir
2015

    
2016
	# First load values from the target PBI
2017
	PBI_FILENAME="$PBI_IT_ADDFILE"
2018
	load_info_from_header
2019

    
2020
	# Get the name in lower-case
2021
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2022
	
2023
	# Prune any old copies of this app from the index
2024
	prune_from_index "$_pbilow" "$PBI_APPARCH"
2025
	
2026
	# Prune any old copies of this app from the index
2027
	mark_current_active_index "$_pbilow" "$PBI_APPARCH"
2028

    
2029
	# Add the new index entry
2030
	add_to_index
2031
	rm_tmpdir
2032
}
2033

    
2034
# Mark any current versions of this PBI as active in the index
2035
mark_current_active_index() {
2036

    
2037
	while read iLine
2038
	do
2039
		echo "$iLine" | grep "^${1}:${2}:" >/dev/null 2>/dev/null
2040
		if [ "$?" != "0" ] ; then
2041
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
2042
			continue
2043
		fi
2044
	 	echo "$iLine" | sed 's|:current|:active|' >> ${PBI_TMPDIR}/.indextmp	
2045

    
2046
	done < $PBI_IT_ADDINDEX	
2047
	mv "${PBI_TMPDIR}/.indextmp" "${PBI_IT_ADDINDEX}"
2048
}
2049

    
2050
# Add the specified PBI to the index
2051
add_to_index() {
2052
	mv "${PBI_IT_ADDINDEX}" "${PBI_TMPDIR}/.indextmp"
2053
	local _date=`date '+%s'`
2054
	local _sha256=`sha256 -q ${PBI_FILENAME}`
2055
	local _psize=`du -k ${PBI_FILENAME} | cut -f 1`
2056
	echo "${_pbilow}:${PBI_APPARCH}:${PBI_PROGVERSION}:${_sha256}:${PBI_PROGMDATE}:${PBI_IT_ADDURL}:$_date:${PBI_IT_ADDBPVERS}:current:${_psize}:" >>"${PBI_TMPDIR}/.indextmp"
2057
	sort ${PBI_TMPDIR}/.indextmp > "${PBI_IT_ADDINDEX}"
2058
}
2059

    
2060

    
2061
# Remove a set number of PBIs from the index
2062
prune_from_index() {
2063
	if [ -z "$PBI_IT_ADDKEEP" ]; then return ; fi
2064

    
2065
	local found="0"
2066
	local added="0"
2067
	while read iLine
2068
	do
2069
		echo "$iLine" | grep "^${1}:${2}:" >/dev/null 2>/dev/null
2070
		if [ "$?" != "0" ] ; then
2071
			# Ready to add back the saved lines
2072
			if [ $found -ne 0 ] ; then
2073
				while read fLine
2074
				do
2075
				  if [ $found -le $PBI_IT_ADDKEEP ] ; then
2076
	 			     echo "$fLine" >> ${PBI_TMPDIR}/.indextmp	
2077
				  fi
2078
				  found=`expr $found - 1`
2079
				done < ${PBI_TMPDIR}/.foundtmp
2080
			fi
2081
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
2082
			continue
2083
		fi
2084
		found=`expr $found + 1`
2085
	 	echo "$iLine" >> ${PBI_TMPDIR}/.foundtmp	
2086
	done < $PBI_IT_ADDINDEX	
2087
	mv "${PBI_TMPDIR}/.indextmp" "${PBI_IT_ADDINDEX}"
2088
}
2089

    
2090
# Add a new repo to the db
2091
pbi_browser_init() {
2092
	parse_browse_pbi_cmdline "$@"
2093
	init_tmpdir
2094

    
2095
	# Check if we are doing a category listing, the default if no options
2096
	if [ "$PBI_BROWSE_LISTCATS" = "YES" -o -z "${PBI_BROWSE_LISTALLPBI}${PBI_BROWSE_CAT}${PBI_BROWSE_SEARCH}" ] ; then
2097
		pbi_browse_listcats
2098
	else
2099
		pbi_browse_listpbi
2100
	fi
2101

    
2102
}
2103

    
2104
# List PBIs from a repo
2105
pbi_browse_listpbi() {
2106
	_rArch=`uname -m`
2107

    
2108
	# Figure out which type of display we are doing
2109
	if [ -n "$PBI_BROWSE_LISTALLPBI" ] ; then
2110
		echo "Using RepoID: $PBI_BROWSE_RID"
2111
		echo "Listing all available PBIs"
2112
		grep -i -e "^App=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2113
	elif [ -n "$PBI_BROWSE_CAT" ] ; then
2114
		echo "Using RepoID: $PBI_BROWSE_RID"
2115
		echo "Available PBIs for Category: $PBI_BROWSE_CAT"
2116
		grep -i -e "^App=" -i -e ";${PBI_BROWSE_CAT};" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2117
	elif [ -n "$PBI_BROWSE_SEARCH" ] ; then
2118
		echo "Using RepoID: $PBI_BROWSE_RID"
2119
		echo "Searching for: $PBI_BROWSE_SEARCH"
2120
		grep -i -e "^App=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2121
	else
2122
		exit_err "No valid search variable set!"
2123
	fi
2124

    
2125
	while read app
2126
	do
2127
		line=`echo $app | sed 's|^App=||g'`
2128
		catCheck=`echo $line | cut -d ';' -f 2 2>/dev/null`
2129
		aName=`echo $line | cut -d ';' -f 1 2>/dev/null`
2130

    
2131
		# Make sure this is from the correct category
2132
		if [ -n "$PBI_BROWSE_CAT" ] ; then
2133
			_cCheck=`echo $catCheck | tr '[:lower:]' '[:upper:]'`
2134
			_cCheck2=`echo $PBI_BROWSE_CAT | tr '[:lower:]' '[:upper:]'`
2135
			if [ "$_cCheck" != "$_cCheck2" ]; then 
2136
			continue
2137
			fi
2138
		fi
2139

    
2140
		# Set the displayed arch type
2141
		aArch="$_rArch"
2142

    
2143
		# Make sure this application has an associated PBI available
2144
		check_pbi_update "$aName" "nodisplay" \
2145
		 "$aName" "current" \
2146
		 "$FBSDMAJOR" "$_rArch" "${PBI_BROWSE_RID}"
2147
		if [ "$?" != "0" ] ; then
2148
			# On amd64, see if 32bit version exists
2149
			if [ "$_rArch" = "amd64" ] ; then
2150
				check_pbi_update "$aName" "nodisplay" \
2151
		 		"$aName" "current" \
2152
		 		"$FBSDMAJOR" "i386" "${PBI_BROWSE_RID}"
2153
				if [ "$?" != "0" ] ; then 
2154
					continue
2155
				else
2156
					# Found a 32bit version of the app
2157
					aArch="i386"
2158
				fi
2159
			else
2160
				# Not on amd64, continue on
2161
				continue
2162
			fi
2163
		fi
2164

    
2165
		aIcon=`echo $line | cut -d ';' -f 3`
2166
		aAuthor=`echo $line | cut -d ';' -f 4`
2167
		aUrl=`echo $line | cut -d ';' -f 5`
2168
		aLic=`echo $line | cut -d ';' -f 6`
2169
		aType=`echo $line | cut -d ';' -f 7`
2170
		aKeywords=`echo $line | cut -d ';' -f 8`
2171
		aDesc=`echo $line | cut -d ';' -f 9`
2172
		aRoot=`echo $line | cut -d ';' -f 10`
2173

    
2174
		# Check for a translation to the description
2175
		get_meta_trans "App" "$cName" "${PBI_BROWSE_METAFILE}"
2176
		if [ -n "$MTRANS" ] ; then
2177
			aDesc="$MTRANS"
2178
		fi
2179

    
2180
		# Search the description / keywords
2181
		if [ -n "$PBI_BROWSE_SEARCH" ] ; then
2182
			echo "$aName,$aDesc,$aKeywords,$MTRANS" | grep -i "$PBI_BROWSE_SEARCH" >/dev/null 2>/dev/null
2183
			if [ "$?" != "0" ]; then continue ; fi
2184
		fi
2185

    
2186
		# Get the local icon file
2187
		ext=`echo $aIcon | sed 's/.*\.//'`
2188
		aIcon="${PBI_DBICONDIR}/${PBI_BROWSE_REPOMD5}-${aName}.${ext}"
2189

    
2190
		echo "------------------------------------"
2191
		echo "Application: $aName"
2192
		echo "Version: $PBI_UPNVER"
2193
		if [ -n "$PBI_UPSIZE" ] ; then
2194
			echo "Size: $PBI_UPSIZE"
2195
		fi
2196
		if [ -n "$PBI_BROWSE_LISTALLPBI" ] ; then
2197
			echo "Category: $catCheck"
2198
		fi
2199
		echo "Created: `echo $PBI_UPMDATE`"
2200
		if [ "$aRoot" = "YES" ] ; then
2201
			echo "RootInstall: YES"
2202
		else
2203
			echo "RootInstall: NO"
2204
		fi
2205
		echo "Arch: $aArch"
2206
		echo "Author: $aAuthor"
2207
		echo "URL: $aUrl"
2208
		echo "License: $aLic"
2209
		echo "Type: $aType"
2210
		echo "Keywords: $aKeywords"
2211
		echo "Icon: $aIcon"
2212
		echo "Description: $aDesc"
2213
		echo ""
2214
		if [ "$aRoot" = "YES" ] ; then
2215
			echo "To install this PBI (As Root):"
2216
		else
2217
			echo "To install this PBI:"
2218
		fi
2219
		echo "# pbi_add --rArch $aArch --repo $PBI_BROWSE_RID -r $aName"
2220
		echo ""
2221

    
2222
		
2223
	done < ${PBI_TMPDIR}/.meta.$$
2224

    
2225
}
2226

    
2227
# List available categories for this repository
2228
pbi_browse_listcats() {
2229

    
2230
	echo "Using RepoID: $PBI_BROWSE_RID"
2231
	echo "Available Categories:"
2232
	grep "^Cat=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2233
	while read cat
2234
	do
2235
		line=`echo $cat | sed 's|^Cat=||g'`
2236
		cName=`echo $line | cut -d ';' -f 1`
2237
		cIcon=`echo $line | cut -d ';' -f 2`
2238
		cDesc=`echo $line | cut -d ';' -f 3`
2239
		
2240
		# Check for a translation to the description
2241
		get_meta_trans "Cat" "$cName" "${PBI_BROWSE_METAFILE}"
2242
		if [ -n "$MTRANS" ] ; then
2243
			cDesc="$MTRANS"
2244
		fi
2245

    
2246
		# Get the local icon file
2247
		ext=`echo $cIcon | sed 's/.*\.//'`
2248
		cIcon="${PBI_DBICONDIR}/${PBI_BROWSE_REPOMD5}-${cName}.${ext}"
2249

    
2250
		echo "------------------------------------"
2251
		echo "Category: $cName"
2252
		echo "Icon: $cIcon"
2253
		echo "Description: $cDesc"
2254
		echo ""
2255

    
2256
	done < ${PBI_TMPDIR}/.meta.$$
2257

    
2258
	echo "To view available PBIs for a particular category:"
2259
	echo " % pbi_browser -c <category> <repoid>"
2260
}
2261

    
2262
# Function to check if we have a translated description
2263
get_meta_trans() {
2264
	local tag="$1"
2265
	local name="$2"
2266
	local metaFile="$3"
2267

    
2268
	# Check if we have a translation to overwrite with
2269
	MTRANS=""
2270
	if [ -z "$LANG" ] ; then return; fi
2271

    
2272
	lCheck="`echo $LANG | cut -d '_' -f 1` `echo $LANG | cut -d '.' -f 1`"
2273
	for l in $lCheck
2274
	do
2275
		catTrans=`grep "^${tag}\[$l\]=${name}" ${metaFile}`	
2276
		if [ -n "$catTrans" ] ; then
2277
			MTRANS=`echo $catTrans | cut -d ";" -f 2`
2278
			return
2279
		fi
2280
	done
2281
}
2282

    
2283
# List repos in the db
2284
pbi_listrepo_init() {
2285
  	require_root_or_group
2286
	parse_listrepo_pbi_cmdline "$@"
2287

    
2288
	# List the repos
2289
	if [ -z "$PBI_LISTREPO_ID" ] ; then
2290
		list_all_pbi_repo
2291
	else
2292
		if [ -n "${PBI_LISTREPO_UP}" ]; then
2293
			require_root
2294
			move_repo_up "${PBI_LISTREPO_ID}" 
2295
			list_all_pbi_repo
2296
		elif [ -n "${PBI_LISTREPO_DOWN}" ] ; then
2297
			require_root
2298
			move_repo_down "${PBI_LISTREPO_ID}"
2299
			list_all_pbi_repo
2300
		elif [ -n "${PBI_LISTREPO_MIRROR}" ] ; then
2301
			require_root
2302
			change_repo_mirror "${PBI_LISTREPO_ID}"
2303
			listrepo_details "${PBI_LISTREPO_ID}"
2304
		else
2305
			listrepo_details "${PBI_LISTREPO_ID}"
2306
		fi
2307
	fi
2308
}
2309

    
2310
# Function to change a specific repos mirror URL
2311
change_repo_mirror() {
2312
	local _rMd5=`ls ${PBI_DBREPODIR}/${1}.* | cut -d '.' -f 2`
2313
	echo "$PBI_LISTREPO_MIRROR" | sed 's|,|\
2314
|g' > "${PBI_DBMIRRORDIR}/${_rMd5}"
2315
}
2316

    
2317
# Move a repo down in priority
2318
move_repo_down() {
2319
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2320
	_uNum=`expr ${1} + 1`
2321

    
2322
	case `echo ${_uNum} | wc -m | tr -d ' '` in
2323
		2) _uNum="00${_uNum}" ;;
2324
		3) _uNum="0${_uNum}" ;;
2325
		*) ;;
2326
	esac
2327
	_uFile=`ls ${PBI_DBREPODIR}/${_uNum}.* 2>/dev/null`
2328
	if [ -z "$_uFile" ] ; then exit_err "This repo is already at the lowest priority!" ; fi
2329

    
2330
	_umd5=`echo $_uFile | cut -d '.' -f 2`
2331
	mv "${_uFile}" "${PBI_DBREPODIR}/${1}.${_umd5}"
2332
	_rmd5=`echo $_rFile | cut -d '.' -f 2`
2333
	mv "${_rFile}" "${PBI_DBREPODIR}/${_uNum}.${_rmd5}"
2334
}
2335

    
2336
# Move a repo up in priority
2337
move_repo_up() {
2338
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2339
	_uNum=`expr ${1} - 1`
2340

    
2341
	case `echo ${_uNum} | wc -m | tr -d ' '` in
2342
		2) _uNum="00${_uNum}" ;;
2343
		3) _uNum="0${_uNum}" ;;
2344
		*) ;;
2345
	esac
2346
	_uFile=`ls ${PBI_DBREPODIR}/${_uNum}.* 2>/dev/null`
2347
	if [ -z "$_uFile" ] ; then exit_err "This repo is already at the highest priority!" ; fi
2348

    
2349
	_umd5=`echo $_uFile | cut -d '.' -f 2`
2350
	mv "${_uFile}" "${PBI_DBREPODIR}/${1}.${_umd5}"
2351
	_rmd5=`echo $_rFile | cut -d '.' -f 2`
2352
	mv "${_rFile}" "${PBI_DBREPODIR}/${_uNum}.${_rmd5}"
2353
}
2354

    
2355
# List all PBI repos
2356
listrepo_details() {
2357
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2358
	_md5=`ls ${PBI_DBREPODIR}/${1}.* | cut -d '.' -f 2`
2359
	_desc=`cat ${_rFile} | grep "Desc: " | sed "s|Desc: ||g"` 
2360
	_url=`cat ${_rFile} | grep "URL: " | sed "s|URL: ||g"` 
2361
	_mirror=`cat ${PBI_DBMIRRORDIR}/$_md5` 
2362
	echo "Repo ID: ${1}"
2363
	echo "Description: ${_desc}"
2364
	echo "IndexURL: ${_url}"
2365
	echo "MD5: ${_md5}"
2366
	echo "LocalMeta: `ls ${PBI_DBINDEXDIR}/${_md5}*meta 2>/dev/null`"
2367
	echo "LocalIndex: `ls ${PBI_DBINDEXDIR}/${_md5}*index 2>/dev/null`"
2368
	echo "Mirror(s):"
2369
	echo "$_mirror"
2370
}
2371

    
2372
# List all PBI repos
2373
list_all_pbi_repo() {
2374
	echo "[ID]	[Description]"
2375
	echo "-----------------------------------------------------"
2376
	for repo in `ls ${PBI_DBREPODIR} | sort `
2377
	do
2378
		_id=`echo $repo | cut -d '.' -f 1`
2379
		_desc=`cat ${PBI_DBREPODIR}/${repo} | grep "Desc: " | sed "s|Desc: ||g"` 
2380
		echo "${_id}	${_desc}"
2381
	done
2382
}
2383

    
2384
# Start the patch process
2385
pbi_patch_init() {
2386
  	require_root_or_group
2387
	init_tmpdir
2388
	parse_patch_pbi_cmdline "$@"
2389

    
2390
	# Check if we are only displaying information
2391
	check_pbi_info_display
2392
	check_pbi_gui_display
2393
	check_pbi_scripts_display
2394
	check_pbi_license_display
2395
	if [ "$PBI_ADD_GUIDISPLAY" = "YES" -o "$PBI_ADD_INFODISPLAY" = "YES" -o "$PBI_CHECKSCRIPTS" = "YES" -o "${PBI_ADD_LICDISPLAY}" = "YES" ] 
2396
	then 
2397
		exit_trap
2398
	fi
2399

    
2400
	# Try to apply this patch file
2401
	do_pbi_patch
2402
}
2403

    
2404
# Start the PBI patch process
2405
do_pbi_patch() {
2406
	
2407
	# Verify the target PBI is installed
2408
	verify_pbi_update_target
2409

    
2410
        pbi_verify_signatures
2411
        pbi_verify_archivesum
2412
        
2413
	# Extract the archive contents
2414
        mk_pbi_extract_dir
2415
        pbi_extract_archive
2416

    
2417
	set_patch_wrkdir
2418

    
2419
	init_tmpdir
2420

    
2421
	# Run the uninstall script
2422
	if [ -e "${PBI_PATCHWRKDIR}/.sbin/.pbi-uninstall.sh" ] ; then
2423
		echo "Removing old xdg data..."
2424
		sh "${PBI_PATCHWRKDIR}/.sbin/.pbi-uninstall.sh"	>/dev/null 2>/dev/null
2425
	fi
2426

    
2427
	# Remove old files from the installed PBI
2428
	patch_rm_old_files
2429
	
2430
	# Extract the new files
2431
	patch_extract_new_files
2432

    
2433
	# Merge in the bsdiffs
2434
	patch_merge_bsdiffs
2435

    
2436
	# Make sure we have good permissions on this PBI
2437
	patch_apply_chmod
2438

    
2439
	# Run the install script
2440
	if [ -e "${PBI_PATCHWRKDIR}/.sbin/.pbi-install.sh" ] ; then
2441
		echo "Adding new xdg data..."
2442
		sh "${PBI_PATCHWRKDIR}/.sbin/.pbi-install.sh"	>/dev/null 2>/dev/null
2443
	fi
2444

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

    
2448
	# Update the registered version of the PBI
2449
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2450
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2451
        newDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHVERSION}-${PBI_APPARCH}"
2452
	mv "$oldDir" "$newDir"
2453
	rm ${newDir}/*.sha1 >/dev/null 2>/dev/null
2454

    
2455
	# Register the app
2456
	pbi_add_register_app	
2457

    
2458
        # Check if we need to run a post-install.sh script again
2459
	if [ -e "${newDir}/${MOD_POSTINS}" ] ; then
2460
          export_script_vars
2461
          sh "${newDir}/${MOD_POSTINS}"
2462
        fi
2463

    
2464
	# Cleanup after our selves
2465
	if [ -d "$PBI_EXTRACTDIR" ] ; then
2466
		echo "Cleaning up..."
2467
		rm -rf "$PBI_EXTRACTDIR"
2468
	fi
2469

    
2470
	# Update the hashdir
2471
	add_hashdir_trigger
2472

    
2473
	# Mark the hash-dir as dirty as well
2474
	make_hashdir_dirty
2475

    
2476
	echo "Finished patching ${_pbilow}: $PBI_PATCHTARGET -> $PBI_PATCHVERSION"
2477
}
2478

    
2479
# Mark the hashdir as dirty
2480
make_hashdir_dirty() {
2481
	date "+%s" > "${PBI_DBDIRTYFILE}"
2482
}
2483

    
2484
# Do any chmod stuff after patching
2485
patch_apply_chmod()
2486
{
2487
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-permList" ] ; then return; fi
2488

    
2489
	cuDir=`pwd`
2490

    
2491
	cd "${PBI_PATCHWRKDIR}"
2492
	echo "Applying updated permissions..."
2493
	while read chLine
2494
	do
2495
		$chLine >/dev/null 2>/dev/null
2496
	done < "${PBI_EXTRACTDIR}/PBI-permList"
2497

    
2498
	cd "$cuDir"
2499
}
2500

    
2501
# Function which does the merge of bsdiff files
2502
patch_merge_bsdiffs()
2503
{
2504
	echo "Applying patch data..."
2505
	find ${PBI_EXTRACTDIR} | grep '.bsdiff' | sed "s|${PBI_EXTRACTDIR}/||g" > ${PBI_TMPDIR}/.PBI.bspatch.$$
2506

    
2507
	while read pLine
2508
	do
2509
		if [ -z "$pLine" ] ; then continue; fi
2510
		_tFile="`echo $pLine | sed 's|.bsdiff$||g'`"
2511
		
2512
		if [ ! -e "${PBI_EXTRACTDIR}/${_tFile}.sha256" ] ; then
2513
			exit_err "Missing checksums for \"${_tFile}\" this patch is corrupt"
2514
		fi
2515

    
2516
		if [ ! -e "${PBI_PATCHWRKDIR}/${_tFile}" ] ; then
2517
			echo "Warning: Missing target file for patching: $_tFile"
2518
			continue
2519
		fi
2520
		
2521
		# Make sure we really are trying to patch the same file
2522
		sha1="`sha256 -q ${PBI_PATCHWRKDIR}/${_tFile}`"
2523
		sha2="`cat ${PBI_EXTRACTDIR}/${_tFile}.sha256`"
2524
		if [ "$sha1" != "$sha2" ] ; then
2525
			echo "Warning: Checksum failed for ${_tFile}, skipping."
2526
			continue
2527
		fi
2528

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

    
2531
		# See if we have a hard-link to take care of first
2532
		get_hard_link_count "${PBI_PATCHWRKDIR}/${_tFile}"
2533
       	 	if [ "$HLINKS" != "1" ] ; then
2534
			mv "${PBI_PATCHWRKDIR}/${_tFile}" "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2535
			cp "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$" "${PBI_PATCHWRKDIR}/${_tFile}"
2536
			rm -f "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2537
        	fi
2538
		
2539
		# Now do the patching
2540
	 	#echo "Patching $_tFile"	
2541
		mv "${PBI_PATCHWRKDIR}/${_tFile}" "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2542
		bspatch "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$" \
2543
			"${PBI_PATCHWRKDIR}/${_tFile}" \
2544
			"${PBI_EXTRACTDIR}/$pLine" >/dev/null 2>/dev/null
2545
		if [ "$?" != "0" ] ; then
2546
			echo "Warning: Failed to apply patch to \"$_tFile\""
2547
		fi
2548

    
2549
		# Re-apply the same permissions to the new file
2550
		chmod $_fPerm "${PBI_PATCHWRKDIR}/${_tFile}"
2551

    
2552
		# Remove the old file
2553
		rm "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2554

    
2555
	done < "${PBI_TMPDIR}/.PBI.bspatch.$$"
2556

    
2557
	rm "${PBI_TMPDIR}/.PBI.bspatch.$$"
2558
}
2559

    
2560
# Function which does the new file extraction for this PBI
2561
patch_extract_new_files()
2562
{
2563
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-newFiles.tar" ] ; then return; fi
2564
	echo "Installing new files..."
2565
	tar xvf "${PBI_EXTRACTDIR}/PBI-newFiles.tar" -C "${PBI_PATCHWRKDIR}" >/dev/null 2>/dev/null 
2566
	if [ "$?" != "0" ] ; then
2567
		echo "Warning: Error during new file extraction, PBI may not function correctly."
2568
	fi
2569
}
2570

    
2571
# Function which removes files that no longer exist in this updated PBI
2572
patch_rm_old_files()
2573
{
2574
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-rmList" ] ; then return; fi
2575
	
2576
	echo "Removing old files..."
2577
	while read rmLine
2578
	do
2579
		if [ -z "$rmLine" ] ; then continue ; fi
2580
		if [ ! -e "${PBI_PATCHWRKDIR}/$rmLine" ] ; then
2581
			continue
2582
		fi
2583

    
2584
		rm -rf "${PBI_PATCHWRKDIR}/${rmLine}"
2585
	done < "${PBI_EXTRACTDIR}/PBI-rmList"
2586

    
2587
}
2588

    
2589
# Sets the workdir of the target PBI we are patching
2590
set_patch_wrkdir()
2591
{
2592
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2593
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2594

    
2595
	if [ ! -e "${oldDir}/pbi_defaultpath" ] ; then
2596
        	exit_err "Can not fild default path for \"$PBI_PROGNAME\"!"
2597
        fi
2598

    
2599
	PBI_PATCHWRKDIR="`cat ${oldDir}/pbi_defaultpath`"
2600

    
2601
	if [ ! -d "$PBI_PATCHWRKDIR" ] ; then
2602
        	exit_err "Path for \"$PBI_PROGNAME\" does not exist!"
2603
	fi
2604
}
2605

    
2606
# Confirms that the target PBI for this patch is installed
2607
# Exits if not and we are not doing a extract only
2608
verify_pbi_update_target()
2609
{
2610
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then return ; fi
2611
	
2612
	# Make sure the target PBI is installed
2613
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2614
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2615

    
2616
	if [ ! -e "${oldDir}" ] ; then
2617
        	exit_err "\"${_pbilow}\" does not appear to be installed!"
2618
        fi
2619

    
2620
	# Check the arch type
2621
	if [ "`cat ${oldDir}/pbi_arch`" != "$PBI_APPARCH" ] ; then
2622
     		exit_err "Installed \"${PBI_PROGNAME}\" is not compiled for $PBI_APPARCH"
2623
	fi
2624

    
2625
	# Check the taret version
2626
	if [ "`cat ${oldDir}/pbi_version`" != "$PBI_PATCHTARGET" ] ; then
2627
     		exit_err "\"${_pbilow}\" patch is for \"$PBI_PROGVERSION\" only!"
2628
	fi
2629

    
2630
	# Check the fbsd version
2631
	_pFbsdVer="`cat ${oldDir}/pbi_fbsdver | cut -c 1`"
2632
	_sFbsdVer="`echo $PBI_FBSDVER | cut -c 1`"
2633
	if [ "$_pFbsdVer" != "$_sFbsdVer" ] ; then
2634
     		exit_err "\"${_pbilow}\" patch is for FreeBSD ${_sFbsdVer}.X only!"
2635
	fi
2636

    
2637
	# Check the mdate of the pbi
2638
	_pMDate="`cat ${oldDir}/pbi_mdate`"
2639
	_sMDate="$PBI_PATCHMDATE"
2640
	if [ "$_pMDate" != "$_sMDate" ] ; then
2641
     		exit_err "\"${_pbilow}\" patch is for the $PBI_PATCHMDATE build!"
2642
	fi
2643
}
2644

    
2645
# Start the pbi_add process
2646
pbi_add_init() {
2647
	init_tmpdir
2648
	parse_add_pbi_cmdline "$@"
2649

    
2650

    
2651
	# Check if we are only displaying information
2652
	check_pbi_info_display
2653
	check_pbi_gui_display
2654
	check_pbi_scripts_display
2655
	check_pbi_license_display
2656
	if [ "$PBI_ADD_GUIDISPLAY" = "YES" -o "$PBI_ADD_INFODISPLAY" = "YES" -o "$PBI_CHECKSCRIPTS" = "YES" -o "${PBI_ADD_LICDISPLAY}" = "YES" ] 
2657
	then 
2658
		clean_remote_dl
2659
		exit_trap
2660
	fi
2661

    
2662
  	require_root_or_group
2663

    
2664
	# If this app can only be installed as root
2665
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then require_root ; fi
2666

    
2667
	check_agree_lic
2668
	check_existing_pbi
2669
	do_pbi_add
2670
}
2671

    
2672
# Check if this PBI exists and exit if so
2673
check_existing_pbi() {
2674
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then return 0; fi
2675
	get_dbdir
2676
	dir="${APPDBDIR}"
2677

    
2678
	# See if this PBI is already installed
2679
	if [ -d "$dir" ]; then
2680
		get_username_from_file "${APPDBDIR}/pbi_name"
2681
		if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
2682
			exit_err "Permission denied to modify PBI installed by: $FILEUSER"     
2683
		fi
2684

    
2685
		if [ "${PBI_FORCEADD}" = "YES" ] ; then return 0; fi
2686
		exit_err "${PBI_PROGNAME} ${PBI_PROGVERSION} is already installed! Use -f to force installation."
2687
	fi
2688

    
2689
	if [ -e "${PBI_PROGDIRPATH}" ]; then
2690
		get_username_from_file "${PBI_PROGDIRPATH}"
2691
		if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
2692
			exit_err "Permission denied to modify PBI installed by: $FILEUSER"     
2693
		fi
2694
		if [ "${PBI_FORCEADD}" = "YES" ] ; then return 0; fi
2695
		exit_err "${PBI_PROGDIRPATH} already exists! Use -f to force installation."
2696
	fi
2697

    
2698

    
2699
}
2700

    
2701
# Check if we have a license to agree to, and if we've provided the flag to do so
2702
check_agree_lic() {
2703
        open_header_tmp
2704
        if [ -f "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}" -a "${PBI_LICAGREE}" = "NO" ] ; then
2705
        	delete_header_tmp
2706
		exit_err "LICENSE must be agreed to (--licagree) before this PBI can be installed."
2707
        fi
2708
        delete_header_tmp
2709
}
2710

    
2711
# See if we need to display pbi license
2712
check_pbi_license_display() {
2713
	if [ "$PBI_ADD_LICDISPLAY" != "YES" ] ; then return 0 ; fi
2714
	open_header_tmp
2715
	
2716
	if [ -f "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}" ] ; then 
2717
		echo "LICENSE:"
2718
		cat "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}"	
2719
	else
2720
		echo "`basename $0`: No LICENSE included with this PBI"
2721
	fi
2722
	delete_header_tmp
2723
}
2724

    
2725
# See if we need to display pbi info
2726
check_pbi_info_display() {
2727
	if [ "$PBI_ADD_INFODISPLAY" != "YES" ] ; then return 0 ; fi
2728
	pbi_display_info
2729
}
2730

    
2731
# Display pbi information to stdout
2732
pbi_display_info() {
2733

    
2734
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
2735
        _appname="${tmp}-${PBI_PROGVERSION}-${PBI_APPARCH}"
2736

    
2737
	if [ -z "$PBI_PATCHVERSION" ] ; then
2738
		echo "PBI Information for: $_appname"
2739
	else
2740
		echo "PBP Information for: $_appname"
2741
	fi
2742
	echo "-----------------------------------------------------"
2743
	echo "Name: ${PBI_PROGNAME}"
2744

    
2745
	if [ -n "$PBI_PATCHVERSION" ] ; then
2746
		echo "PatchTarget: $PBI_PATCHTARGET"
2747
	fi
2748

    
2749
	if [ -n "$PBI_INSTALLED_BY" ] ; then
2750
		echo "InstalledBy: $PBI_INSTALLED_BY"
2751
	fi
2752

    
2753
	# Does this PBI need root to install?
2754
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then
2755
		echo "RootInstall: YES"
2756
	else
2757
		echo "RootInstall: NO"
2758
	fi
2759

    
2760
	echo "Version: ${PBI_PROGVERSION}"
2761
	echo "Built: ${PBI_PROGMDATE}"
2762
	echo "Prefix: ${PBI_ORIGPROGDIRPATH}"
2763
	echo "Author: ${PBI_PROGAUTHOR}"
2764
	echo "Website: ${PBI_PROGWEB}"
2765
	echo "Arch: ${PBI_APPARCH}"
2766
	echo "FbsdVer: ${PBI_FBSDVER}"
2767
	echo "CreatorVer: ${PBI_APPCREATEVER}"
2768
	echo "ArchiveCount: ${PBI_ARCHIVE_COUNT}"
2769
	echo "ArchiveSum: ${PBI_ARCHIVE_CHECKSUM}"
2770
	case ${PBI_SIGVALID} in
2771
		0) echo "Signature: Verified" ;;
2772
  	       -1) echo "Signature: Not Signed" ;;
2773
  	        1) echo "Signature: Bad" ;;
2774
		*) echo "Signature: <Unknown>" ;;
2775
	esac
2776

    
2777
	if [ -n "${PBI_REPO}" ] ; then
2778
		local _rDesc="`cat ${PBI_DBREPODIR}/*.${PBI_REPO} | grep "Desc:" | sed 's|Desc: ||g'`"
2779
		local _rID="`ls ${PBI_DBREPODIR}/*.${PBI_REPO}`"
2780
		_rID=`basename $_rID | cut -d '.' -f 1`
2781
		echo "Associated Repo: ${_rID} (${_rDesc})"
2782
	fi
2783
	
2784
	# Check if autoupdate is enable or not
2785
	if [ "${PBI_ENABLEAUTOUPDATE}" = "YES" ] ; then
2786
		echo "AutoUpdate: YES"
2787
	else
2788
		echo "AutoUpdate: NO"
2789
	fi
2790

    
2791
	# See if we have any XDG stuff
2792
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-desktop/install-desktop-icons.sh" ] ; then
2793
		echo "DesktopIcons: YES"
2794
	fi
2795
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-menu/install-menu-icons.sh" ] ; then
2796
		echo "MenuIcons: YES"
2797
	fi
2798
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-mime/install-mime.sh" ] ; then
2799
		echo "MimeRegistration: YES"
2800
	fi
2801

    
2802
	# If verbose mode, show file contents
2803
	if [ "$PBI_VERBOSE" = "YES" ] ; then
2804
		if [ -n "${PBI_FILENAME}" -a -e "${PBI_FILENAME}" ] ; then
2805
	  		pbi_find_archive_header
2806
                	echo "TOTALFILES: ${PBI_ARCHIVE_COUNT}"
2807
                	echo "Archive Contents:"
2808
                	echo "--------------------------------------"
2809
                	tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar tvf - 
2810
		fi
2811
        fi
2812
}
2813

    
2814
# See if we need to display gui header info
2815
check_pbi_gui_display() {
2816
	if [ "$PBI_ADD_GUIDISPLAY" != "YES" ] ; then return 0 ; fi
2817
	open_header_tmp
2818
	
2819
	pbi_display_gui "$PBI_HEADER_TMPDIR" "COPY"
2820

    
2821
	delete_header_tmp
2822

    
2823
}
2824

    
2825
# Display location of PBI graphics
2826
pbi_display_gui() {
2827
	dir="$1"
2828
	copy="$2"
2829
	if [ -e "${dir}/top-banner.png" ] ; then 
2830
		if [ "$copy" = "COPY" ] ; then
2831
			pbi_guitop="/tmp/.PBI-top.$$.png"
2832
			cp "${dir}/top-banner.png" "$pbi_guitop"
2833
		else
2834
			pbi_guitop="${dir}/top-banner.png"
2835
		fi
2836
		echo "TopBanner: ${pbi_guitop}"
2837
	fi
2838
	if [ -e "${dir}/side-banner.png" ] ; then 
2839
		if [ "$copy" = "COPY" ] ; then
2840
			pbi_guiside="/tmp/.PBI-side.$$.png"
2841
			cp "${dir}/side-banner.png" "$pbi_guiside"
2842
		else
2843
			pbi_guiside="${dir}/side-banner.png"
2844
		fi
2845
		echo "SideBanner: ${pbi_guiside}"
2846
	fi
2847

    
2848
	# Try to find an icon
2849
	ls ${dir}/pbi_icon.* >/dev/null 2>/dev/null
2850
	if [ "$?" = "0" ] ; then
2851
		_iconExt=`ls ${dir}/pbi_icon.* | head -n 1 | awk -F . '{print $NF}'`
2852
		if [ "$copy" = "COPY" ] ; then
2853
			pbi_guiicon="/tmp/.PBI-icon.$$.${_iconExt}"
2854
			cp "${dir}/pbi_icon.${_iconExt}" "$pbi_guiicon"
2855
		else
2856
			pbi_guiicon="${dir}/pbi_icon.${_iconExt}"
2857
		fi
2858
		echo "Icon: ${pbi_guiicon}"
2859
	fi
2860

    
2861
}
2862

    
2863
open_header_tmp() {
2864
	init_tmpdir
2865

    
2866
	# If we have a custom extract dir, use it
2867
	if [ -z "$1" ] ; then
2868
		PBI_HEADER_TMPDIR="${PBI_TMPDIR}/.PBI-header.$$"
2869
	else
2870
		PBI_HEADER_TMPDIR="${1}/.PBI-header.$$"
2871
	fi
2872

    
2873
	if [ -e "${PBI_HEADER_TMPDIR}" ] ; then rm -rf "${PBI_HEADER_TMPDIR}" ; fi
2874
	mkdir -p "${PBI_HEADER_TMPDIR}"
2875
	
2876
	# Extract the header files 
2877
	tar xvf "${PBI_FILENAME}" -C "${PBI_HEADER_TMPDIR}" >/dev/null 2>/dev/null
2878
	if [ "$?" != "0" ] ; then exit_err "Failed to read PBI header! Possible corrupt PBI, or wrong PBI version for this OS." ; fi
2879

    
2880
}
2881

    
2882
delete_header_tmp() {
2883
	if [ -z "${PBI_HEADER_TMPDIR}" ] ; then return 0 ; fi
2884
	if [ -d "${PBI_HEADER_TMPDIR}" ] ; then rm -rf "${PBI_HEADER_TMPDIR}" ; fi
2885
}
2886

    
2887
# Load in all the configuration data from the header
2888
load_info_from_header() {
2889
	open_header_tmp
2890

    
2891
	# Start loading our variables
2892
	load_info_from_dir "${PBI_HEADER_TMPDIR}"
2893

    
2894
	delete_header_tmp
2895
}
2896

    
2897
# See if we need to display scripts
2898
check_pbi_scripts_display() {
2899
	if [ "$PBI_CHECKSCRIPTS" != "YES" ] ; then return 0 ; fi
2900

    
2901
	# Display our scripts
2902
	open_header_tmp
2903
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_PREINS}" ] ; then
2904
		echo -e "\n${MOD_PREINS}:"
2905
		echo "--------------------------------"
2906
		cat "${PBI_HEADER_TMPDIR}/${MOD_PREINS}"
2907
	fi
2908
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}" ] ; then
2909
		echo -e "\n${MOD_POSTINS}:"
2910
		echo "--------------------------------"
2911
		cat "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}"
2912
	fi
2913
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_PREREM}" ] ; then
2914
		echo -e "\n${MOD_PREREM}:"
2915
		echo "--------------------------------"
2916
		cat "${PBI_HEADER_TMPDIR}/${MOD_PREREM}"
2917
	fi
2918
	delete_header_tmp
2919
}
2920

    
2921
# Load pbi information from the specified directory
2922
load_info_from_dir() {
2923
	REQUIRED_FILES="pbi_defaultpath pbi_name pbi_version pbi_author pbi_web pbi_arch pbi_fbsdver pbi_createver"
2924
	for f in $REQUIRED_FILES
2925
	do
2926
		if [ ! -e "${1}/${f}" ] ; then echo "Warning: Missing file: ${f}" ; fi
2927
	done
2928
        PBI_APPARCH=""
2929
        PBI_APPCREATEVER=""
2930
        PBI_ARCHIVE_CHECKSUM=""
2931
        PBI_ARCHIVE_COUNT=""
2932
	PBI_ENABLEAUTOUPDATE=""
2933
        PBI_FBSDVER=""
2934
	PBI_ORIGPROGDIRPATH=""
2935
	PBI_PATCHMDATE=""
2936
	PBI_PATCHVERSION=""
2937
	PBI_PATCHTARGET=""
2938
	PBI_PROGNAME=""
2939
        PBI_PROGVERSION=""
2940
        PBI_PROGAUTHOR=""
2941
        PBI_PROGMDATE=""
2942
        PBI_PROGWEB=""
2943
	PBI_REPO=""
2944
	PBI_REQUIRESROOT=""
2945
	PBI_SIGVALID=""
2946

    
2947
	PBI_ORIGPROGDIRPATH="`cat ${1}/pbi_defaultpath`"
2948
        PBI_PROGNAME="`cat ${1}/pbi_name`"
2949
        PBI_PROGVERSION="`cat ${1}/pbi_version`"
2950
        PBI_PROGAUTHOR="`cat ${1}/pbi_author`"
2951
        PBI_PROGWEB="`cat ${1}/pbi_web 2>/dev/null`"
2952
        PBI_PROGMDATE="`cat ${1}/pbi_mdate 2>/dev/null`"
2953
        PBI_APPARCH="`cat ${1}/pbi_arch 2>/dev/null`"
2954
        PBI_FBSDVER="`cat ${1}/pbi_fbsdver 2>/dev/null`"
2955
        PBI_APPCREATEVER="`cat ${1}/pbi_createver 2>/dev/null`"
2956
        PBI_ARCHIVE_COUNT="`cat ${1}/pbi_archivecount 2>/dev/null`"
2957
        PBI_ARCHIVE_CHECKSUM="`cat ${1}/pbi_archivesum 2>/dev/null`"
2958

    
2959
	# Check if auto-update is enabled
2960
	if [ -e "${1}/autoupdate-enable" ] ; then
2961
		PBI_ENABLEAUTOUPDATE="YES"
2962
	fi
2963

    
2964
	# Does this PBI need to be installed as root
2965
	if [ -e "${1}/pbi_requiresroot" ] ; then
2966
		PBI_REQUIRESROOT="YES"
2967
	fi
2968
	
2969
	# Check if this is a patch file
2970
	if [ -e "${1}/pbi_patchfile" ] ; then
2971
        	PBI_PATCHVERSION=`cat ${1}/pbi_patchfile | cut -d ':' -f 2`
2972
		PBI_PATCHTARGET=`cat ${1}/pbi_patchfile | cut -d ':' -f 1`
2973
	fi
2974
	
2975
	# Check if this associates with a particular repo
2976
	if [ -e "${1}/pbi_repo" ] ; then
2977
        	PBI_REPO=`cat ${1}/pbi_repo`
2978
	fi
2979

    
2980
	# See if this patch is for a particular mdate
2981
	if [ -e "${1}/pbi_patchmdate" ] ; then
2982
        	PBI_PATCHMDATE=`cat ${1}/pbi_patchmdate`
2983
	fi
2984

    
2985
	# See if this PBI was signed
2986
	if [ -e "${1}/pbi_archivesum.sha1" ] ; then
2987
		check_valid_sigs "${1}"
2988
		if [ "$?" = "0" ] ; then
2989
			PBI_SIGVALID="0"
2990
		else
2991
			PBI_SIGVALID="1"
2992
		fi
2993
	else
2994
		PBI_SIGVALID="-1"
2995
	fi
2996
}
2997

    
2998
# Start installing the PBI
2999
do_pbi_add() {
3000
	pbi_verify_signatures
3001
	pbi_verify_archivesum
3002

    
3003
	check_preinstall_script
3004

    
3005
	mk_pbi_extract_dir
3006
	pbi_extract_archive
3007
	
3008
	pbi_add_check_gids
3009
	pbi_add_check_uids
3010

    
3011
	pbi_add_run_script
3012
	check_postinstall_script
3013

    
3014
	pbi_add_register_app
3015

    
3016
	# Be sure to let the pbid know we have a new hash-dir to register
3017
	add_hashdir_trigger
3018

    
3019
	clean_remote_dl
3020
}
3021

    
3022
# Check for any GIDs we need to create
3023
pbi_add_check_gids() {
3024
	if [ ! -e "${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}" ] ; then return ; fi
3025
	runUID=`id -u`
3026

    
3027
	while read gidLine
3028
	do
3029
		gName=`echo $gidLine | cut -d ':' -f 1`
3030
		gID=`echo $gidLine | cut -d ':' -f 3`
3031
		gUsers=`echo $gidLine | cut -d ':' -f 4`
3032

    
3033
		# Is this group already on the system?
3034
		pw groupshow $gName >/dev/null 2>/dev/null
3035
		if [ $? -eq 0 ] ; then 
3036
			echo "Using existing group: $gName"
3037
		else
3038
			# Are we installing as root?
3039
			if [ "$runUID" != "0" ] ; then
3040
				echo "Please create group \"$gName\" manually or re-install PBI as root."
3041
			else
3042
				echo "Adding group: $gName"
3043
				pw groupadd $gName -g $gID;
3044
			fi
3045
		fi
3046

    
3047
		if [ -n "$gUsers" ] ; then
3048
			for gUser in `echo $gUsers | sed 's|,| |g'`
3049
			do
3050
				pw groupshow ${gName} | grep -qw ${gUser}
3051
				if [ $? -ne 0 ] ; then
3052
					# Are we installing as root?
3053
					if [ "$runUID" != "0" ] ; then
3054
						echo "Please add user \"$gUser\" to group \"$gName\" manually or re-install PBI as root."
3055
						continue
3056
					fi
3057

    
3058
					echo "Adding user ${gUser} to group ${gName}"
3059
					pw groupmod ${gName} -m ${gUser}
3060
				fi
3061
			done
3062
		fi
3063
	done < ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}
3064
}
3065

    
3066
# Check for any UIDs we need to create
3067
pbi_add_check_uids() {
3068
	if [ ! -e "${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}" ] ; then return ; fi
3069
	runUID=`id -u`
3070

    
3071
	while read uidLine
3072
	do
3073
		uName=`echo $uidLine | cut -d ':' -f 1`
3074

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

    
3079
		# Are we installing as root?
3080
		if [ "$runUID" != "0" ] ; then
3081
			echo "Please create user \"$uName\" manually or re-install PBI as root."
3082
			continue
3083
		fi
3084

    
3085
		uID=`echo $uidLine | cut -d ':' -f 3`
3086
		gID=`echo $uidLine | cut -d ':' -f 4`
3087
		uClass=`echo $uidLine | cut -d ':' -f 5`
3088
		uGecos=`echo $uidLine | cut -d ':' -f 8`
3089
		uHomedir=`echo $uidLine | cut -d ':' -f 9 | sed "s|^/usr/local|${PBI_PROGDIRPATH}|"`
3090
		uShell=`echo $uidLine | cut -d ':' -f 10`
3091

    
3092
		echo "Adding user: $uName"
3093
		pw useradd $uName -u $uID -g $gID $uClass -c "$uGecos" -d $uHomedir -s $uShell;
3094

    
3095
		# Create homedir
3096
		case $uHomedir in 
3097
			/nonexistent|/var/empty) ;; 
3098
			*) install -d -g $gID -o $uID $uHomedir ;;
3099
		esac 
3100
	done < ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}
3101
}
3102

    
3103
add_hashdir_trigger() {
3104
	get_dbdir
3105
        _htrig=`echo ${APPDBDIR} | sed "s|${PBI_DBAPPDIR}|${PBI_DBHASHQUEUEDIR}|g"`
3106
	if [ ! -e "${_htrig}" ] ; then
3107
		touch "${_htrig}"
3108
	fi
3109
}
3110

    
3111
# Run the install script if exists
3112
pbi_add_run_script() {
3113

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

    
3117
	insc="${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/.pbi-install.sh"
3118
	if [ ! -e "${insc}" ] ; then return 0 ; fi
3119
	export_script_vars
3120
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3121
		${insc}
3122
	else
3123
		${insc} >/dev/null 2>/dev/null
3124
	fi
3125

    
3126
}
3127

    
3128
# If we need to, update the hashdir
3129
pbi_add_update_hashdir() {
3130
	if [ "${PBI_NOHASHDIR}" = "YES" ] ; then return 0 ; fi
3131
	if [ ! -e "${1}/${PBI_HASHLIST}" ] ; then return 0; fi
3132

    
3133
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3134
		echo "HASHCOUNT: `wc -l ${1}/${PBI_HASHLIST} | tr -d ' ' | cut -d '/' -f 1`"
3135
	else
3136
	
3137
		echo -e "Merging with hashdir...\c"
3138
	fi
3139
	
3140
	# Read the hashfile, and start making links to identical files
3141
	while read hl
3142
	do
3143
		file="`echo $hl | sed 's/:::.*$//g'`"
3144

    
3145
		# If we are trying to merge a PBI which was deleted, stop
3146
		if [ -n "${2}" -a -e "${2}" ] ; then
3147
			echo "HASHDONE - Deleted" 
3148
			return
3149
		fi
3150

    
3151
		# Make sure the target file hasnt been removed
3152
		if [ ! -e "${1}/${file}" ] ; then continue ; fi
3153

    
3154
		# We dont need no stinking sym-links
3155
		if [ -h "${1}/${file}" ] ; then continue ; fi
3156

    
3157
		if [ -f "${PBI_HASHDIR}/${hl}" ] ; then
3158
			use_hashfile "$hl" "${1}/$file"
3159
		else
3160
			mv_ln_hashfile "$hl" "${1}/$file"
3161
		fi
3162
	done < "${1}/${PBI_HASHLIST}"
3163

    
3164
	if [ "$PBI_VERBOSE" = "YES" ] ; then 
3165
		echo "HASHDONE"
3166
	else 
3167
		echo -e "Done!" 
3168
	fi
3169
}
3170

    
3171
# Use an existing hashfile
3172
use_hashfile() {
3173
	tfile="$1"
3174
	file="$2"
3175
	dir="`dirname ${tfile}`"
3176
	if [ ! -d "${PBI_HASHDIR}/${dir}" ] ; then
3177
		mkdir -p ${PBI_HASHDIR}/${dir}
3178
	fi
3179

    
3180
	# We have a match!
3181
	ln -f "${PBI_HASHDIR}/${tfile}" "${file}"
3182
	if [ $? -ne 0 ] ; then 
3183
		echo "Warning: Unable to make hash-link ${PBI_HASHDIR}/${tfile} -> ${file}"
3184
		return
3185
	fi
3186
	
3187
	# Make sure the hard-linked file doesn't get changed
3188
	chmod u-w,g-w,o-w "${file}"
3189
	if [ $? -ne 0 ] ; then 
3190
		echo "Warning: Unable to chmod ${file}"
3191
		return
3192
	fi
3193
	
3194
}
3195

    
3196
# New file we can save to hashdir
3197
mv_ln_hashfile() {
3198
	tfile="$1"
3199
	file="$2"
3200
	dir="`dirname ${tfile}`"
3201
	if [ ! -d "${PBI_HASHDIR}/${dir}" ] ; then
3202
		mkdir -p ${PBI_HASHDIR}/${dir}
3203
	fi
3204

    
3205
	ln -f "${file}" "${PBI_HASHDIR}/${tfile}"
3206
	if [ $? -ne 0 ] ; then 
3207
		echo "Warning: Unable to make hash-link ${file} -> ${PBI_HASHDIR}/${tfile}"
3208
		return
3209
	fi
3210

    
3211
	# Make sure the hard-linked file doesn't get changed
3212
	chmod u-w,g-w,o-w "${file}"
3213
	if [ $? -ne 0 ] ; then 
3214
		echo "Warning: Unable to chmod ${file}"
3215
		return
3216
	fi
3217

    
3218
	# Make sure the hard-linked file doesn't get changed
3219
	chmod u-w,g-w,o-w "${PBI_HASHDIR}/${tfile}"
3220
	if [ $? -ne 0 ] ; then 
3221
		echo "Warning: Unable to chmod ${PBI_HASHDIR}/${tfile}"
3222
		return
3223
	fi
3224

    
3225
	if [ "$PBI_VERBOSE" = "YES" ] ; then echo "L" ; fi
3226
}
3227

    
3228
# Return the dbdir for this PBI
3229
get_dbdir() {
3230
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
3231
        APPDBDIR="${PBI_DBAPPDIR}/${tmp}-${PBI_PROGVERSION}-${PBI_APPARCH}"
3232
}
3233

    
3234
# Register this app as installed
3235
pbi_add_register_app() {
3236
	if [ ! -d "$PBI_DBAPPDIR" ] ; then mkdir -p ${PBI_DBAPPDIR} ; fi
3237
        open_header_tmp
3238
	get_dbdir
3239
	dir="${APPDBDIR}"
3240

    
3241
	# Make sure we remove any existing meta-data if forcing an installation
3242
	if [ "$PBI_FORCEADD" = "YES" ] ; then
3243
	  	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
3244
          	rm -rf ${PBI_DBAPPDIR}/${tmp}-*-${PBI_APPARCH}
3245
	fi
3246

    
3247
	mkdir -p "${dir}"
3248
	
3249
        tar cvf - -C "${PBI_HEADER_TMPDIR}" . 2>/dev/null | tar xvf - -C "$dir" 2>/dev/null
3250

    
3251
	# If this was a patch, use the original path
3252
	if [ -n "${PBI_ORIGPROGDIRPATH}" ] ; then
3253
		echo "${PBI_ORIGPROGDIRPATH}" >${dir}/pbi_installedpath
3254
	else
3255
		echo "${PBI_PROGDIRPATH}" >${dir}/pbi_installedpath
3256
	fi
3257

    
3258
	# See which repo / key this PBI associates to, if any
3259
	check_valid_sigs "${dir}"
3260
	if [ -n "$PBI_VALIDKEYSIG" ] ; then
3261
		_rMd5="`echo ${PBI_VALIDKEYSIG} | cut -d '.' -f 1`"
3262
		echo "$_rMd5" | sed "s|${PBI_DBKEYDIR}/||g" > ${dir}/pbi_repo
3263
	fi
3264

    
3265
	# Dont need any patch version info
3266
	if [ -e "${dir}/pbi_patchfile" ] ; then
3267
		rm "${dir}/pbi_patchfile"
3268
	fi
3269

    
3270
        delete_header_tmp
3271

    
3272
	echo "Installed: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3273
}
3274

    
3275
# Check if we have a postinstall script we need to use
3276
check_postinstall_script() {
3277
        open_header_tmp
3278

    
3279
        if [ ! -e "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}" ] ; then
3280
                delete_header_tmp
3281
                return 0
3282
        fi
3283

    
3284
        export_script_vars
3285
        sh "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}"
3286
        delete_header_tmp
3287
}
3288

    
3289
# Check if we have a preinstall script we need to use
3290
check_preinstall_script() {
3291
	open_header_tmp
3292

    
3293
	if [ ! -e "${PBI_HEADER_TMPDIR}/${MOD_PREINS}" ] ; then 
3294
		delete_header_tmp
3295
		return 0 
3296
	fi
3297

    
3298
	export_script_vars
3299
	sh "${PBI_HEADER_TMPDIR}/${MOD_PREINS}"
3300
	if [ "$?" != "0" ] ; then
3301
        	delete_header_tmp
3302
		exit_err "${MOD_PREINS} returned error status"
3303
	fi
3304
        delete_header_tmp
3305
}
3306

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

    
3314
}
3315

    
3316
# Check if we have valid signatures, and return "0" if success, "1" if failure
3317
check_valid_sigs() {
3318
	PBI_VALIDKEYSIG=""
3319

    
3320
	for _pk in ${PBI_PUBKEYS}
3321
	do
3322
		good="true"
3323
		_sf="${1}/pbi_archivesum ${1}/${MOD_PREINS} ${1}/${MOD_POSTINS} ${1}/${MOD_PREREM}"
3324
       		for _ts in $_sf
3325
        	do
3326
                	openssl dgst -sha1 \
3327
                        -verify ${_pk} \
3328
                        -signature ${_ts}.sha1 \
3329
                        ${_ts} >/dev/null 2>/dev/null
3330
			if [ "$?" != "0" ] ; then
3331
				good="false" ; break
3332
			fi
3333
			PBI_VALIDKEYSIG="$_pk"
3334
		done
3335
		if [ "$good" = "true" ] ; then return 0 ; fi
3336
        done
3337
	return 1	
3338
}
3339

    
3340
# Verify if the archive checksum is good
3341
pbi_verify_archivesum() {
3342
	if [ "${PBI_SKIPCHECKSUM}" = "YES" ] ; then return 0 ; fi
3343
	echo -e "Verifying Checksum...\c"
3344

    
3345
        pbi_find_archive_header
3346
	sum=`tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | sha256 -q`
3347
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3348
		echo "Archive checksum: ${sum}"
3349
		echo "Saved checksum: ${PBI_ARCHIVE_CHECKSUM}"
3350
	fi
3351
	if [ "$sum" != "$PBI_ARCHIVE_CHECKSUM" ] ; then
3352
		exit_err "${PBI_FILENAME} failed checksum, the archive may be corrupt."
3353
	fi
3354
	echo -e "OK"
3355

    
3356
}
3357

    
3358
# Make our PBI extraction dir
3359
mk_pbi_extract_dir() {
3360
	PBI_EXTRACTDIR="${PBI_PROGDIRPATH}"
3361
	if [ -e "${PBI_EXTRACTDIR}" ] ; then
3362
               rm -rf "$PBI_EXTRACTDIR"
3363
	fi
3364
	mkdir -p "${PBI_EXTRACTDIR}" >/dev/null 2>/dev/null
3365
	if [ "$?" != "0" ] ; then 
3366
		exit_err "Failed to create directory: ${PBI_PROGDIRPATH}"
3367
	fi
3368
}
3369

    
3370
pbi_find_archive_header() {
3371
	# Find the header for the archive
3372
	# SEARCH FOR: $PBI_SS_ARCHIVE
3373
	PBI_SKIP_ARCHLINES=`awk "/^${PBI_SS_ARCHIVE}/ { print NR + 1; exit 0; }" "${PBI_FILENAME}"`
3374
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3375
		echo "SKIP_ARCHLINES: $PBI_SKIP_ARCHLINES"
3376
	fi
3377
}
3378

    
3379
# Extract the PBI archive file
3380
pbi_extract_archive() {
3381
	pbi_find_archive_header	
3382

    
3383
	echo "Extracting to: ${PBI_EXTRACTDIR}"
3384
	tar="xvf -"
3385

    
3386
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3387
		echo "TOTALFILES: ${PBI_ARCHIVE_COUNT}"
3388
		tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar ${tar} -C "${PBI_EXTRACTDIR}"
3389
		err="$?"
3390
	else
3391
		tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar ${tar} -C "${PBI_EXTRACTDIR}" >/dev/null 2>/dev/null
3392
		err="$?"
3393
	fi
3394
	
3395
	if [ "$err" != "0" ] ; then exit_err "Failed extracting ${PBI_FILENAME}" ; fi
3396

    
3397
	if [ "$PBI_VERBOSE" = "YES" ] ; then echo "Extraction Finished!" ; fi
3398

    
3399
	# If this is an extract only, do it and exit
3400
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then exit_trap ; fi
3401
}
3402
	
3403

    
3404
# Starting pbi_create
3405
pbi_create_init() {
3406

    
3407
	require_root
3408

    
3409
	parse_create_pbi_cmdline "$@"
3410

    
3411
	# If we are making a backup copy of an installed PBI
3412
	if [ "$PBI_CBACKUP" = "YES" ] ; then
3413
		init_tmpdir
3414
		do_pbi_create_backup
3415
		exit_trap
3416
	fi
3417

    
3418
	load_pbi_conffile
3419

    
3420
	parse_cmdline_overrides
3421

    
3422
	# Copy over the application to the correct location
3423
        echo ${PBI_PROGDIRPATH} | grep -q "^${PBI_APPDIR}/"
3424
	if [ $? -ne 0 ] ; then
3425
	   _pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
3426
	   newPDP="${PBI_APPDIR}/${_pbilow}-${ARCH}"
3427
	   if [ -d "${newPDP}" ] ; then exit_err "Error: ${newPDP} already exists!" ; fi	
3428
	   cp -r ${PBI_PROGDIRPATH} ${newPDP}
3429
	   PBI_PROGDIRPATH="${newPDP}"
3430
	   export PBI_PROGDIRPATH
3431
	fi
3432

    
3433
	PBI_CREATEONLY="YES"
3434

    
3435
	check_create_required_vars
3436

    
3437
	do_pbi_create
3438

    
3439
	# Cleanup the copy dir
3440
 	if [ -n "$newPDP" ] ; then
3441
		if [ "${newPDP}" != "/" -a "${newPDP}" != "${PBI_APPDIR}/-" ] ; then
3442
			rm -rf "${newPDP}"
3443
		fi
3444
	fi
3445
}
3446

    
3447
# Start the pbi_create backup process
3448
do_pbi_create_backup() {
3449

    
3450
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_CBACKUPTARGET}"
3451
	echo "Creating backup PBI: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3452

    
3453
	# Start by making a fresh archive of the installed PBI
3454
	PBI_STAGEDIR="$PBI_ORIGPROGDIRPATH"
3455
	mk_archive_file
3456

    
3457
	# Now make the header dir
3458
	_hDir="${PBI_TMPDIR}/.header.$$"
3459
	PBI_HEADERDIR="${_hDir}"
3460
	mkdir -p "${_hDir}"
3461
	cp ${PBI_DBAPPDIR}/${PBI_CBACKUPTARGET}/* "${_hDir}"
3462
	rm ${_hDir}/*.sha1 >/dev/null 2>/dev/null
3463

    
3464
	# Get the total number of files in the STAGEDIR
3465
	get_filetotal_dir "${PBI_STAGEDIR}"
3466
	echo "${FILETOTAL}" > "${PBI_HEADERDIR}/pbi_archivecount"
3467

    
3468
	# Save a checksum of archive file
3469
	sha256 -q "${PBI_CREATE_ARCHIVE}" > "${PBI_HEADERDIR}/pbi_archivesum"
3470

    
3471
	# Sign any header files
3472
	sign_pbi_files "$PBI_HEADERDIR"
3473

    
3474
	# Make the header archive
3475
	mk_header_file
3476

    
3477
	# Remove the new headerdir
3478
	rm -rf "$PBI_HEADERDIR"
3479
	
3480
	# Now finish up and make the resulting PBI file
3481
	mk_output_pbi
3482

    
3483
}
3484

    
3485

    
3486
# Vars required for creation
3487
check_create_required_vars() {
3488
	if [ -z "${PBI_PROGNAME}" ] ; then exit_err "Missing PBI_PROGNAME"; fi
3489
	if [ -z "${PBI_PROGVERSION}" ] ; then exit_err "Missing PBI_PROGVERSION"; fi
3490
	if [ -z "${PBI_PROGAUTHOR}" ] ; then exit_err "Missing PBI_PROGAUTHOR"; fi
3491
	if [ -z "${PBI_PROGWEB}" ] ; then exit_err "Missing PBI_PROGWEB"; fi
3492
}
3493

    
3494
# Start the pbi_create process
3495
do_pbi_create() {
3496
	get_pbi_progname
3497
	echo "Creating PBI: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3498

    
3499

    
3500
	if [ "`basename $0`" = "pbi_makeport" -o "`basename $0`" = "pbi_makeport_chroot" ] ; then
3501
	  PBI_STAGEDIR="${PBI_PROGDIRPATH}"
3502
	else
3503
	  mk_stage_dir
3504
	fi
3505

    
3506
	copy_resource_dir
3507
	clean_stage_dir
3508

    
3509
	mk_extlink_entries
3510
	clean_icons_dir
3511
	mk_xdg_scripts
3512

    
3513
	run_pbi_prepkgscript
3514

    
3515
	mk_install_script
3516
	mk_deinstall_script
3517

    
3518
	mk_hash_list
3519

    
3520
	mk_archive_file
3521

    
3522
	mk_header_dir
3523
 	save_pbi_details_to_header
3524
	mk_header_file
3525
	rm_header_dir
3526

    
3527
	mk_output_pbi
3528

    
3529
	rm_stage_dir
3530
}
3531

    
3532
# Start looping through and creating a hash-list of files
3533
mk_hash_list() {
3534
  	if [ "${PBI_CREATE_HASHLIST}" = "NO" ] ; then return 0 ; fi
3535
	echo "Creating hash list..."
3536

    
3537
	hashfile="${PBI_STAGEDIR}/${PBI_HASHLIST}"
3538

    
3539
	if [ -e "${hashfile}" ] ; then rm "${hashfile}" ; fi
3540

    
3541
	for hdir in ${HASH_SEARCH_DIRS}
3542
	do
3543
		if [ ! -d "${PBI_STAGEDIR}/${hdir}" ] ; then continue ; fi
3544
	 	save_dir_hash_list "${hdir}" "${hashfile}"	
3545
	done
3546
}
3547

    
3548
#  Read the specified directory and save hashsums of each file
3549
save_dir_hash_list() {
3550
	cd ${PBI_STAGEDIR}
3551
	tmp_hashdir="${PBI_STAGEDIR}/.tmp-hash.$$"
3552
	find "${1}" -type f > ${tmp_hashdir}
3553
	while read line
3554
	do
3555
		if [ ! -f "$line" -o -h "$line" ] ; then continue ; fi
3556
		
3557
		# Make sure this isn't a binary executable
3558
		file "${line}" | grep "executable," >/dev/null 2>/dev/null
3559
		if [ "$?" = "0" ] ; then continue ; fi
3560

    
3561
		# Ignore files / libs with the full PREFIX hard-coded
3562
		strings "${line}" | grep "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
3563
		if [ "$?" = "0" ]; then continue ; fi
3564

    
3565
		# Check if this hash file is excluded
3566
		_hfound="0"
3567
		if [ -n "${PBI_HASH_EXCLUDES}" ] ; then
3568
			for _hexcl in ${PBI_HASH_EXCLUDES}
3569
			do
3570
				if [ "$_hexcl" = "$line" ] ; then
3571
					_hfound="1"
3572
				fi
3573
			done
3574
			if [ "$_hfound" = "1" ] ; then
3575
				continue
3576
			fi
3577
		fi	
3578

    
3579
		# Get the file size
3580
		tSize=`du -k "${line}" | awk '{print $1}'`
3581
		if [ $(is_num "$tSize") ] ; then 
3582
			# If the file is less than 10Kb, we can skip
3583
			if [ $tSize -lt 10 ] ; then continue ; fi
3584

    
3585
			# Add to the hash-dir
3586
	 		sha=`sha256 -q "$line"`
3587
			echo "${line}:::${sha}" >> ${2}
3588
		fi
3589
	done < ${tmp_hashdir}
3590
	rm ${tmp_hashdir}
3591
	cd /
3592
}
3593

    
3594
# Parse any external link directives
3595
mk_extlink_entries() {
3596
	echo "Creating external link entries..."
3597
	init_tmpdir
3598
	_extf="${PBI_CONFDIR}/${MOD_EXTLINKFILE}"
3599
	_autoextf="${PBI_STAGEDIR}/${MOD_AUTOEXTLINKFILE}"
3600
	_tmpextf="${PBI_TMPDIR}/${MOD_AUTOEXTLINKFILE}.$$"
3601
  	if [ ! -e "${_extf}" -a ! -e "${_autoextf}" ] ; then return 0 ; fi
3602

    
3603
	dir="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}"
3604
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3605

    
3606
	# Create the headers for the PATH link scripts
3607
        echo "#!/bin/sh" >"${dir}/${PBI_INS_PATHSCRIPT}"
3608
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_PATHSCRIPT}"
3609

    
3610
	# Make sure we also set SYS_LOCALBASE in case user runs these stand-alone at some point
3611
        echo "if [ -z \"\$SYS_LOCALBASE\" ]; then SYS_LOCALBASE=\"${SYS_LOCALBASE}\" ; fi" >"${dir}/${PBI_INS_PATHSCRIPT}"
3612
        echo "if [ -z \"\$SYS_LOCALBASE\" ]; then SYS_LOCALBASE=\"${SYS_LOCALBASE}\" ; fi" >"${dir}/${PBI_UNINS_PATHSCRIPT}"
3613

    
3614
	touch "$_tmpextf"
3615
	if [ -e "$_autoextf" ]; then cat "${_autoextf}" >> "${_tmpextf}" ; fi
3616
	if [ -e "$_extf" ]; then cat "${_extf}" >> "${_tmpextf}" ; fi
3617

    
3618
        while read line
3619
        do
3620
		_bin="NO"
3621
		_wraponly="NO"
3622
		_crashhandle="YES"
3623
		_keep="YES"
3624
		_linux="NO"
3625
                echo $line | tr '\t' ' ' | tr -s ' ' | grep "^#" >/dev/null 2>/dev/null
3626
                if [ "$?" != "0" ] ; then
3627
                        src="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 1`"
3628
                        tar="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 2`"
3629
                        act="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 3`"
3630

    
3631
			if [ -z "$src" -o -z "$tar" ] ; then continue ; fi
3632

    
3633
			# Check if this is an icon we need to preserve
3634
			echo $src | grep -q "^share/icons/"
3635
			if [ $? -eq 0 -a "${PBI_USESYSFONTS}" != "NO" ] ; then
3636
				iDir=`dirname $src`
3637
				if [ ! -d "${PBI_STAGEDIR}/${PBI_ICDIR}/${iDir}" ] ; then 
3638
					mkdir -p "${PBI_STAGEDIR}/${PBI_ICDIR}/${iDir}"
3639
				fi
3640
				cp "${PBI_STAGEDIR}/${src}" "${PBI_STAGEDIR}/${PBI_ICDIR}/${iDir}"
3641
				src="${PBI_ICDIR}/${src}"
3642
			fi
3643

    
3644
			if [ ! -e "${PBI_STAGEDIR}/$src" ] ; then
3645
				echo "WARN: external_link target: \"$src -> $tar $act\" does not exist!"
3646
				continue
3647
			fi
3648

    
3649
			# Check for act directives
3650
			for i in `echo ${act} | sed 's|,| |g'`
3651
  			do
3652
				case ${i} in
3653
					binary) _bin="YES" ;;
3654
	  			    binwrapper) _bin="YES" ; _wraponly="YES" ;;
3655
				       nocrash) _crashhandle="NO" ;;
3656
				          keep) _keep="YES" ;;
3657
				       replace) _keep="NO" ;;
3658
				         linux) _bin="YES" ; _linux="YES" ;;
3659
					*) echo "Warning: Unknown option \"$i\" in ${MOD_EXTLINKFILE}";;
3660
				esac
3661
				
3662
			done
3663

    
3664
			# Make sure SYS_LOCALBASE/$tar dir exists
3665
			echo "_bd=\"\`dirname \$SYS_LOCALBASE/$tar\`\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3666
			echo "if [ ! -d \"\$_bd\" ] ; then" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3667
			echo "	mkdir -p \"\${_bd}\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3668
			echo "fi" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3669

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

    
3673
				# Make sure we don't create any duplicates
3674
				echo "$_donewrap" | grep "#${src}#" >/dev/null 2>/dev/null
3675
				if [ "$?" = "0" ] ; then continue ; fi
3676
				
3677
				# Make the binary wrapper
3678
				mk_path_wrappers "$src" "$tar" "$_crashhandle" "$_wraponly" "$_linux"
3679

    
3680
				# This binary is done, save it now so we don't duplicate later
3681
				_donewrap="$_donewrap #${src}#"
3682
			else
3683
				# Make our link commands
3684
				if [ "$_keep" = "YES" ] ; then _lop="-fs"; else _lop="-s"; fi
3685
				echo "ln ${_lop} $PBI_PROGDIRPATH/${src} \$SYS_LOCALBASE/${tar}" \
3686
					>> "${dir}/${PBI_INS_PATHSCRIPT}"
3687
			fi
3688

    
3689
			# Make the uninstall command
3690
			echo "ls -al \"\$SYS_LOCALBASE/$tar\" | grep \"> $PBI_PROGDIRPATH\" >/dev/null 2>/dev/null " \
3691
				>> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3692
			echo "if [ \"\$?\" = \"0\" ] ; then" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3693
			echo "	rm \"\$SYS_LOCALBASE/${tar}\"" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3694
			echo "fi" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3695

    
3696
			echo " " >> "${dir}/${PBI_INS_PATHSCRIPT}"
3697
			echo " " >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3698

    
3699

    
3700

    
3701
                fi
3702

    
3703
        done < "${_tmpextf}"
3704
	rm "${_tmpextf}"
3705

    
3706
	chmod 755 "${dir}/${PBI_INS_PATHSCRIPT}"
3707
	chmod 755 "${dir}/${PBI_UNINS_PATHSCRIPT}"
3708
}
3709

    
3710

    
3711
# Create the wrapper scripts for the specified binaries 
3712
mk_path_wrappers() {
3713
	dir="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}"
3714
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3715

    
3716
	bin="${1}"
3717
	fbin="`basename ${bin}`"
3718
	tar="${2}"
3719
	ch="${3}"
3720
	onlywrap="${4}"
3721
	linwrap="${5}"
3722

    
3723
	# Check if the fake-bin wrapper already exists, and if so use
3724
	# a different name
3725
	if [ -e "${dir}/${fbin}" ] ; then
3726
		fbin=`echo $bin | sed 's|/|-|g'`
3727
	fi
3728

    
3729
	# Make our link to the system localbase if its not a wrapper only
3730
 	if [ "$onlywrap" != "YES" ] ; then	
3731
		echo "ln -fs $PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${fbin} \$SYS_LOCALBASE/${tar}" \
3732
			>> "${dir}/${PBI_INS_PATHSCRIPT}"
3733
	fi
3734

    
3735
	# Copy the wrapper binary
3736
	PBI_WRAPPERFILE="${PBI_APPDIR}/.pbiwrapper-$ARCH"
3737
	cp ${PBI_WRAPPERFILE} ${dir}/${fbin}
3738
	chmod 755 ${dir}/${fbin}
3739

    
3740
	# Create the wrapper .pbiopt
3741
	echo "PROGDIR: ${PBI_PROGDIRPATH}" >${dir}/${fbin}.pbiopt
3742
	echo "TARGET: ${bin}" >>${dir}/${fbin}.pbiopt
3743

    
3744
	# Figure out the extra ldconfig dirs
3745
	LDCONFIGDIRS=""
3746
	if [ -d "${PBI_STAGEDIR}/libdata/ldconfig" ] ; then
3747
	  for _ldc in `ls ${PBI_STAGEDIR}/libdata/ldconfig 2>/dev/null`
3748
 	  do
3749
   	     while read TMP
3750
  	     do
3751
      	       echo $LDCONFIGDIRS | grep "${TMP}:" >/dev/null 2>/dev/null
3752
      	       if [ "$?" != "0" ]; then
3753
        	 LDCONFIGDIRS="${TMP}:${LDCONFIGDIRS}"
3754
     	       fi
3755
    	     done < ${PBI_STAGEDIR}/libdata/ldconfig/${_ldc}
3756
          done
3757
        fi
3758

    
3759
	# If this is marked as a linux app, make sure we point to the linux libs first
3760
	if [ "$linwrap" = "YES" ] ; then
3761
	  LDCONFIGDIRS="${PROGDIR}/linuxlib"
3762
	fi
3763

    
3764
	# Create the wrapper .ldhints
3765
	echo "${LDCONFIGDIRS}" >${dir}/${fbin}.ldhints
3766
}
3767

    
3768
# Create any XDG script for install / deinstall
3769
mk_xdg_scripts() {
3770
 	echo "Creating xdg scripts..."
3771
  	mk_xdg_desktop_script
3772
  	mk_xdg_menu_script
3773
  	mk_xdg_mime_script
3774
}
3775

    
3776
# Create any XDG script for desktop icons
3777
mk_xdg_desktop_script() {
3778
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGDESK_DIR}" ] ; then return 0 ; fi
3779
	_dFound=0
3780

    
3781
	dir="${PBI_STAGEDIR}/${PBI_APPDESK_DIR}"
3782
	if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3783
	echo "#!/bin/sh" >"${dir}/${PBI_INS_DESKSCRIPT}"
3784
	echo "#!/bin/sh" >"${dir}/${PBI_UNINS_DESKSCRIPT}"
3785

    
3786
  	cd "${PBI_CONFDIR}/${MOD_XDGDESK_DIR}"
3787
  	for i in `ls *.desktop 2>/dev/null`
3788
  	do
3789
		_dFound=1
3790

    
3791
		# Copy over the .desktop file, modifying any variables within
3792
	        cat "${i}" \
3793
           	| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
3794
		| sed "s|%%PBI_APPDIR%%|$PBI_PROGDIRPATH|g" \
3795
		> "${dir}/PBI-${i}"
3796

    
3797
		# Set the correct permissions on the desktop file
3798
		chmod 744 "${dir}/PBI-${i}"
3799

    
3800
		ifi="$PBI_PROGDIRPATH/${PBI_APPDESK_DIR}/PBI-${i}"
3801

    
3802
		echo "xdg-desktop-icon install --novendor ${ifi}" \
3803
			 >> "${dir}/${PBI_INS_DESKSCRIPT}"
3804
		echo "xdg-desktop-icon uninstall ${ifi}" \
3805
			 >> "${dir}/${PBI_UNINS_DESKSCRIPT}"
3806
		
3807
  	done
3808

    
3809
	chmod 755 "${dir}/${PBI_INS_DESKSCRIPT}"
3810
	chmod 755 "${dir}/${PBI_UNINS_DESKSCRIPT}"
3811

    
3812
	# No desktop entries
3813
        if [ "$_dFound" = "0" ] ; then
3814
                rm "${dir}/${PBI_INS_DESKSCRIPT}"
3815
                rm "${dir}/${PBI_UNINS_DESKSCRIPT}"
3816
        fi
3817
}
3818

    
3819
# Create any XDG script for menu icons
3820
mk_xdg_menu_script() {
3821
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGMENU_DIR}" ] ; then return 0 ; fi
3822

    
3823
	_mFound=0
3824

    
3825
	dir="${PBI_STAGEDIR}/${PBI_APPMENU_DIR}"
3826
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3827
        echo "#!/bin/sh" >"${dir}/${PBI_INS_MENUSCRIPT}"
3828
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_MENUSCRIPT}"
3829

    
3830
  	cd "${PBI_CONFDIR}/${MOD_XDGMENU_DIR}"
3831
  	for i in `ls *.desktop 2>/dev/null`
3832
  	do
3833
		_mFound=1
3834

    
3835
		# Copy the desktop file, changing any included vars
3836
	        cat "${i}" \
3837
           	| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
3838
		| sed "s|%%PBI_APPDIR%%|$PBI_PROGDIRPATH|g" \
3839
		> "${dir}/PBI-${i}"
3840

    
3841
		# Set the correct permissions on the menu file
3842
		chmod 744 "${dir}/PBI-${i}"
3843

    
3844
		ifi="$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/PBI-${i}"
3845

    
3846
		# Check for a .directory file associated with this .desktop
3847
		ifd=""
3848
		dirfile="`basename -s .desktop ${i}`"
3849
		if [ -e "${dirfile}.directory" ] ; then
3850
	        	cat "${dirfile}.directory" \
3851
           		| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
3852
			| sed "s|%%PBI_APPDIR%%|$PBI_PROGDIRPATH|g" \
3853
			> "${dir}/PBI-${dirfile}.directory"
3854
			#cp "${dirfile}.directory" "${dir}/PBI-${dirfile}.directory"
3855
			ifd="$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/PBI-${dirfile}.directory "	
3856
		fi
3857

    
3858
		echo "xdg-desktop-menu install --novendor ${ifd}${ifi}" \
3859
			 >> "${dir}/${PBI_INS_MENUSCRIPT}"
3860
		echo "xdg-desktop-menu uninstall ${ifd}${ifi}" \
3861
			 >> "${dir}/${PBI_UNINS_MENUSCRIPT}"
3862

    
3863
  	done
3864

    
3865
	chmod 755 "${dir}/${PBI_INS_MENUSCRIPT}"
3866
	chmod 755 "${dir}/${PBI_UNINS_MENUSCRIPT}"
3867

    
3868
	# No mime entries
3869
        if [ "$_mFound" = "0" ] ; then
3870
                rm "${dir}/${PBI_INS_MENUSCRIPT}"
3871
                rm "${dir}/${PBI_UNINS_MENUSCRIPT}"
3872
        fi
3873
}
3874

    
3875
# Create any XDG script for mime types
3876
mk_xdg_mime_script() {
3877
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGMIME_DIR}" ] ; then return 0 ; fi
3878
	_mFound=0
3879

    
3880
        dir="${PBI_STAGEDIR}/${PBI_APPMIME_DIR}"
3881
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3882
        echo "#!/bin/sh" >"${dir}/${PBI_INS_MIMESCRIPT}"
3883
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_MIMESCRIPT}"
3884

    
3885

    
3886
  	cd "${PBI_CONFDIR}/${MOD_XDGMIME_DIR}"
3887
  	for i in `ls *.xml 2>/dev/null`
3888
  	do
3889
		_mFound=1
3890
		cp "${i}" "${dir}/PBI-${i}"
3891
		ifi="$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/PBI-${i}"
3892

    
3893
		# Check for a .directory file associated with this .desktop
3894
		ifp=""
3895
		iconfile="`basename -s .xml ${i}`"
3896
		if [ -e "${iconfile}.png" ] ; then
3897
			cp "${iconfile}.png" "${dir}/${iconfile}.png"
3898
			ifp="$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${iconfile}.png"
3899
			mi=`cat "$i" | grep '<mime-type' | cut -d '"' -f 2 | sed 's|/|-|g'`
3900
			echo "xdg-icon-resource install --novendor --context mimetypes ${ifp} --size 64 $mi" \
3901
				 >> "${dir}/${PBI_INS_MIMESCRIPT}"
3902
			echo "xdg-icon-resource uninstall --context mimetypes ${ifp} --size 64" \
3903
				 >> "${dir}/${PBI_UNINS_MIMESCRIPT}"
3904
		fi
3905

    
3906
		echo "xdg-mime install --novendor ${ifi}" \
3907
			 >> "${dir}/${PBI_INS_MIMESCRIPT}"
3908
		echo "xdg-mime uninstall ${ifi}" \
3909
			 >> "${dir}/${PBI_UNINS_MIMESCRIPT}"
3910
  	done
3911

    
3912
	chmod 755 "${dir}/${PBI_INS_MIMESCRIPT}"
3913
	chmod 755 "${dir}/${PBI_UNINS_MIMESCRIPT}"
3914

    
3915
	# No mime entries
3916
	if [ "$_mFound" = "0" ] ; then
3917
		rm "${dir}/${PBI_INS_MIMESCRIPT}"
3918
		rm "${dir}/${PBI_UNINS_MIMESCRIPT}"
3919
	fi
3920
}
3921

    
3922

    
3923
# Create the install script for the PBI
3924
mk_install_script() {
3925
	echo "Creating install script..."
3926
	if [ ! -d "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}" ] ; then mkdir -p "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}" ; fi
3927
	insc="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/.pbi-install.sh"
3928
	echo "#!/bin/sh" > "$insc"
3929
	echo "PBI_WRAPPERBIN=\"${PBI_FAKEBIN_DIR}\"" >> "$insc"
3930
	echo "PBI_PROGDIRPATH=\"${PBI_PROGDIRPATH}\"" >> "$insc"
3931
	echo "SYS_LOCALBASE=\"${SYS_LOCALBASE}\"" >> "$insc"
3932
	echo "cd \"\$PBI_PROGDIRPATH\"" >> "$insc"
3933

    
3934
	# Xorg Font setup
3935
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
3936
		echo 'if [ -d "${PBI_PROGDIRPATH}/etc" ] ; then' >> "$insc"
3937
		echo '	rm "${PBI_PROGDIRPATH}/etc/fonts" >/dev/null 2>/dev/null' >> "$insc"
3938
		echo '	ln -fs "${SYS_LOCALBASE}/etc/fonts" "${PBI_PROGDIRPATH}/etc/fonts"' >> "$insc"
3939
		echo 'fi' >> "$insc"
3940
		echo 'if [ -d "${PBI_PROGDIRPATH}/lib/X11" ] ; then' >> "$insc"
3941
		echo '	rm "${PBI_PROGDIRPATH}/lib/X11/fonts" >/dev/null 2>/dev/null' >> "$insc"
3942
		echo '	ln -fs "${SYS_LOCALBASE}/lib/X11/fonts" "${PBI_PROGDIRPATH}/lib/X11/fonts"' >> "$insc"
3943
		echo '	rm "${PBI_PROGDIRPATH}/lib/X11/icons" >/dev/null 2>/dev/null' >> "$insc"
3944
		echo '	ln -fs "${SYS_LOCALBASE}/lib/X11/icons" "${PBI_PROGDIRPATH}/lib/X11/icons"' >> "$insc"
3945
		echo '	rm "${PBI_PROGDIRPATH}/share/icons" >/dev/null 2>/dev/null' >> "$insc"
3946
		echo '	ln -fs "${SYS_LOCALBASE}/share/icons" "${PBI_PROGDIRPATH}/share/icons"' >> "$insc"
3947
		echo 'fi' >> "$insc"
3948
	fi
3949

    
3950
	# Add the binary wrapper sym-links
3951
        if [ -e "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" ] ; then
3952
		echo 'if [ `id -u` = "0" ] ; then ' >>${insc}
3953
		echo "	$PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" >>${insc}
3954
		echo "fi" >>${insc}
3955
	fi
3956

    
3957
	# Look for any XDG scripts
3958
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMIME_DIR}/${PBI_INS_MIMESCRIPT}" ] ; then
3959
		echo "$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${PBI_INS_MIMESCRIPT}" >>${insc}
3960
	fi
3961
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMENU_DIR}/${PBI_INS_MENUSCRIPT}" ] ; then
3962
		echo "$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/${PBI_INS_MENUSCRIPT}" >>${insc}
3963
	fi
3964

    
3965
	chmod 755 "${insc}"
3966
	
3967
}
3968

    
3969
# Create the deinstall script for the PBI
3970
mk_deinstall_script() {
3971
	echo "Creating deinstall script..."
3972
	uisc="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/.pbi-uninstall.sh"
3973

    
3974
	echo "#!/bin/sh" > "$uisc"
3975
	echo "PBI_PROGDIRPATH=\"${PBI_PROGDIRPATH}\"" >> "$uisc"
3976
	echo "SYS_LOCALBASE=\"${SYS_LOCALBASE}\"" >> "$uisc"
3977

    
3978
	# Remove the binary wrapper sym-links
3979
        if [ -e "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" ] ; then
3980
		echo 'if [ `id -u` = "0" ] ; then ' >>${uisc}
3981
		echo "	$PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" >>${uisc}
3982
		echo "fi" >>${uisc}
3983
	fi
3984

    
3985
	# Look for any XDG scripts
3986
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMIME_DIR}/${PBI_UNINS_MIMESCRIPT}" ] ; then
3987
		echo "$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${PBI_UNINS_MIMESCRIPT}" >>${uisc}
3988
	fi
3989
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMENU_DIR}/${PBI_UNINS_MENUSCRIPT}" ] ; then
3990
		echo "$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/${PBI_UNINS_MENUSCRIPT}" >>${uisc}
3991
	fi
3992
	chmod 755 "${uisc}"
3993
}
3994

    
3995
# Create a dir for manipulating header info
3996
mk_header_dir() {
3997
	PBI_HEADERDIR="${PBI_PROGDIRPATH}/.headerdir"
3998
	if [ -e "${PBI_HEADERDIR}" ] ; then rm -rf "${PBI_HEADERDIR}" ; fi
3999
	mkdir -p ${PBI_HEADERDIR}
4000
}
4001

    
4002
# Remove the tmp header-dir
4003
rm_header_dir() {
4004
	PBI_HEADERDIR="${PBI_PROGDIRPATH}/.headerdir"
4005
	if [ -e "${PBI_HEADERDIR}" ] ; then rm -rf "${PBI_HEADERDIR}" ; fi
4006
}
4007

    
4008
# Create a dir for staging the final archive
4009
mk_stage_dir() {
4010
	local _excOpts=""
4011

    
4012
	PBI_STAGEDIR="${PBI_PROGDIRPATH}/.stagedir"
4013
	echo "Creating Stage Dir: ${PBI_STAGEDIR}"
4014
	if [ -e "${PBI_STAGEDIR}" ] ; then 
4015
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4016
		chflags -R noschg ${PBI_STAGEDIR} 2>/dev/null
4017
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4018
	fi
4019
	mkdir -p ${PBI_STAGEDIR}
4020

    
4021
	# Build module list of excludes
4022
	if [ -n "$PBI_EXCLUDELIST" ] ; then
4023
		for excl in $PBI_EXCLUDELIST
4024
		do
4025
			if [ -z "$_excOpts" ] ; then
4026
				_excOpts="--exclude ${excl}"
4027
			else
4028
				_excOpts="$_excOpts --exclude ${excl}"
4029
			fi
4030
		done
4031
	fi
4032

    
4033
	# Now copy the stagedir
4034
	tar cvf - ${_excOpts} --exclude .stagedir \
4035
		--exclude .pkgdb --exclude .ld-elf.hints --exclude make.conf \
4036
		--exclude make.conf.bak --exclude .keepports \
4037
		-C "${PBI_PROGDIRPATH}" . 2>/dev/null \
4038
		| tar xvpf - -C ${PBI_STAGEDIR} 2>/dev/null
4039

    
4040
}
4041

    
4042
# Remove the stagedir
4043
rm_stage_dir() {
4044
	cd /
4045
	PBI_STAGEDIR="${PBI_PROGDIRPATH}/.stagedir"
4046
	if [ -e "${PBI_STAGEDIR}" ] ; then 
4047
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4048
		chflags -R noschg ${PBI_STAGEDIR} 2>/dev/null
4049
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
4050
	fi
4051
}
4052

    
4053
# See if we need to clean the icons dir
4054
clean_icons_dir() {
4055
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
4056
		rm -rf ${PBI_STAGEDIR}/share/icons >/dev/null 2>/dev/null
4057
	fi
4058
}
4059

    
4060
# See if we need to clean the stagedir
4061
clean_stage_dir() {
4062
	if [ "${PBI_USESYSGL}" != "NO" ] ; then
4063
		rm ${PBI_STAGEDIR}/lib/libGl.* >/dev/null 2>/dev/null
4064
		rm ${PBI_STAGEDIR}/lib/libGL.* >/dev/null 2>/dev/null
4065
		rm ${PBI_STAGEDIR}/lib/libGLU.* >/dev/null 2>/dev/null
4066
	fi
4067
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
4068
		rm -rf ${PBI_STAGEDIR}/etc/fonts >/dev/null 2>/dev/null
4069
		rm -rf ${PBI_STAGEDIR}/lib/X11/fonts >/dev/null 2>/dev/null
4070
		rm -rf ${PBI_STAGEDIR}/lib/X11/icons >/dev/null 2>/dev/null
4071
	fi
4072
}
4073

    
4074
# Copy over any resource files into the PBI dir
4075
copy_resource_dir() {
4076
	if [ -d "${PBI_CONFDIR}/${PBI_RESOURCE_DIR}" ] ; then
4077
		echo "Copying ${PBI_CONFDIR}/${PBI_RESOURCE_DIR} -> ${PBI_STAGEDIR}"
4078
		tar cvf - -C ${PBI_CONFDIR}/${PBI_RESOURCE_DIR} --exclude .svn . 2>/dev/null \
4079
		| tar xvpf - -C ${PBI_STAGEDIR} 2>/dev/null
4080
	fi
4081
}
4082

    
4083
# Check if tar supports lzma compression
4084
test_tar_lzma() {
4085
	touch /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
4086
	tar cvJf /tmp/.pbilzma.tar.$$ /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
4087
	_exitcode=$?
4088
	rm /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
4089
	rm /tmp/.pbilzma.tar.$$ >/dev/null 2>/dev/null
4090
	return $_exitcode
4091
}
4092

    
4093
# Start creating the application archive 
4094
mk_archive_file() {
4095
        # Build module list of excludes
4096
        if [ -n "$PBI_EXCLUDELIST" ] ; then
4097
                for excl in $PBI_EXCLUDELIST
4098
                do
4099
                        if [ -z "$_excOpts" ] ; then
4100
                                _excOpts="--exclude ${excl}"
4101
                        else
4102
                                _excOpts="$_excOpts --exclude ${excl}"
4103
                        fi
4104
                done
4105
        fi
4106
	PBI_CREATE_ARCHIVE="${PBI_CREATE_OUTDIR}/.PBI.$$.tbz"
4107
	if test_tar_lzma ; then _tcmp="J" ; else _tcmp="j" ; fi
4108
	echo "Creating compressed archive..."
4109
	tar cv${_tcmp}f "${PBI_CREATE_ARCHIVE}" ${_excOpts} -C ${PBI_STAGEDIR} . 2>/dev/null 
4110
}
4111

    
4112
# Start creating the header archive
4113
mk_header_file() {
4114
	PBI_HEADER_ARCHIVE="${PBI_CREATE_OUTDIR}/.PBI-header.$$.tbz"
4115
	tar cvjf ${PBI_HEADER_ARCHIVE} -C ${PBI_HEADERDIR} . >/dev/null 2>/dev/null
4116
}
4117

    
4118
# Start copying pbi details into header file
4119
save_pbi_details_to_header() {
4120
	local _osArch="$ARCH"
4121
	local _osRel="$FBSDREL"
4122
	if [ -n "${PBI_OSREL}" ] ; then
4123
		_osRel="${PBI_OSREL}"
4124
	fi
4125

    
4126
	if [ "${PBI_CREATEONLY}" = "YES" ] ; then
4127
		_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
4128
		echo "${PBI_APPDIR}/${_pbilow}-${_osArch}" > "${PBI_HEADERDIR}/pbi_defaultpath"
4129
	else	
4130
		echo "${PBI_PROGDIRPATH}" > "${PBI_HEADERDIR}/pbi_defaultpath"
4131
	fi
4132
	echo "${PBI_PROGNAME}" > "${PBI_HEADERDIR}/pbi_name"
4133
	echo "${PBI_PROGVERSION}" > "${PBI_HEADERDIR}/pbi_version"
4134
	echo "${PBI_PROGAUTHOR}" > "${PBI_HEADERDIR}/pbi_author"
4135
	echo "${PBI_PROGWEB}" > "${PBI_HEADERDIR}/pbi_web"
4136
	date "+%Y%m%d %H%M%S" > "${PBI_HEADERDIR}/pbi_mdate"
4137

    
4138
	if [ "${PBI_REQUIRESROOT}" = "YES" ] ; then
4139
		touch ${PBI_HEADERDIR}/pbi_requiresroot
4140
	fi
4141

    
4142
	# Do we have a license to accept?
4143
	if [ -e "${PBI_CONFDIR}/${PBI_LICENSEFILE}" ] ; then
4144
		cp "${PBI_CONFDIR}/${PBI_LICENSEFILE}" "${PBI_HEADERDIR}/${PBI_LICENSEFILE}"
4145
	fi
4146

    
4147
	# Custom install / remove scripts
4148
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREINS}" ] ; then
4149
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREINS}" \
4150
			"${PBI_HEADERDIR}/${MOD_PREINS}"
4151
	else
4152
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_PREINS}
4153
	fi
4154
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_POSTINS}" ] ; then
4155
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_POSTINS}" \
4156
			"${PBI_HEADERDIR}/${MOD_POSTINS}"
4157
	else
4158
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_POSTINS}
4159
	fi
4160
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREREM}" ] ; then
4161
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREREM}" \
4162
			"${PBI_HEADERDIR}/${MOD_PREREM}"
4163
	else
4164
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_PREREM}
4165
	fi
4166

    
4167
	# Copy over our icon
4168
	if [ -n "${PBI_PROGICON}" -a -e "${PBI_STAGEDIR}/${PBI_PROGICON}" ] ; then
4169
		# Get the file extension
4170
		_iconExt=`echo "$PBI_PROGICON" | awk -F . '{print $NF}'`
4171
		cp "${PBI_STAGEDIR}/${PBI_PROGICON}" "${PBI_HEADERDIR}/pbi_icon.${_iconExt}" >/dev/null 2>/dev/null
4172
	else
4173
		_iconExt=`echo "$PBI_DEFAULT_ICON_CHROOT" | awk -F . '{print $NF}'`
4174
		cp "${PBI_DEFAULT_ICON_CHROOT}" "${PBI_HEADERDIR}/pbi_icon.${_iconExt}" >/dev/null 2>/dev/null
4175
	fi
4176

    
4177
	# Check for any gui images
4178
	if [ -e "${PBI_STAGEDIR}/${PBI_GUITOPBANNER}" ] ; then
4179
		cp "${PBI_STAGEDIR}/${PBI_GUITOPBANNER}" "${PBI_HEADERDIR}/top-banner.png"
4180
	fi
4181
	if [ -e "${PBI_STAGEDIR}/${PBI_GUISIDEBANNER}" ] ; then
4182
		cp "${PBI_STAGEDIR}/${PBI_GUISIDEBANNER}" "${PBI_HEADERDIR}/side-banner.png"
4183
	fi
4184

    
4185
	# Save the uname details
4186
	echo "${_osArch}" > "${PBI_HEADERDIR}/pbi_arch"
4187
	echo "${_osRel}" > "${PBI_HEADERDIR}/pbi_fbsdver"
4188
	echo "${PROGVERSION}" > "${PBI_HEADERDIR}/pbi_createver"
4189

    
4190
	# Get the total number of files in the STAGEDIR
4191
	get_filetotal_dir "${PBI_STAGEDIR}"
4192
	echo "${FILETOTAL}" > "${PBI_HEADERDIR}/pbi_archivecount"
4193

    
4194
	# Save a checksum of archive file
4195
	sha256 -q "${PBI_CREATE_ARCHIVE}" > "${PBI_HEADERDIR}/pbi_archivesum"
4196

    
4197
	sign_pbi_files "$PBI_HEADERDIR"
4198
}
4199

    
4200
# Use openssl to sign parts of the pbi header structure and archive 
4201
sign_pbi_files() {
4202
	if [ -z "${PBI_SSLPRIVKEY}" ] ; then return 0 ; fi
4203
	_sf="${1}/pbi_archivesum ${1}/${MOD_PREINS} ${1}/${MOD_POSTINS} ${1}/${MOD_PREREM}"
4204
	for i in $_sf
4205
	do
4206
		openssl dgst -sha1 \
4207
  			-sign ${PBI_SSLPRIVKEY} \
4208
  			-out ${i}.sha1 \
4209
  			${i} >/dev/null 2>/dev/null
4210
	done
4211
}
4212

    
4213

    
4214
# All the pieces are ready, spit out the final PBI file
4215
mk_output_pbi() {
4216
        if [ -n "${PBI_PROGICON}" -a -e "${PBI_STAGEDIR}/${PBI_PROGICON}" ] ; then
4217
                icon="${PBI_STAGEDIR}/${PBI_PROGICON}"
4218
        else
4219
                icon="${PBI_DEFAULT_ICON_CHROOT}"
4220
        fi
4221
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
4222

    
4223
	outfile="${PBI_CREATE_OUTDIR}/${_pbilow}-${PBI_PROGVERSION}-${ARCH}.pbi"
4224
	mark1="${PBI_CREATE_OUTDIR}/.pbimark1.$$"
4225
	mark2="${PBI_CREATE_OUTDIR}/.pbimark2.$$"
4226

    
4227
	echo "
4228
${PBI_SS_ICON}" >$mark1
4229
	echo "
4230
${PBI_SS_ARCHIVE}" >$mark2
4231

    
4232
	# DO IT, DO IT NOW!!!
4233
	cat ${PBI_HEADER_ARCHIVE} $mark1 ${icon} $mark2 ${PBI_CREATE_ARCHIVE} > ${outfile}	
4234
	sha256 -q ${outfile} > ${outfile}.sha256
4235

    
4236
	echo "Created PBI: ${outfile}"
4237

    
4238
	rm $mark1
4239
	rm $mark2
4240
	rm ${PBI_HEADER_ARCHIVE}
4241
	rm ${PBI_CREATE_ARCHIVE}
4242
}
4243

    
4244
get_filetotal_dir() {
4245
	FILETOTAL="`find ${1} | wc -l | tr -d ' '`"
4246
}
4247

    
4248
pbi_delete_init() {
4249
  	require_root_or_group
4250
	init_tmpdir
4251
	parse_delete_pbi_cmdline "$@"
4252
	do_pbi_delete
4253
}
4254

    
4255
# Delete this PBI
4256
do_pbi_delete() {
4257
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4258
	PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}"
4259

    
4260
	get_username_from_file "${PBI_DBAPPDIR}/${PBI_DELETENAME}/pbi_name"
4261
	if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
4262
		exit_err "Permission denied to modify PBI installed by: $FILEUSER"
4263
	fi
4264

    
4265
	# Set the dirty flag that we are removing this PBI
4266
	touch ${PBI_DBAPPDIR}/${PBI_DELETENAME}/.pbiDeleted
4267

    
4268
	check_preremove_script
4269
	run_remove_script
4270
 	remove_pbidir
4271
	unregister_pbi
4272
	
4273
	# Mark the hashdir as dirty
4274
	make_hashdir_dirty
4275
}
4276

    
4277
# Save the hash-list to run a cleanup afterwards
4278
pbirm_save_hashlist() {
4279
	if [ "${PBI_DISABLEHASHDIR}" = "YES" ] ; then return 0 ; fi
4280
	if [ -e "${PBI_PROGDIRPATH}/${PBI_HASHLIST}" ] ; then
4281
		PBI_TMPHASHLIST="${PBI_TMPDIR}/.pbi-hash.$$"
4282
		cp ${PBI_PROGDIRPATH}/${PBI_HASHLIST} ${PBI_TMPHASHLIST}
4283
	fi
4284
}
4285

    
4286
# Function which removes all empty dirs from the hash-dir
4287
pbi_clean_emptyhdirs() {
4288
        if [ ! -d "${PBI_HASHDIR}" ] ; then return 0 ; fi
4289
	cd ${PBI_HASHDIR}
4290
	found="0"
4291
	for i in `find . -empty -type d 2>/dev/null`
4292
	do
4293
		if [ "${i}" = "." ] ; then continue ; fi
4294
		if [ -d "${PBI_HASHDIR}/${i}" ] ; then
4295
			rmdir "${PBI_HASHDIR}/${i}"
4296
			found="1"
4297
		fi	
4298
	done
4299

    
4300
	# Run recursively
4301
	if [ "$found" = "1" ];then pbi_clean_emptyhdirs ; fi
4302
}
4303

    
4304
# Read through and clean the given hash-list
4305
pbi_clean_hashlist() {
4306
	if [ -z "${PBI_TMPHASHLIST}" ] ; then return 0 ; fi
4307
	while read hl
4308
	do
4309
		file="`echo $hl | sed 's/:::.*$//g'`"
4310
		hash="`echo $hl | sed 's/^.*::://g'`"
4311
		tfile="${file}:::${hash}"
4312
		if [ -f "${PBI_HASHDIR}/${tfile}" ] ; then
4313
			check_remove_hashfile "${tfile}"
4314
		fi
4315

    
4316
	done < ${PBI_TMPHASHLIST}
4317
	rm ${PBI_TMPHASHLIST}
4318
}
4319

    
4320
# Read through and clean the entire hashdir
4321
pbi_clean_hashdir() {
4322
        if [ ! -d "${PBI_HASHDIR}" ] ; then return 0 ; fi
4323
	echo "Cleaning shared-hash dir..."
4324
	cd ${PBI_HASHDIR}
4325
	tmphashlist="${PBI_TMPDIR}/.pbi-hashdir.$$"
4326
	find * -type f -links 1 > "${tmphashlist}" 2>/dev/null
4327
        while read hl
4328
        do
4329
		if [ ! -f "$hl" -o -h "$hl" ] ; then continue ; fi
4330
                if [ -f "${PBI_HASHDIR}/${hl}" ] ; then
4331
                        check_remove_hashfile "${hl}"
4332
                fi
4333

    
4334
        done < $tmphashlist
4335
        rm "$tmphashlist"
4336
	pbi_clean_emptyhdirs
4337
}
4338

    
4339
# Check if this hash-file is ready to be removed from the hash-dir
4340
check_remove_hashfile() {
4341
	tfile="${PBI_HASHDIR}/${1}"
4342
	get_hard_link_count "${tfile}"
4343
	if [ "$HLINKS" = "1" ] ; then
4344
		if [ "${PBI_VERBOSE}" = "YES" ] ; then 
4345
			echo "Removing unused hashfile: $tfile"
4346
		fi
4347
		rm -f "${tfile}"
4348
	fi
4349
}
4350

    
4351
# Run the removal script for this PBI
4352
run_remove_script() {
4353
	uisc="${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/.pbi-uninstall.sh"
4354
	if [ ! -e "$uisc" ] ; then return 0 ; fi
4355

    
4356
	# If not running as root, be sure to cleanup path links
4357
	if [ "`id -u`" != "0" ]; then
4358
	 	cat ${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT} | grep 'rm "$SYS_LOCALBASE/bin' | sed 's|$SYS_LOCALBASE|${HOME}|g' >${PBI_TMPDIR}/.binlnks
4359
         	while read lnk
4360
          	do
4361
               	 	/bin/sh -c "${lnk}"
4362
          	done <${PBI_TMPDIR}/.binlnks
4363
          	rm ${PBI_TMPDIR}/.binlnks
4364
        fi
4365
        export_script_vars
4366
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4367
       		sh "${uisc}"
4368
	else
4369
       		sh "${uisc}" >/dev/null 2>/dev/null
4370
	fi
4371
}
4372

    
4373
# Function to check the supplied $1 dir for any mounts before we
4374
# do a rm -rf
4375
umount_before_rm()
4376
{
4377
   	if [ -z "${1}" ] ; then return 0 ; fi
4378

    
4379
        local _ddir="$1"
4380
        echo "$_ddir" | rev | grep -q '^/'	
4381
	if [ $? -ne 0 ] ; then
4382
	   _ddir="${_ddir}/"
4383
	fi
4384
	
4385
	mount | grep -q "on ${_ddir}"
4386
	if [ $? -ne 0 ] ; then return 0; fi
4387

    
4388
        for i in `mount | grep "on ${_ddir}" | awk '{print $3}'`
4389
	do
4390
	   umount -f ${i} >/dev/null 2>/dev/null
4391
	   if [ $? -ne 0 ] ; then 
4392
		exit_err "Could not umount ${i} before rm -rf, bailing!"
4393
	   fi
4394
	done
4395
	return 0
4396
}
4397

    
4398
# Remove the pbi directory
4399
remove_pbidir() {
4400
	if [ -z "${PBI_PROGDIRPATH}" ] ; then return 0 ; fi
4401
	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then return 0 ; fi
4402
	if [ "${PBI_PROGDIRPATH}" = "/" ] ; then return 0 ; fi
4403
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4404
		echo "Removing: ${PBI_PROGDIRPATH}"
4405
	fi
4406

    
4407
        # Make sure we are unmounted
4408
        umount_before_rm "${PBI_PROGDIRPATH}"
4409
	
4410
	rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4411

    
4412
	# Do we have leftovers?
4413
	if [ -d "${PBI_PROGDIRPATH}" ] ; then
4414
		chflags -R noschg "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4415
		chmod -R 777 "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4416
		rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4417
	fi
4418
}
4419

    
4420
# Remove this PBI registration
4421
unregister_pbi() {
4422
	if [ -z "${PBI_DBAPPDIR}" ] ; then return 0 ; fi
4423
	if [ -z "${PBI_DELETENAME}" ] ; then return 0 ; fi
4424
	if [ ! -d "${PBI_DBAPPDIR}/${PBI_DELETENAME}" ] ; then return 0 ; fi
4425
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4426
		echo "Removing: ${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4427
	fi
4428
	rm -rf "${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4429

    
4430
}
4431

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

    
4436
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4437
		echo "Running pre-removal script: ${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}"
4438
	fi
4439
        export_script_vars
4440
       	sh "${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}"
4441
}
4442

    
4443
add_app_path_links()
4444
{
4445
	# If root, run the regular path script
4446
	if [ `id -u` = "0" ] ; then
4447
		sh "${1}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" >/dev/null 2>/dev/null
4448
		return
4449
	fi
4450

    
4451
	# Running as user add to ~/bin
4452
	init_tmpdir
4453
	if [ ! -d "${HOME}/bin" ] ; then mkdir -p "${HOME}/bin"; fi
4454
	cat ${1}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT} | grep "${1}/${PBI_FAKEBIN_DIR}" | grep '$SYS_LOCALBASE/bin' | sed 's|$SYS_LOCALBASE|${HOME}|g' >${PBI_TMPDIR}/.binlnks
4455
	while read lnk
4456
	do
4457
		/bin/sh -c "${lnk}"
4458
		
4459
	done <${PBI_TMPDIR}/.binlnks
4460
	rm ${PBI_TMPDIR}/.binlnks
4461
	
4462
}
4463

    
4464
del_app_path_links()
4465
{
4466
	# If root, run the regular path script
4467
	if [ `id -u` = "0" ] ; then
4468
		sh "${1}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" >/dev/null 2>/dev/null
4469
		return
4470
	fi
4471

    
4472
	# Running as user remove from ~/bin
4473
	if [ ! -d "${HOME}/bin" ] ; then mkdir -p "${HOME}/bin"; fi
4474
	for lnk in `ls ${1}/${PBI_FAKEBIN_DIR}`
4475
	do
4476
		if [ "$lnk" = "$PBI_INS_PATHSCRIPT" -o "$lnk" = "$PBI_UNINS_PATHSCRIPT" ]
4477
		then
4478
			continue
4479
		fi
4480

    
4481
		if [ ! -e "${HOME}/bin/$lnk" ] ; then continue ; fi
4482
		if [ ! -h "${HOME}/bin/$lnk" ] ; then continue ; fi
4483
			
4484
		ls -al "${HOME}/bin/$lnk" | awk '{print $11}' | grep $1 >/dev/null 2>/dev/null
4485
		if [ "$?" = "0" ] ; then
4486
			rm ${HOME}/bin/$lnk
4487
		fi
4488
	done
4489
	
4490
}
4491

    
4492
pbi_icon_init() {
4493
	parse_icon_pbi_cmdline "$@"
4494
	
4495
	do_pbi_icon
4496
}
4497

    
4498
# Start the PBI icon process
4499
do_pbi_icon() {
4500
	# Get the dir for this PBI
4501
	_appDir=`cat ${PBI_DBAPPDIR}/${PBI_ICONTARGETAPP}/pbi_installedpath`
4502

    
4503
	if [ "${PBI_PATHADD}" = "YES" ] ; then
4504
		add_app_path_links "$_appDir"
4505
	fi
4506
	if [ "${PBI_PATHDEL}" = "YES" ] ; then
4507
		del_app_path_links "$_appDir"
4508
	fi
4509

    
4510
	if [ "${PBI_DESKADD}" = "YES" ] ; then
4511
		if [ ! -e "${_appDir}/.xdg-desktop/${PBI_INS_DESKSCRIPT}" ] ; then 
4512
			exit_err "No desktop icons for this PBI"
4513
		fi
4514
		sh "${_appDir}/.xdg-desktop/${PBI_INS_DESKSCRIPT}"
4515
	fi
4516
	if [ "${PBI_DESKDEL}" = "YES" ] ; then
4517
		if [ ! -e "${_appDir}/.xdg-desktop/${PBI_UNINS_DESKSCRIPT}" ] ; then 
4518
			exit_err "No desktop icons for this PBI"
4519
		fi
4520
		sh "${_appDir}/.xdg-desktop/${PBI_UNINS_DESKSCRIPT}"
4521
	fi
4522
	if [ "${PBI_MENUADD}" = "YES" ] ; then
4523
		require_root_or_group
4524
		if [ ! -e "${_appDir}/.xdg-menu/${PBI_INS_MENUSCRIPT}" ] ; then 
4525
			exit_err "No menu icons for this PBI"
4526
		fi
4527
		sh "${_appDir}/.xdg-menu/${PBI_INS_MENUSCRIPT}"
4528
	fi
4529
	if [ "${PBI_MENUDEL}" = "YES" ] ; then
4530
		require_root_or_group
4531
		if [ ! -e "${_appDir}/.xdg-menu/${PBI_UNINS_MENUSCRIPT}" ] ; then 
4532
			exit_err "No menu icons for this PBI"
4533
		fi
4534
		sh "${_appDir}/.xdg-menu/${PBI_UNINS_MENUSCRIPT}"
4535
	fi
4536
	if [ "${PBI_MIMEADD}" = "YES" ] ; then
4537
		require_root_or_group
4538
		if [ ! -e "${_appDir}/.xdg-mime/${PBI_INS_MIMESCRIPT}" ] ; then 
4539
			exit_err "No mime registration for this PBI"
4540
		fi
4541
		sh "${_appDir}/.xdg-mime/${PBI_INS_MIMESCRIPT}"
4542
	fi
4543
	if [ "${PBI_MIMEDEL}" = "YES" ] ; then
4544
		require_root_or_group
4545
		if [ ! -e "${_appDir}/.xdg-mime/${PBI_UNINS_MIMESCRIPT}" ] ; then 
4546
			exit_err "No mime registration for this PBI"
4547
		fi
4548
		sh "${_appDir}/.xdg-mime/${PBI_UNINS_MIMESCRIPT}"
4549
	fi
4550
}
4551

    
4552
pbid_init() {
4553
	require_root
4554

    
4555
	parse_pbid_cmdline "$@"
4556

    
4557
	do_pbid
4558
}
4559

    
4560
# Start the PBID daemon
4561
do_pbid() {
4562

    
4563
	# Start by sourcing /etc/profile
4564
	# This grabs any HTTP_ / FTP_ PROXY variables
4565
	. /etc/profile
4566

    
4567
	# Allow user supplied logfile
4568
        if [ -z "${PBID_LOGFILE}" ] ; then
4569
	  _pbid_log="/var/log/pbid.log"
4570
	else
4571
          _pbid_log="${PBID_LOGFILE}"
4572
        fi
4573

    
4574
	# Set verbosity 
4575
	_redir="&1"
4576
	if [ "${PBI_VERBOSE}" != "YES" ] ; then _redir="/dev/null" ; fi
4577
	echo "Started pbid: `date`" > ${_pbid_log}
4578

    
4579
	while
4580
	i=1
4581
	do
4582
		# Do regular sleeps
4583
		qslp=0
4584

    
4585
		# Check if we have any out of date index files to update
4586
		for _dbIndex in `ls ${PBI_DBREPODIR}`
4587
		do
4588
			_iMd5=`echo ${_dbIndex} | cut -d '.' -f 2`
4589
			check_update_index "${_iMd5}"
4590

    
4591
			# If we failed to get an index try again sooner
4592
			# This is useful if the user has just installed and has not setup
4593
			# the network yet. We want to fetch indexes quickly after net
4594
			# comes up so they dont need to wait 15 min or whatever its set to
4595
			if [ ! -e "${PBI_DBINDEXDIR}/${_iMd5}-index" ] ; then qslp=1; fi
4596
		done
4597

    
4598
		# Check if we have a dirty hash-dir to cleanup
4599
		check_clean_hashdir "$_pbid_log" "$_redir"
4600

    
4601
		# Check if we have any PBIs to auto-update
4602
		check_autoupdate_pbis "$_pbid_log" "$_redir"
4603

    
4604
		# Check if we need to merge files into the hashdir
4605
		if [ -n "`ls ${PBI_DBHASHQUEUEDIR}`" ] ; then
4606
			init_tmpdir
4607
			for _hpbi in `ls ${PBI_DBHASHQUEUEDIR}`
4608
			do
4609
				if [ ! -e "${PBI_DBAPPDIR}/${_hpbi}/pbi_installedpath" ] ; then
4610
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4611
					continue
4612
				fi
4613

    
4614
				_hpbipath=""
4615
				_hpbipath=`cat ${PBI_DBAPPDIR}/${_hpbi}/pbi_installedpath`
4616
				if [ ! -e "${_hpbipath}/${PBI_HASHLIST}" ] ; then
4617
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4618
					continue
4619
				fi
4620

    
4621
				# Get the username this PBI was installed as
4622
				get_username_from_file "${_hpbipath}"
4623

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

    
4627
				if [ "$FILEUSER" = "root" ];then
4628
					pbi_add_update_hashdir "${_hpbipath}" "${PBI_DBAPPDIR}/${_hpbi}/.pbiDeleted" >${_redir} 2>${_redir}
4629
				else
4630
					# Run hashdir command as a user
4631
					su $FILEUSER -c "pbi_update_hashdir \"${_hpbipath}\" \"${PBI_DBAPPDIR}/${_hpbi}/.pbiDeleted\"" >${_redir} 2>${_redir}
4632
				fi
4633
				echo "Finished adding ${_hpbipath} to hash-dir: `date`" >> ${_pbid_log}
4634
				
4635
				# Now remove the trigger file
4636
				rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4637

    
4638
			done
4639
			rm_tmpdir
4640

    
4641
		fi
4642
		
4643
		# Check if we should rotate the logfile
4644
		_pbidLines=`wc -l ${_pbid_log} | awk '{ print $1 }'`
4645
		if [ $(is_num "$_pbidLines") ] ; then
4646
			if [ $_pbidLines -gt $PBI_LOG_LINES ] ; then
4647
				echo "Logfile turnover: `date`" >${_pbid_log}
4648
			fi
4649
		fi
4650
		
4651

    
4652
		# Done with our check, lets go back to sleep now
4653
		if [ $qslp -eq 1 ] ; then
4654
			sleep 60
4655
		else
4656
			sleep ${PBIDSLEEP}
4657
		fi
4658
	done
4659

    
4660
}
4661

    
4662
# Check if there are any PBIs which are flagged for auto-updates
4663
check_autoupdate_pbis() {
4664

    
4665
	for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
4666
	do
4667
		if [ ! -e "${PBI_DBAPPDIR}/${i}/autoupdate-enable" ] ; then
4668
			continue 
4669
		fi
4670

    
4671
		# Check if this app is already updating
4672
		if [ -e "${PBI_DBAPPDIR}/${i}/.updating" ] ; then
4673
			ps -p `cat ${PBI_DBAPPDIR}/${i}/.updating` >/dev/null 2>/dev/null
4674
			if [ "$?" != "0" ] ; then
4675
				rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
4676
			else
4677
				continue 
4678
			fi
4679
		fi
4680

    
4681
		# Found an auto-update enabled APP, see if it needs upping
4682
		PBI_UPDATEAPP="$i"
4683

    
4684
		# Load the details about this app
4685
		load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4686
		if [ -z "${PBI_REPO}" ]; then
4687
			pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4688
		fi
4689
		if [ -z "${PBI_REPO}" ]; then continue ; fi
4690
		local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
4691

    
4692
		# Does this need an update?
4693
		check_pbi_update "$PBI_UPDATEAPP" "nodisplay" \
4694
			"$PBI_PROGNAME" "current" \
4695
			"$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
4696
		if [ "$?" != "0" ] ; then
4697
			continue
4698
		fi
4699
		
4700
		# Get the username this PBI was installed as
4701
		get_username_from_file "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4702

    
4703
		# Its Update Time!
4704
		echo "Starting Auto-Update of ${PBI_UPDATEAPP} ($FILEUSER): `date`" >>${_pbid_log}
4705

    
4706
		su ${FILEUSER} -c "pbi_update ${PBI_UPDATEAPP}" >>${_pbid_log} 2>>${_pbid_log}
4707
		if [ "$?" = "0" ] ; then
4708
			echo "Success! Update of ${PBI_UPDATEAPP}: `date`" >>${_pbid_log}
4709
		else
4710
			echo "Failed! Update of ${PBI_UPDATEAPP}: `date`" >>${_pbid_log}
4711
		fi
4712

    
4713
		rm "${PBI_DBAPPDIR}/${i}/.updating" >/dev/null 2>/dev/null
4714
	done
4715
}
4716

    
4717
check_clean_hashdir() {
4718
	if [ ! -e "${PBI_DBDIRTYFILE}" ] ; then return ; fi
4719

    
4720
	# Get the date of the last hash-cleaning done
4721
	local _curDate="`cat ${PBI_DBDIRTYFILE}`"
4722
	if [ -e "${PBI_DBDIRTYFILE}.last" ] ; then
4723
		local _lastDate="`cat ${PBI_DBDIRTYFILE}.last`"
4724
	else
4725
		local _lastDate="0"
4726
	fi
4727

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

    
4731
	# Loop through and clean any hash-dirs as the appropriate user
4732
	for cHdir in `ls -d ${PBI_HASHDIR}*`
4733
	do
4734
		get_username_from_file "${cHdir}"
4735
		echo "Cleaning hash-dir ($FILEUSER): `date`" >> ${1}
4736
		su ${FILEUSER} -c "pbi_delete --clean-hdir" >>${2} 2>>${2}
4737
		echo "Finished cleaning hash-dir ($FILEUSER): `date`" >> ${1}
4738
		echo "$_curDate" > ${PBI_DBDIRTYFILE}.last 2>/dev/null
4739
	done
4740
}
4741

    
4742
pbi_info_init() {
4743
	parse_info_pbi_cmdline "$@"
4744
	
4745
	do_pbi_info
4746
}
4747

    
4748
# Display information on the PBI / PBIs
4749
do_pbi_info() {
4750

    
4751
	# If we are listing available PBIs via the index file
4752
	if [ "$PBI_INFOINDEX" = "YES" ] ; then
4753
		
4754
		# List the available PBIs from the index
4755
		do_index_listing
4756
		
4757
		exit_trap
4758
	fi
4759

    
4760
	if [ "$PBI_INFONAME" = "--ALL--" ] ; then
4761
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
4762
		do
4763
			if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
4764
				if [ "$PBI_VERBOSE" = "YES" ] ; then
4765
        				load_info_from_dir "${PBI_DBAPPDIR}/${i}"
4766
					get_username_from_file "${PBI_DBAPPDIR}/${i}"
4767
					PBI_INSTALLED_BY=$FILEUSER
4768
					pbi_display_info
4769
					pbi_display_gui "${PBI_DBAPPDIR}/${i}" ""
4770
					echo " "
4771
				else
4772
					echo "${i}"
4773
				fi
4774
			fi
4775
		done
4776
	else
4777
		# Start loading our variables
4778
        	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_INFONAME}"
4779
		get_username_from_file "${PBI_DBAPPDIR}/${PBI_INFONAME}"
4780
		PBI_INSTALLED_BY=$FILEUSER
4781
		pbi_display_info
4782
	fi
4783
}
4784

    
4785
# Read through the master index file and provide listing of available PBIs for installation
4786
do_index_listing()
4787
{
4788
	# Make sure we have a master index
4789
	ls ${PBI_DBINDEXDIR}/* >/dev/null 2>/dev/null
4790
	if [ "$?" != "0" ] ; then return ; fi
4791

    
4792
	for _rIndex in `ls ${PBI_DBINDEXDIR}/*index* | grep -v '.time'`
4793
	do
4794
		_rMd5=`basename ${_rIndex} | sed 's|-index||g'`
4795
		_rDesc=`cat ${PBI_DBREPODIR}/*.${_rMd5} | grep 'Desc: ' | sed 's|Desc: ||g'`
4796
		echo "Current and available PBIs. * = current"
4797
		echo "Repository: $_rDesc"
4798
		echo "----------------------------------------------------------------"
4799

    
4800
		sort "${_rIndex}" | while read _iLine
4801
		do
4802
			PBI_UPNAME="`echo $_iLine | cut -d ':' -f 1`"
4803
			PBI_UPARCH="`echo $_iLine | cut -d ':' -f 2`"
4804
	        	PBI_UPNVER="`echo $_iLine | cut -d ':' -f 3`"
4805
        		PBI_UPSTATUS="`echo $_iLine | cut -d ':' -f 9`"
4806
			pad_var "${PBI_UPNAME}" "30"
4807
			PBI_UPNAME="${PAD_VAR}"
4808
			pad_var "${PBI_UPNVER}" "15"
4809
			PBI_UPNVER="${PAD_VAR}"
4810
			pad_var "${PBI_UPARCH}" "6"
4811
			PBI_UPARCH="${PAD_VAR}"
4812
	
4813
			if [ "$PBI_UPSTATUS" = "current" ] ; then
4814
				echo "$PBI_UPNAME   $PBI_UPNVER	$PBI_UPARCH *"
4815
			fi
4816
			if [ "$PBI_UPSTATUS" = "active" ] ; then
4817
				echo "$PBI_UPNAME   $PBI_UPNVER	$PBI_UPARCH"
4818
			fi
4819
		done
4820
	done
4821

    
4822
}
4823

    
4824
# Function to pad a variable to X spaces
4825
pad_var() {
4826
	local _pVar="$1"
4827
	local _pNum="$2"
4828
	PAD_VAR="`echo \"$_pVar                                                                                    x\" | cut -c 1-$_pNum`"
4829
}
4830

    
4831
# Checks if we have a custom script to run prior to port make
4832
run_pbi_preportmake()
4833
{
4834
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
4835
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
4836
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-portmake.sh" ] ; then return 0 ; fi
4837

    
4838
	export_script_vars
4839

    
4840
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-portmake.sh"
4841
	if [ "$?" != "0" ] ; then
4842
		exit_err "pre-portmake.sh failed!"
4843
	fi
4844
}
4845

    
4846
# Checks if we have a custom script to run prior to port make
4847
run_pbi_postportmake()
4848
{
4849
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
4850
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
4851
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/post-portmake.sh" ] ; then return 0 ; fi
4852

    
4853
	export_script_vars
4854

    
4855
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/post-portmake.sh"
4856
	if [ "$?" != "0" ] ; then
4857
		echo "Warning: post-portmake.sh returned non-0 status!"
4858
	fi
4859
}
4860

    
4861
# Checks if we have a custom script to run prior to pbi create
4862
run_pbi_prepkgscript()
4863
{
4864
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
4865
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
4866
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-pbicreate.sh" ] ; then return 0 ; fi
4867

    
4868
	export_script_vars
4869

    
4870
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-pbicreate.sh"
4871
	if [ "$?" != "0" ] ; then
4872
		echo "Warning: post-portmake.sh returned non-0 status!"
4873
	fi
4874
}
4875

    
4876
# Begins the port make
4877
start_pbi_makeport()
4878
{
4879
	do_port_build "/usr/ports/${PBI_MAKEPORT}"
4880
}
4881

    
4882
# Prune any ports which aren't required for runtime
4883
start_pbi_prune_ports()
4884
{
4885
	if [ "${PBI_PRUNEBUILDPORTS}" = "NO" ] ; then return ; fi
4886

    
4887
  	local iFile="$PORTSDIR/INDEX-$FBSDMAJOR"
4888

    
4889
	get_pkgname "${PORTSDIR}/${PBI_MAKEPORT}"
4890
	echo "${PKGNAME}" > /.keepports
4891
	grep "^${PKGNAME}|" $iFile | cut -d '|' -f 9 | tr ' ' '\n' >>/.keepports
4892

    
4893
	# Do the same for any OTHERPORTS
4894
	for port in ${PBI_MKPORTBEFORE}
4895
	do
4896
                if [ ! -d "${PORTSDIR}/${port}" ] ; then continue ; fi
4897
		get_pkgname "${PORTSDIR}/${port}"
4898
		echo "${PKGNAME}" >> /.keepports
4899
		grep "^${PKGNAME}|" $iFile | cut -d '|' -f 9 | tr ' ' '\n' >>/.keepports
4900
        done
4901

    
4902
	for port in ${PBI_MKPORTAFTER}
4903
	do
4904
                if [ ! -d "${PORTSDIR}/${port}" ] ; then continue ; fi
4905
		get_pkgname "${PORTSDIR}/${port}"
4906
		echo "${PKGNAME}" >> /.keepports
4907
		grep "^${PKGNAME}|" $iFile | cut -d '|' -f 9 | tr ' ' '\n' >>/.keepports
4908
        done
4909
	
4910
	# Sort and clean the ports
4911
	cat /.keepports | sort | uniq > /.keepports.tmp
4912
	mv /.keepports.tmp /.keepports
4913

    
4914
	# Define some commands
4915
     	if [ $PKGNG -eq 1 ] ; then
4916
		pkgInf="pkg info -f"
4917
     	else
4918
		pkgInf="pkg_info -I -a"
4919
	fi
4920

    
4921
	# Now remove any unused ports
4922
	for j in `$pkgInf | cut -d " " -f 1`
4923
	do
4924
		grep -q "^${j}" "/.keepports"
4925
		if [ $? -ne 0 ] ; then 
4926
			echo "Removing non-required port: ${j}"
4927
			$PKG_DELETE ${j} 
4928
		fi
4929
	done
4930
}
4931

    
4932
# Get the full package-name for a target port
4933
get_pkgname() {
4934
        name="`make -C ${1} -V PKGNAME PORTSDIR=${PORTSDIR}`"
4935
	PKGNAME="${name}"
4936
}
4937

    
4938
# Make any additional required ports 
4939
start_pbi_mkportbefore()
4940
{
4941
	if [ -z "${PBI_MKPORTBEFORE}" ] ; then return ; fi
4942
	
4943
	for port in ${PBI_MKPORTBEFORE}
4944
	do
4945
		if [ ! -d "/usr/ports/${port}" ] ; then
4946
			exit_err "/usr/ports/${port} does not exist!"
4947
		fi
4948
		do_port_build "/usr/ports/${port}"
4949
	done
4950

    
4951
}
4952

    
4953
# Make any additional required ports 
4954
start_pbi_mkportafter()
4955
{
4956
	if [ -z "${PBI_MKPORTAFTER}" ] ; then return ; fi
4957
	
4958
	for port in ${PBI_MKPORTAFTER}
4959
	do
4960
		if [ ! -d "/usr/ports/${port}" ] ; then
4961
			exit_err "/usr/ports/${port} does not exist!"
4962
		fi
4963
		do_port_build "/usr/ports/${port}"
4964
	done
4965

    
4966
}
4967

    
4968
# Start pbi_update_hashdir
4969
pbi_update_hashdir_init() {
4970
	pbi_add_update_hashdir "$1" "$2"
4971
}
4972

    
4973
# Start pbi_update processing
4974
pbi_update_init() {
4975

    
4976
  	parse_update_pbi_cmdline "$@"
4977

    
4978
	check_enable_disable_auto
4979

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

    
4983
	start_update_checks
4984
	if [ "$?" != "0" ] ; then rm_tmpdir ; exit 1 ; fi
4985

    
4986
	# Stop here if only doing update checks
4987
	if [ -n "${PBI_UPCHECK}" ]; then return 0 ; fi
4988

    
4989
  	require_root_or_group
4990

    
4991
	do_pbi_update
4992
}
4993

    
4994
# Check if we are enabling / disabling auto-updating
4995
check_enable_disable_auto()
4996
{
4997
	if [ -z "$PBI_UPENABLEAUTO" ] ; then return ; fi
4998
	if [ ! -d "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}" ] ; then return ; fi
4999

    
5000
	# Enable / disable auto-updating now
5001
	if [ "$PBI_UPENABLEAUTO" = "YES" ]; then
5002
		touch ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable
5003
	else
5004
		rm ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable >/dev/null 2>/dev/null
5005
	fi
5006
}
5007

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

    
5012
        # See which repo / key this PBI associates to, if any
5013
	check_valid_sigs "${1}"
5014
	if [ "$?" = "0" -a -n "$PBI_VALIDKEYSIG" ] ; then
5015
		_rMd5="`echo ${PBI_VALIDKEYSIG} | cut -d '.' -f 1`"
5016
		echo "$_rMd5" | sed "s|${PBI_DBKEYDIR}/||g" > ${1}/pbi_repo
5017
	fi
5018
}
5019

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

    
5024
	# Open up the tmpdir
5025
	init_tmpdir
5026

    
5027
	if [ "${PBI_UPCHECK}" = "YES" ] ; then
5028
		load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5029
		if [ -z "${PBI_REPO}" ]; then
5030
			pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5031
		fi
5032
		if [ -z "${PBI_REPO}" ]; then
5033
			return 1
5034
		else
5035
			local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5036
		fi
5037

    
5038
		check_pbi_update "$PBI_UPDATEAPP" "display" \
5039
	 	 "$PBI_PROGNAME" "current" \
5040
	 	 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5041
		return $?
5042
	else
5043
		# Loop and check all PBIs for updates
5044
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
5045
                do
5046
			PBI_REPO=""
5047
                        if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
5048
				load_info_from_dir "${PBI_DBAPPDIR}/${i}"
5049
				if [ -z "${PBI_REPO}" ]; then
5050
					pbi_checksig_repomatch "${PBI_DBAPPDIR}/${i}"
5051
				fi
5052
				if [ -z "${PBI_REPO}" ]; then
5053
					continue
5054
				else
5055
					local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5056
				fi
5057

    
5058
				check_pbi_update "$i" "display" \
5059
				 "$PBI_PROGNAME" "current" \
5060
				 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5061
                        fi
5062
                done
5063
		return 0
5064
	fi
5065

    
5066
}
5067

    
5068
# Check if we need to pull down the updated INDEX file
5069
check_update_index() {
5070

    
5071
	init_tmpdir
5072
	
5073
	local _repoMd5="$1"
5074
	local _rURL=`cat ${PBI_DBREPODIR}/*${_repoMd5} | grep URL: | sed 's|URL: ||g'`
5075

    
5076
	_pbiIndex="${PBI_DBINDEXDIR}/${_repoMd5}-index"
5077
	_pbiMeta="${PBI_DBINDEXDIR}/${_repoMd5}-meta"
5078
	_pbiIndexTime="${_pbiIndex}.time"
5079
	_tmpPbiIndex="${PBI_TMPDIR}/.upcheck$$"
5080
	_tmpPbiMeta="${PBI_TMPDIR}/.upcheck$$"
5081
		
5082
	# Check if its been greater than $PBI_INDEXREFRESH hours since the last update
5083
	if [ -e "${_pbiIndexTime}" ] ; then
5084
		_curTime=`date +%s`
5085
		_oTime=`cat ${_pbiIndexTime}`
5086
		_trigTime=`expr ${PBI_INDEXREFRESH} \* 60 \* 60`
5087
		expr $_curTime - $_oTime >/dev/null 2>/dev/null
5088
		if [ "$?" = "0" ] ; then
5089
			_passed=`expr $_curTime - $_oTime`
5090
			if [ "$_passed" -lt "$_trigTime" ] ; then
5091
				return;
5092
			fi
5093
		fi
5094
		
5095
	fi
5096

    
5097
	if [ "${PBI_VERBOSE}" = "YES" ] ; then
5098
		echo "Updating index ${_pbiIndex}"
5099
		echo "Updating index ${_pbiIndex}: `date`" >> ${_pbid_log}
5100
	fi
5101

    
5102
	# Check that the last char isn't a '/'
5103
	_tmp=`echo ${_rURL} | wc -m | tr -s ' ' | tr -d ' '`
5104
	_tmp2=`expr $_tmp - 1`
5105
	_lastC=`echo ${_tmp} | cut -c ${_tmp2}-${_tmp}`
5106
	if [ "${_lastC}" = "/" ] ; then
5107
		_upURL="`echo ${_rURL} | sed 's|\(.*\).|\1|'`"
5108
	else
5109
		_upURL="${_rURL}"
5110
	fi
5111

    
5112
	fetch -o "${_tmpPbiIndex}.bz2" "${_upURL}/${PBI_INDEXUPFILE}.bz2" >/dev/null 2>/dev/null
5113
	if [ "$?" != "0" ] ; then
5114
		return
5115
	fi
5116

    
5117
	bzip2 -d "${_tmpPbiIndex}.bz2" >/dev/null 2>/dev/null
5118
	if [ "$?" != "0" ] ; then
5119
		return
5120
	fi
5121

    
5122
	# Move the uncompressed file
5123
	mv "${_tmpPbiIndex}" "${_pbiIndex}" >/dev/null 2>/dev/null
5124

    
5125
	# Wait a sec
5126
 	sleep 1
5127

    
5128
	# Now check for an optional meta file update
5129
	fetch -o "${_tmpPbiMeta}.bz2" "${_upURL}/${PBI_METAUPFILE}.bz2" >/dev/null 2>/dev/null
5130
	if [ "$?" = "0" ] ; then
5131
		bzip2 -d "${_tmpPbiMeta}.bz2" >/dev/null 2>/dev/null
5132
		if [ "$?" = "0" ] ; then
5133
			mv "${_tmpPbiMeta}" "${_pbiMeta}" >/dev/null 2>/dev/null
5134
		fi
5135
	fi
5136

    
5137
	# Update the icons for this repos meta file
5138
	update_repo_icons "${_repoMd5}" "${_pbiMeta}"
5139

    
5140
	echo "Finished updating index ${_pbiIndex}: `date`" >> ${_pbid_log}
5141
	if [ "${PBI_VERBOSE}" = "YES" ] ; then
5142
		echo "Finished updating index ${_pbiIndex}"
5143
	fi
5144

    
5145
	# Save the time that we are done
5146
	date +%s > ${_pbiIndexTime}
5147

    
5148
}
5149

    
5150
# Check if we need to update any repository icons
5151
update_repo_icons() {
5152
	_repoMd5="$1"
5153
	_repoMeta="$2"
5154

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

    
5157
	# Loop through, downloading icons we find
5158
	while read mLine
5159
	do
5160
		# Make sure this is an app / cat
5161
		echo "$mLine" | grep -e "^App=" -e "^Cat=" >/dev/null 2>/dev/null
5162
		if [ "$?" != "0" ] ; then continue ; fi
5163

    
5164
		# Get the icon URL
5165
		echo "$mLine" | grep "^App=" >/dev/null 2>/dev/null
5166
		if [ "$?" = "0" ] ; then
5167
			line=`echo $mLine | sed 's|^App=||g'`
5168
			aIcon=`echo $line | cut -d ';' -f 3`
5169
		else
5170
			line=`echo $mLine | sed 's|^Cat=||g'`
5171
			aIcon=`echo $line | cut -d ';' -f 2`
5172
		fi
5173
		iName=`echo $line | cut -d ';' -f 1`
5174
		ext=`echo $aIcon | sed 's/.*\.//'`
5175
	
5176
		# If we already have this icon, we can skip
5177
		if [ -e "${PBI_DBICONDIR}/${_repoMd5}-${iName}.${ext}" ] ; then
5178
			continue
5179
		fi
5180

    
5181
		# Now fetch the file
5182
		sFile="${PBI_DBICONDIR}/${_repoMd5}-${iName}.${ext}"
5183
		fetch -o "${sFile}" "${aIcon}" >/dev/null 2>/dev/null
5184
		if [ $? -ne 0 ]; then
5185
		  # Wait a moment before trying the next
5186
		  sleep 40 
5187
		fi
5188
		
5189
	done < ${_repoMeta}
5190
}
5191

    
5192
# Check a specific PBI for updates
5193
check_pbi_update() {
5194

    
5195
	# Init the tmpdir
5196
	init_tmpdir
5197

    
5198
	# Set the vars
5199
	_upbi="${1}"
5200
	_udisp="${2}"
5201
	_uprog="${3}"
5202
	_uver="${4}"
5203
	_ufbsdver="${5}"
5204
	_uarch="${6}"
5205
	_urepo="${7}"
5206
	_omdate="${8}"
5207

    
5208
	appname="`echo ${_uprog} | tr '[:lower:]' '[:upper:]'`"
5209

    
5210
	PBI_UPNVER=""
5211
	PBI_UPFILE=""
5212
	PBI_UPPATCHES=""
5213
	PBI_UPCSUM=""
5214
	PBI_UPMDATE=""
5215
	PBI_UPREPO=""
5216
	PBI_UPSIZE=""
5217

    
5218
	# If we are looking for the current app, set _uver accordingly
5219
	if [ "$_uver" = "current" ] ; then
5220
		_uver=":current"
5221
	else
5222
		_uver=":${_uver}:"
5223
	fi
5224

    
5225

    
5226
	for _repo in `ls ${PBI_DBINDEXDIR}`
5227
	do
5228

    
5229
		if [ "$_urepo" = "AUTO" ] ; then
5230
			_pbiIndex="${PBI_DBINDEXDIR}/${_repo}"
5231
			_rMd5="`echo ${_repo} | sed 's|-index||g'`"
5232
		else
5233
			_rMd5=`ls ${PBI_DBREPODIR}/${_urepo}.* | cut -d '.' -f 2`
5234
			_pbiIndex="${PBI_DBINDEXDIR}/${_rMd5}-index"
5235
		fi
5236

    
5237
		if [ ! -e "${_pbiIndex}" ] ; then continue ; fi
5238

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

    
5242
		PBI_UPNVER="`echo $_upLine | cut -d ':' -f 3`"
5243
		PBI_UPFILE="`echo $_upLine | cut -d ':' -f 6`"
5244
		PBI_UPPATCHES="`echo $_upLine | cut -d ':' -f 8`"
5245
		PBI_UPCSUM="`echo $_upLine | cut -d ':' -f 4`"
5246
		PBI_UPMDATE="`echo $_upLine | cut -d ':' -f 5`"
5247
		PBI_UPSIZE="`echo $_upLine | cut -d ':' -f 8`"
5248
		PBI_UPMIRROR="`cat ${PBI_DBMIRRORDIR}/${_rMd5} 2>/dev/null`"
5249
		PBI_UPREPO="${_rMd5}"
5250

    
5251
		if [ -n "${PBI_UPNVER}" ] ; then break; fi
5252
		if [ "${_urepo}" != "AUTO" ] ; then break; fi
5253

    
5254
	done
5255

    
5256
	# If no new version
5257
	if [ -z "$PBI_UPNVER" ] ; then return 1 ; fi
5258

    
5259
	# See if this update is newer than the installed date
5260
	if [ -n "$_omdate" ] ; then
5261
		nDay=`echo $PBI_UPMDATE | cut -d ' ' -f 1`
5262
		nHour=`echo $PBI_UPMDATE | cut -d ' ' -f 2`
5263
		oDay=`echo $_omdate | cut -d ' ' -f 1`
5264
		oHour=`echo $_omdate | cut -d ' ' -f 2`
5265

    
5266
		# Make sure we have all legit numbers
5267
		if [ $(is_num "$nDay") -a $(is_num "$nHour") \
5268
			-a $(is_num "$oDay") -a $(is_num "$oHour") ] ; then
5269
			if [ $oDay -gt $nDay ] ; then return 1 ; fi
5270
			if [ "$oDay" = "$nDay" -a $oHour -gt $nHour ] ; then return 1 ; fi
5271
		fi
5272
	fi
5273

    
5274
	if [ "$PBI_UPNVER" != "$PBI_PROGVERSION" ] ; then
5275
		if [ "$_udisp" = "display" ] ; then 
5276
			echo "${_upbi} - Available: ${PBI_UPNVER}"
5277
		fi
5278
		return 0
5279
	else
5280
		return 1
5281
	fi
5282
}
5283

    
5284
# Start PBI update process
5285
do_pbi_update() {
5286
	if [ -n "${PBI_UPCHECK}" ]; then return 0 ; fi
5287

    
5288
	if [ "$PBI_UPDATEAPP" = "ALL" ] ; then
5289
		# Loop and check all PBIs for updates
5290
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
5291
                do
5292
			if [ -e "${PBI_DBAPPDIR}/${i}/.updating" ] ; then
5293
				ps -p `cat ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating` >/dev/null 2>/dev/null
5294
				if [ "$?" = "0" ] ; then
5295
					continue
5296
				fi
5297
				rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5298
			fi
5299
                        if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
5300
				PBI_UPDATEAPP="${i}"
5301
				start_pbi_updateapp "all"
5302
                        fi
5303
		done
5304
	else
5305
		if [ -e "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" ] ; then
5306
			ps -p `cat ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating` >/dev/null 2>/dev/null
5307
			if [ "$?" = "0" ] ; then
5308
				exit_err "This application is currently updating."
5309
			fi
5310
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5311
		fi
5312
		start_pbi_updateapp "single"
5313
	fi
5314
}
5315

    
5316
# Attempt to download a PBI from the update server for "pbi_add -r"
5317
pbi_add_fetch_remote() {
5318
	# Set the target program we want to download
5319
	_rtar="$PBI_FILENAME"
5320
	unset PBI_FILENAME
5321

    
5322
	# Check if the user overrode the arch / versions we want to install
5323
	_rArch=`uname -m`
5324
	if [ -n "$PBI_ADD_ALTARCH" ] ; then _rArch=$PBI_ADD_ALTARCH ; fi
5325

    
5326
	_rVer="current"
5327
	if [ -n "$PBI_ADD_ALTVER" ] ; then _rVer=$PBI_ADD_ALTVER ; fi
5328

    
5329

    
5330
	check_pbi_update "$_rtar" "nodisplay" \
5331
	 "$_rtar" "$_rVer" \
5332
	 "$FBSDMAJOR" "$_rArch" "${PBI_ADDREPO_ID}"
5333
	if [ "$?" != "0" ] ; then 
5334
		exit_err "Could not find \"$_rtar\" in any indexes" 
5335
	fi
5336

    
5337
	# We've gotten this far, now download the updated PBI
5338
	pbi_update_dl
5339
	if [ "$?" != "0" ] ; then
5340
		exit_err "Failed downloading PBI"
5341
	fi
5342

    
5343
	# Now overwrite the PBI_FILENAME and let us proceed to regular install
5344
	PBI_FILENAME="$PBI_UPDLFILE"
5345

    
5346
	# If we are only fetching, finish up now
5347
	if [ "$PBI_REMOTEFETCHONLY" = "YES" ] ; then
5348
		mv $PBI_FILENAME ./`basename ${PBI_UPFILE}`
5349
		echo "PBI saved to ./`basename ${PBI_UPFILE}`"
5350
		exit_trap
5351
	fi
5352

    
5353
}
5354

    
5355
# Update the targed PBI
5356
start_pbi_updateapp() {
5357
	_upact="${1}"
5358
	if [ "$2" = "pbid" ] ; then 
5359
		_pbidlog="$2"
5360
	else
5361
		_pbidlog=""
5362
	fi
5363

    
5364
	echo "$$" > "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5365

    
5366
	# Check for update to this app, and exit or return if not available
5367
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5368
	if [ -z "${PBI_REPO}" ]; then
5369
		pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5370
	fi
5371
	if [ -z "${PBI_REPO}" ]; then
5372
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5373
		return
5374
	else
5375
		local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5376
	fi
5377

    
5378
	check_pbi_update "$PBI_UPDATEAPP" "nodisplay" \
5379
	 "$PBI_PROGNAME" "current" \
5380
	 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5381
	if [ "$?" != "0" ] ; then 
5382
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5383
		if [ "$_upact" = "single" ] ; then
5384
			exit_err "$PBI_UPDATEAPP - no update available!"
5385
		else
5386
			return 1
5387
		fi
5388
	fi
5389
	
5390
	
5391
	echo "Starting update of ${PBI_UPDATEAPP} to ${PBI_UPNVER}..."
5392
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
5393

    
5394
	# Check if there is a possible patch file for this update
5395
	# new filename to download
5396
	_pFile="${_pbilow}-${PBI_PROGVERSION}_to_${PBI_UPNVER}-${PBI_APPARCH}.pbp"
5397

    
5398
	# Try downloading the patch file
5399
	echo "Trying update via patchfile..."
5400
	pbi_update_dl "$_pFile" "OFF"
5401
	if [ "$?" = "0" ] ; then
5402
		# We had a good patch download, try applying it now
5403
		echo "Updating via patch file..."
5404
		pbi_patch "$PBI_UPDLFILE" #>/dev/null 2>/dev/null
5405
		if [ "$?" != "0" ] ; then
5406
			# Patching failed, we'll grab a fresh copy next
5407
			echo "Failed to patch with ${PBI_UPDLFILE}"
5408
			echo "Will try full file update"
5409
		else
5410
			echo "Patch successful!"
5411
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" >/dev/null 2>/dev/null
5412
			rm "${PBI_UPDLFILE}" >/dev/null 2>/dev/null
5413
			return 0
5414
		fi
5415
			
5416
	fi
5417

    
5418
	# No patch file, grab the full app
5419
	echo "Trying update via full-file..."
5420
	pbi_update_dl 
5421
	if [ "$?" != "0" ] ; then
5422
		if [ "$_upact" = "single" ] ; then
5423
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5424
			exit_err "Failed downloading update!"
5425
		fi
5426
	fi
5427

    
5428
	echo " "
5429

    
5430
	# Save the auto-update status
5431
	if [ -e "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable" ] ; then
5432
		_autoUpEnable="YES"
5433
	else
5434
		_autoUpEnable="NO"
5435
	fi
5436
	
5437
	echo -e "Removing old version...\c"
5438
	pbi_delete "${PBI_UPDATEAPP}"
5439
	echo "Done"
5440

    
5441
	# Now install new PBI
5442
	echo -e "Installing new version...\c"
5443
	pbi_add --licagree -f "$PBI_UPDLFILE" >/dev/null 2>/dev/null
5444
	if [ "$?" != "0" ] ; then
5445
		echo "Failed to install PBI: ${PBI_UPDLFILE}"
5446
		rm "${PBI_UPDLFILE}"
5447
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" 2>/dev/null
5448
		return 1
5449
	else
5450
		if [ "$_autoUpEnable" = "YES" ] ; then
5451
		 	touch "${PBI_DBAPPDIR}/${_pbilow}-${PBI_UPNVER}-${PBI_APPARCH}/autoupdate-enable"
5452
		fi
5453
		echo "Done"
5454
		rm "${PBI_UPDLFILE}"
5455
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" 2>/dev/null
5456
		return 0
5457
	fi	
5458
}
5459

    
5460
# Start downloading the update
5461
pbi_update_dl() {
5462

    
5463
	_tPatch=$1
5464
	local _CKSUM="$2"
5465
	
5466
	# Set local download location
5467
	_dl_loc="${PBI_APPDIR}/.`basename $PBI_UPFILE`"
5468

    
5469
	# Have a patch file to download instead, make that the active file to try
5470
	if [ -n "$_tPatch" ] ; then
5471
		_bDir=`dirname $PBI_UPFILE`
5472
		_uFile="${_bDir}/${_tPatch}"
5473
	else
5474
		_uFile="${PBI_UPFILE}"
5475
	fi
5476

    
5477
	_mirrorList=`echo $PBI_UPMIRROR | sed 's|\n| |g'`
5478

    
5479
	# Start download from repos mirror(s) in order
5480
	for _cMirror in $_mirrorList
5481
	do
5482
		if [ "$_cMirror" = "PCBSDCDN" ] ; then
5483
			get_pcbsd_mirror
5484
			_furl="${VAL}${_uFile}"
5485
		else
5486
			_furl="`echo $_cMirror | sed 's/\/*$//'`${_uFile}"
5487
		fi
5488

    
5489
		echo "Downloading ${_furl}"
5490
		pbi_get_file "$_furl" "$_dl_loc"
5491
		if [ "$?" != "0" ]  ; then 
5492
			rm "${_dl_loc}" >/dev/null 2>/dev/null
5493
			echo "Download Failed: ${_furl}"
5494
			continue
5495
		fi
5496
		_upcsum=`sha256 -q "$_dl_loc"`
5497
		if [ "$_CKSUM" != "OFF" -a "$_upcsum" != "$PBI_UPCSUM" ] ; then
5498
			rm "${_dl_loc}" >/dev/null 2>/dev/null
5499
			echo "Download fails checksum: ${_furl}"
5500
			continue
5501
		fi
5502

    
5503
		# If we get this far, we have a good file!
5504
		PBI_UPDLFILE="$_dl_loc"
5505
		sync
5506
		return 0
5507
	done
5508

    
5509
	return 1
5510
}
5511

    
5512
# Function to download a file from remote using fetch
5513
pbi_get_file() {
5514
	_rf="${1}"
5515
	_lf="${2}"
5516

    
5517
	init_tmpdir
5518
	if [ -e "${_lf}" ] ; then 
5519
		echo "Resuming download of: ${_lf}"
5520
	fi
5521

    
5522
	if [ "$PBI_FETCH_PARSING" != "YES" ] ; then
5523
		fetch -r -o "${_lf}" "${_rf}"
5524
		_err=$?
5525
	else
5526
		# Doing a front-end download, parse the output of fetch
5527
		_eFile="${PBI_TMPDIR}/.fetch-exit.$$"
5528
		fetch -s "${_rf}" > ${PBI_TMPDIR}/.fetch-size.$$ 2>/dev/null
5529
		_fSize=`cat ${PBI_TMPDIR}/.fetch-size.$$ 2>/dev/null`
5530
		_fSize="`expr ${_fSize} / 1024 2>/dev/null`"
5531
		rm "${PBI_TMPDIR}/.fetch-size.$$" 2>/dev/null
5532
		_time=1
5533

    
5534
		( fetch -r -o "${_lf}" "${_rf}" >/dev/null 2>/dev/null ; echo "$?" > ${_eFile} ) &
5535
		FETCH_PID=`ps -auwwwx | grep -v grep | grep "fetch -r -o ${_lf}" | awk '{print $2}'`
5536
		while : 
5537
		do
5538
			if [ -e "${_lf}" ] ; then
5539
				_dSize=`du -k ${_lf} | tr -d '\t' | cut -d '/' -f 1`
5540
				if [ $(is_num "$_dSize") ] ; then
5541
					if [ ${_fSize} -lt ${_dSize} ] ; then _dSize="$_fSize" ; fi
5542
					_kbs=`expr ${_dSize} \/ $_time`
5543
					echo "SIZE: ${_fSize} DOWNLOADED: ${_dSize} SPEED: ${_kbs} KB/s"
5544
				fi
5545
			fi
5546

    
5547
			# Make sure download isn't finished
5548
			ps -p $FETCH_PID >/dev/null 2>/dev/null
5549
			if [ "$?" != "0" ] ; then break ; fi
5550
			sleep 2
5551
			_time=`expr $_time + 2`
5552
		done
5553

    
5554
		_err="`cat ${_eFile}`"
5555
		if [ "$_err" = "0" ]; then echo "FETCHDONE" ; fi
5556
		unset FETCH_PID
5557
	fi
5558

    
5559
	echo ""
5560
	return $_err
5561
}
5562

    
5563
is_num()
5564
{
5565
	expr $1 + 1 2>/dev/null
5566
	return $?
5567
}
5568

    
5569
# Function to check if the port is flagged to only build on specific arch
5570
# Returns 0 for OK, 1 for invalid arch
5571
check_port_compat_arch()
5572
{
5573
	local sPort=$1
5574
 	local cValues="`make -C $sPort -V ONLY_FOR_ARCHS PORTSDIR=${PORTSDIR}`"
5575
	if [ -z "$cValues" ] ; then return 0 ; fi
5576

    
5577
	for cArch in $cValues
5578
	do
5579
		if [ "$cArch" = "$ARCH" ] ; then return 0; fi
5580
	done
5581
	
5582
	return 1
5583
}
5584

    
5585
# start processing autobuild
5586
pbi_autob_init() {
5587

    
5588
        require_root
5589

    
5590
        parse_autob_pbi_cmdline "$@"
5591

    
5592
        do_pbi_autob
5593
}
5594

    
5595
check_zfs_ab_destroy()
5596
{
5597
	local bNum=$1
5598
 	if [ -e "${PBI_TMPDIR}/${bNum}.zmnt" ] ; then
5599
 		zDir=`cat ${PBI_TMPDIR}/${bNum}.zmnt`
5600
  		# Make sure this zfs dataset is in the PBI_APPDIR directory
5601
 		echo $zDir | grep -q "${PBI_APPDIR}/" 
5602
	    	if [ $? -eq 0 ] ; then
5603
		  # Make sure all is unmounted
5604
		  umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
5605
		  umount -f ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
5606
	  	  umount -f ${PBI_CHROOTDIR}/usr/ports >/dev/null 2>/dev/null
5607
	 	  umount -f ${PBI_CHROOTDIR}/pkgs >/dev/null 2>/dev/null
5608
		  umount -f ${PBI_CHROOTDIR}/.ccache >/dev/null 2>/dev/null
5609
		  umount -f ${PBI_CHROOTDIR}/usr/wrkdirprefix >/dev/null 2>/dev/null
5610
		  sleep 3
5611
		  umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
5612
		  sync
5613
		  sleep 3
5614
             	  zfs destroy ${zDir}
5615
       	 	  rmdir ${zDir} >/dev/null 2>/dev/null
5616
		fi
5617
  	fi
5618
}
5619

    
5620
ab_clean_build_tmpfiles()
5621
{
5622
	local build=$1
5623

    
5624
	# Cleanup 
5625
	rm ${PBI_TMPDIR}/${build}.result 2>/dev/null
5626
	rm ${PBI_TMPDIR}/${build}.pid 2>/dev/null
5627
	rm ${PBI_TMPDIR}/${build}.bPort 2>/dev/null
5628
	rm ${PBI_TMPDIR}/${build}.od 2>/dev/null
5629
	rm ${PBI_TMPDIR}/${build}.mp 2>/dev/null
5630
	rm ${PBI_TMPDIR}/${build}.cd 2>/dev/null
5631
	rm ${PBI_TMPDIR}/${build}.pv 2>/dev/null
5632
	rm ${PBI_TMPDIR}/${build}.zmnt 2>/dev/null
5633
}
5634

    
5635
# Start the auto-build traversal process
5636
do_pbi_autob() {
5637

    
5638
	echo "`basename ${0}` started: `date`"
5639

    
5640
	# Prune any outdir files which we don't have modules for
5641
	do_pbi_autob_prune
5642

    
5643
	cd "${PBI_AB_CONFDIR}"
5644
	init_tmpdir
5645

    
5646
	# Get this runs timestamp
5647
	PBI_AB_TIMESTAMP=`date | md5`
5648

    
5649

    
5650
	# Build our list of targets first
5651
	echo "=> Creating build queue list..."
5652
	ab_get_build_list
5653

    
5654
	done=0
5655
	rebuildlist=0
5656
	while :; do
5657
	  activity=0
5658
	  # Start checking each job
5659
	  for build in ${JOBS-$(jot -w %02d ${PBI_AB_BUILDERS})}; do
5660
		# Is this builder running?
5661
		if [ -e "${PBI_TMPDIR}/${build}.pid" ] ; then
5662
			if pgrep -qF "${PBI_TMPDIR}/${build}.pid" >/dev/null 2>&1; then 
5663
				activity=1
5664
				continue; 
5665
			else
5666
		 		# Do the ZFS destroy here if necessary
5667
				check_zfs_ab_destroy "$build"
5668
				
5669
				# Run the post-build process
5670
				ab_post_build ${build}
5671

    
5672
				# Cleanup
5673
				ab_clean_build_tmpfiles ${build}
5674
			fi
5675
		fi
5676
		if [ $done -eq 1 ] ; then continue ; fi
5677

    
5678
		# Builder idle, lets figure out the next build
5679
  		echo "==> Finding target for build process [$build]"
5680
		start_next_ab_target "$build"
5681
		if [ $? -eq 0 ] ; then 
5682
			# Nothing left to build, lets wait for any existing build to finish before exiting
5683
			done=1
5684
		fi
5685
		activity=1
5686
          done
5687

    
5688
	  # Every 2 hours, we can re-scan the modules directory, catch any ones which may have been added / changed
5689
	  if [ $rebuildlist -eq 7200 ] ; then
5690
	     rebuildlist=0
5691
	     ab_get_build_list
5692
	  else
5693
	     rebuildlist=`expr $rebuildlist + 1`
5694
          fi
5695

    
5696
	  # Wait before checking again
5697
          [ $activity -eq 1 ] && sleep 1
5698
	  # Nothing to do? We can end now
5699
          [ $activity -eq 0 ] && break
5700
	done 
5701

    
5702
	echo "`basename ${0}` Finished: `date`"
5703
};
5704

    
5705
ab_get_build_list()
5706
{
5707

    
5708
   AB_FOUND="0"
5709
   unset CUR_PRIORITY_PBI CUR_WORKING_PBI
5710

    
5711
   # Clear the tmp build list
5712
   rm ${PBI_TMPDIR}/.ablist 2>/dev/null
5713
		
5714
   cd "${PBI_AB_CONFDIR}"
5715
   for pbi in `find . -type f -name "${PBI_CONFFILE}" | grep -v '\.svn' | sort`
5716
   do
5717
	# Figure out the target port for this build
5718
	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
5719
	. ${pbi}
5720

    
5721
	_cd=$(dirname $pbi | sed 's|./||')
5722
	PBI_CONFDIR="$_cd"
5723

    
5724
	# Make sure PBI_MAKEPORT is set
5725
	if [ -z "${PBI_MAKEPORT}" ] ; then
5726
		PBI_MAKEPORT=`echo $pbi | sed 's|./||'`
5727
		export PBI_MAKEPORT
5728
	fi	
5729

    
5730
	if [ ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ] ; then 
5731
		#echo "Skipping invalid port ${PORTSDIR}/${PBI_MAKEPORT}"
5732
		continue
5733
	fi
5734
	
5735
	# Check if this port can be built on this architecture
5736
	check_port_compat_arch "${PORTSDIR}/${PBI_MAKEPORT}"
5737
	if [ "$?" = "1" ] ; then
5738
		#echo "${PBI_MAKEPORT} - Skipping for invalid system arch"
5739
		continue
5740
	fi
5741
	
5742
	# Check for missing port target
5743
	if [ -z "$PBI_MAKEPORT" ] ; then
5744
		#echo "Warning: Missing PBI_MAKEPORT for ${pbi}"
5745
		continue
5746
	fi
5747

    
5748
	# Check if another builder is already doing this port
5749
	pBuilding=0
5750
	for p in `ls ${PBI_TMPDIR}/*.bPort 2>/dev/null`
5751
	do
5752
		if [ "`cat $p`" = "$PBI_MAKEPORT" ] ; then
5753
			pBuilding=1
5754
			break
5755
		fi
5756
	done
5757
	if [ $pBuilding -eq 1 ] ; then
5758
		continue
5759
	fi
5760

    
5761
	check_ab_needed "$PBI_MAKEPORT" "${PBI_BUILDKEY}" "$_cd" "$PBI_AB_TIMESTAMP"
5762
 	if [ "$?" = "0" ] ; then	
5763
	   AB_FOUND="1"
5764

    
5765
 	           # Unset the priority if set to 00 / 0
5766
           if [ "${PBI_AB_PRIORITY}" = "00" -o "${PBI_AB_PRIORITY}" = "0" ] ; then 
5767
	   	unset PBI_AB_PRIORITY
5768
           fi
5769

    
5770
	   # Check the priority of this PBI, see if it rises to the top
5771
	   if [ -z "${CUR_PRIORITY_PBI}" ] ; then 
5772
	     CUR_WORKING_PBI="${pbi}"
5773
	     if [ -z "$PBI_AB_PRIORITY" ] ; then 
5774
                     CUR_PRIORITY_PBI="$internal_ab_priority"
5775
             else
5776
                     CUR_PRIORITY_PBI=`expr $PBI_AB_PRIORITY + 10`
5777
             fi
5778
	     #echo "Setting higher priority target: ${pbi} - Priority: ${CUR_PRIORITY_PBI}"
5779
   	     echo "${CUR_PRIORITY_PBI} $pbi" >> ${PBI_TMPDIR}/.abtmp
5780
             continue
5781
           fi
5782

    
5783
	   # Bump up the supplied AB priority
5784
	   if [ -n "${PBI_AB_PRIORITY}" ] ; then 
5785
              internal_ab_priority=`expr $PBI_AB_PRIORITY + 10`
5786
	   fi
5787

    
5788
	   # Check if this PBI is a higher priority
5789
	   if [ $CUR_PRIORITY_PBI -lt $internal_ab_priority ] ; then
5790
	     #echo "Setting higher priority target: ${pbi} - Priority: ${internal_ab_priority}"
5791
	     CUR_WORKING_PBI="${pbi}"
5792
             CUR_PRIORITY_PBI="$internal_ab_priority"
5793
   	     echo "${internal_ab_priority} $pbi" >> ${PBI_TMPDIR}/.abtmp
5794
	     continue
5795
	   else 
5796
	     echo "${internal_ab_priority} $pbi" >> ${PBI_TMPDIR}/.abtmp
5797
	   fi
5798
	   continue
5799
  	 fi
5800

    
5801
  done
5802

    
5803
  # Sort the list
5804
  sort -n -r ${PBI_TMPDIR}/.abtmp > ${PBI_TMPDIR}/.ablist
5805
  rm ${PBI_TMPDIR}/.abtmp
5806
}
5807

    
5808
start_next_ab_target()
5809
{
5810
  local curBuilder="$1"
5811
  # No list to parse?
5812
  if [ ! -e "${PBI_TMPDIR}/.ablist" ] ; then return 0; fi
5813

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

    
5818
  cd "${PBI_AB_CONFDIR}"
5819

    
5820
  # We have something to build lets do it!
5821
  pbi="$CUR_WORKING_PBI"
5822
  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
5823
  . ${pbi}
5824

    
5825
  _cd=$(dirname $pbi | sed 's|./||')
5826
  PBI_CONFDIR="$_cd"
5827

    
5828
  # Get the prog version
5829
  get_pbi_progversion
5830

    
5831
  if [ -z "${PBI_MAKEPORT}" ] ; then
5832
     PBI_MAKEPORT=$(dirname $pbi | sed 's|./||')
5833
  fi	
5834

    
5835
  echo "==> Starting build process [$curBuilder]: $PBI_MAKEPORT"
5836
  echo "$PBI_MAKEPORT" >${PBI_TMPDIR}/${curBuilder}.bPort
5837

    
5838
  # Remove this from the queue
5839
  cat ${PBI_TMPDIR}/.ablist | tail -n +2 > ${PBI_TMPDIR}/.abtmp
5840
  mv ${PBI_TMPDIR}/.abtmp ${PBI_TMPDIR}/.ablist
5841

    
5842
  # Start the build now
5843
  start_ext_ab "$PBI_MAKEPORT" \
5844
  "${PBI_BUILDKEY}" "${PBI_PROGVERSION}" \
5845
  "${_cd}" "${PBI_AB_OUTDIR}" "${PBI_AB_TIMESTAMP}" "${curBuilder}"
5846

    
5847
  return 1
5848
};
5849

    
5850
# Prune any outdir files which don't have matching modules
5851
do_pbi_autob_prune() {
5852
	if [ "${PBI_AB_PRUNE}" != "YES" ] ; then return 0 ; fi
5853

    
5854
	echo "=> Cleaning outgoing directory..."
5855
    	# Prune outgoing dirs which don't have matching modules anymore
5856
	cd "${PBI_AB_OUTDIR}"
5857
	for i in `find . -type d | grep -v '\.svn'`
5858
	do
5859
		if [ "${i}" = "." -o "${i}" = ".." ] ; then continue ; fi
5860
		_pDir=`dirname ${i}`
5861
		if [ -d "${i}" -a -n "${i}" ] ; then
5862
    			if [ ! -e "${PBI_AB_CONFDIR}/${_pDir}" ] ; then
5863
      			# Not in our module tree anymore, remove it
5864
      			echo "Auto-Prune: ${PBI_AB_OUTDIR}/${_pDir}"
5865
      			rm -rf "${PBI_AB_OUTDIR}/${_pDir}"
5866
    			fi
5867
  		fi
5868
	done
5869
	cd
5870
}
5871

    
5872
# Start the pbi_makeport process
5873
start_ext_ab() {
5874
	_mp="${1}"
5875
	_bk="${2}"
5876
	_pv="${3}"
5877
	_cd="${4}"
5878
	_od="${5}/${_cd}"
5879
	local _abkey="$6"
5880
	local eBuilder="$7"
5881
	_flags=""
5882
	_flags="-c ${_cd} -d ${PORTSDIR} -o ${_od} --delbuild"
5883
	if [ -n "${PBI_AB_SSLPRIVKEY}" ] ; then
5884
		_flags="${_flags} --sign ${PBI_AB_SSLPRIVKEY}"
5885
	fi
5886

    
5887
	# Check if we need to enable tmpfs
5888
 	if [ "$PBI_AB_TMPFS" = "YES" ] ; then
5889
		if [ -z "${PBI_AB_NOTMPFS}" -o "$PBI_AB_NOTMPFS" != "YES" ] ; then
5890
		   	_flags="${_flags} --tmpfs"
5891
		fi
5892
	fi
5893

    
5894
	# Check if we need to enable pkgcaching
5895
 	if [ "$PBI_AB_PKGCACHE" = "YES" -a -z "$PBI_AB_NOPKGCACHE"  ] ; then
5896
		if [ ! -d "${_od}/pkgcache" ] ; then
5897
			mkdir -p ${_od}/pkgcache
5898
		fi
5899
		_flags="${_flags} --pkgdir ${_od}/pkgcache"
5900
	fi
5901

    
5902
	# Are we doing 32bit builds?
5903
 	if [ "$PBI_AB32" = "YES" ] ; then _flags="${_flags} -32"; fi
5904

    
5905
	get_pbi_progversion
5906

    
5907
	#echo "Starting build of ${_mp} - ${_pv}"
5908
	#echo "pbi_makeport ${_flags} ${_mp}"
5909

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

    
5912
	# Save the autobuild hash key
5913
	echo "$_abkey" > ${_od}/.abkey
5914
	
5915
	# Save the build key for this PBI
5916
	if [ -n "$_bk" ] ; then
5917
		echo "$_bk" > "${_od}/pbi-buildkey"
5918
	else
5919
		echo "__NONE__" > "${_od}/pbi-buildkey"
5920
	fi
5921

    
5922
	# Clean old log files
5923
	if [ -e "${_od}/build.log" ] ; then
5924
		rm "${_od}/build.log"
5925
	fi
5926
	if [ -e "${_od}/build.log.bz2" ] ; then
5927
		rm "${_od}/build.log.bz2"
5928
	fi
5929
	if [ -e "${_od}/.failed-csum" ] ; then
5930
		rm ${_od}/.failed-csum
5931
	fi
5932

    
5933
	# Move old PBIs to archived folder
5934
        oldVersion=`cat ${_od}/pbi-version 2>/dev/null`
5935
	if [ "$oldVersion" != "$PBI_PROGVERSION" ]; then
5936
		#echo "Archiving old PBIs..."
5937
		archive_old_pbis "${_od}" "$PBI_AB_ARCHIVENUM"
5938
	fi
5939

    
5940
	# Set some variables we can call in pbi_makeport
5941
	PBI_AB_TMPDIR="${PBI_TMPDIR}"
5942
	PBI_AB_BUILDER="$eBuilder"
5943
	export PBI_AB_TMPDIR PBI_AB_BUILDER
5944

    
5945
	# Add some header info to log file
5946
	echo "Starting build: `date`" >${_od}/build.log
5947
	echo "Build Command:" >>${_od}/build.log
5948
	echo "pbi_makeport ${_flags} ${_mp}" >>${_od}/build.log
5949
	echo "------------------------------------------------------" >>${_od}/build.log
5950
	
5951
	echo "${_od}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.od"
5952
	echo "${_mp}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.mp"
5953
	echo "${_cd}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.cd"
5954
	echo "${PBI_PROGVERSION}" > "${PBI_TMPDIR}/${PBI_AB_BUILDER}.pv"
5955
	pbi_makeport ${_flags} ${_mp} >>${_od}/build.log 2>>${_od}/build.log &
5956
  	echo "$!" > ${PBI_TMPDIR}/${eBuilder}.pid
5957

    
5958
}
5959

    
5960
ab_post_build() 
5961
{
5962
	local build=$1
5963
	_od="`cat ${PBI_TMPDIR}/${build}.od`"
5964
	_mp="`cat ${PBI_TMPDIR}/${build}.mp`"
5965
	_cd="`cat ${PBI_TMPDIR}/${build}.cd`"
5966
	_pv="`cat ${PBI_TMPDIR}/${build}.pv`"
5967
	sleep 1
5968

    
5969
	if [ -e "${PBI_TMPDIR}/${build}.result" -a "`cat ${PBI_TMPDIR}/${build}.result`" = "0" ] ; then
5970
		echo "$_pv" > "${_od}/pbi-version"
5971
		echo "OK" > "${_od}/pbi-result"
5972

    
5973
		# Save the mdate file
5974
		date "+%Y%m%d %H%M%S" >${_od}/pbi-mdate
5975

    
5976
		if [ -n "${PBI_AB_HELPS}" ] ; then
5977
			${PBI_AB_HELPS} "OK" "${_od}"
5978
		fi
5979

    
5980
		# Copy over a description file
5981
		if [ -e "${PORTSDIR}/${_mp}/pkg-descr" ] ; then
5982
			cp "${PORTSDIR}/${_mp}/pkg-descr" "${_od}/pbi-descr"
5983
		fi
5984
		if [ -e "${PBI_AB_CONFDIR}/${_cd}/pbi-descr" ] ; then
5985
			cp "${PBI_AB_CONFDIR}/${_cd}/pbi-descr" "${_od}/pbi-descr"
5986
		fi
5987

    
5988
		# Check if we need to rebuild patches
5989
		if [ "$PBI_AB_GENPATCH" = "YES" -a -d "${_od}/archived" ] ; then
5990
			echo "===> Generating patches for [$build]"
5991
			gen_pbi_patches "${_od}" "${_od}/archived"
5992
		fi
5993

    
5994
		rm "${_od}/build.log.bz2" >/dev/null 2>/dev/null
5995
		bzip2 "${_od}/build.log"
5996

    
5997
	else
5998
		# Save the md5sum of the ports directory
5999
		tar cvf - -C "${PORTSDIR}/${_mp}" . 2>/dev/null | md5 -q >${_od}/.failed-csum
6000

    
6001
		echo "Failed" > "${_od}/pbi-result"
6002
		if [ -n "${PBI_AB_HELPS}" ] ; then
6003
			${PBI_AB_HELPS} "FAILED" "${_od}"
6004
		fi
6005
	fi
6006

    
6007
}
6008

    
6009
# Function which begins to generate patch files from archived PBIs to current
6010
gen_pbi_patches()
6011
{
6012
	_curPBIdir="$1"
6013
	_oldPBIdir="$2"
6014

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

    
6017
	# First remove any old patches
6018
	rm ${_curPBIdir}/*.pbp 2>/dev/null
6019
	rm ${_curPBIdir}/*.pbp.sha256 2>/dev/null
6020

    
6021
	# Make sure to enable signing of the patch files
6022
	if [ -n "${PBI_AB_SSLPRIVKEY}" ] ; then
6023
        	local _mpflags="-o $_curPBIdir --sign ${PBI_AB_SSLPRIVKEY}"
6024
	else
6025
		local _mpflags="-o $_curPBIdir"
6026
	fi
6027

    
6028
	# Check if we need to enable tmpfs
6029
 	if [ "$PBI_AB_TMPFS" = "YES" ] ; then _mpflags="${_mpflags} --tmpfs" ; fi
6030

    
6031
	# Build a list of old PBIs we need to make patches from
6032
	for _oPBI in `ls ${_oldPBIdir}/*.pbi 2>/dev/null`
6033
	do
6034
		# Make sure we don't try to make a patch of identical files
6035
	  	if [ "`basename $_oPBI`" != "`basename $_curPBI`" ] ; then	
6036
			#echo "Building pbp patch of ${_oPBI} -> ${_curPBI}"
6037
			pbi_makepatch $_mpflags "$_oPBI" "$_curPBI" >/dev/null 2>/dev/null
6038
			if [ "$?" != "0" ] ; then
6039
				echo "pbi_makepatch: Failed creating patchfile for $_oPBI -> $_curPBI"
6040
			fi
6041
		 	
6042
		fi
6043
	done
6044
}
6045

    
6046
# Function which compares two PBIs, and creates a .pbp file from the differences 
6047
make_pbi_patchfile()
6048
{
6049
	_pbiNew="$1"
6050
	_pbiOld="$2"
6051
	_cDir="$3"
6052

    
6053
	init_tmpdir
6054

    
6055
        # Load all the information about this PBI / PBP
6056
	PBI_FILENAME="$1"
6057
        load_info_from_header
6058

    
6059
	_pbiNewDir="${PBI_APPDIR}/.newPBI-$$"
6060
	_pbiOldDir="${PBI_APPDIR}/.oldPBI-$$"
6061
	_pbiPatchDir="${PBI_APPDIR}/.patchPBI-$$"
6062
	_pbiPatchHeaderDir="${PBI_APPDIR}/.patchPBIHeaderDir-$$"
6063
	_pbiPatchArchiveFile="${PBI_APPDIR}/.patchPBIArchive-$$"
6064
	_pbiPatchHeaderFile="${PBI_APPDIR}/.patchPBIHeaderFile-$$"
6065

    
6066
	# Get the PBI Versions
6067
	get_ver_from_pbi_file "$_pbiNew"
6068
	_pbiNewVer="$VAL"
6069
	get_ver_from_pbi_file "$_pbiOld"
6070
	_pbiOldVer="$VAL"
6071

    
6072
	# Get the PBI directory names
6073
	get_prefix_from_pbi_file "$_pbiNew"
6074
	_pbiNewPrefix="`basename $VAL`"
6075
	get_prefix_from_pbi_file "$_pbiOld"
6076
	_pbiOldPrefix="`basename $VAL`"
6077

    
6078
	# Get the mdate of the old PBI
6079
	get_mdate_from_pbi_file "$_pbiOld"
6080
	_pbiOldMDate="$VAL"
6081

    
6082
	# Sanity check these prefixes
6083
	if [ "${_pbiNewPrefix}" != "${_pbiOldPrefix}" ] ; then
6084
		echo "Error: Prefix mismatch between $_pbiNew and $_pbiOld"
6085
		return
6086
	fi
6087

    
6088
	# Get the arch type
6089
	get_arch_from_pbi_file "$_pbiNew"
6090
	_pbiNewArch="$VAL"
6091
	get_arch_from_pbi_file "$_pbiOld"
6092
	_pbiOldArch="$VAL"
6093

    
6094
	# Sanity check these system types
6095
	if [ "${_pbiNewArch}" != "${_pbiOldArch}" ] ; then
6096
		echo "Error: Arch mismatch between $_pbiNew and $_pbiOld"
6097
		return
6098
	fi
6099

    
6100
	# Make our extraction directories
6101
	if [ -e "$_pbiNewDir" ] ; then rm -rf "$_pbiNewDir"; fi
6102
	if [ -e "$_pbiOldDir" ] ; then rm -rf "$_pbiOldDir"; fi
6103
	if [ -e "$_pbiPatchDir" ] ; then rm -rf "$_pbiPatchDir"; fi
6104
	mkdir -p "$_pbiNewDir"
6105
	mkdir -p "$_pbiOldDir"
6106
	mkdir -p "$_pbiPatchDir"
6107

    
6108
	# If using tmpfs to speed up patch process
6109
        if [ "$PBI_MP_TMPFS" = "YES" ] ; then
6110
		mount -t tmpfs tmpfs "${_pbiNewDir}"
6111
		mount -t tmpfs tmpfs "${_pbiOldDir}"
6112
		mount -t tmpfs tmpfs "${_pbiPatchDir}"
6113
	fi
6114

    
6115
	local _opts="-e --licagree"
6116
	if [ "${PBI_SKIPSIGVERIFY}" = "YES" ] ; then
6117
		_opts="${_opts} --no-checksig"
6118
	fi
6119

    
6120
	# Extract the two PBIs
6121
	echo "Extracting PBI: $_pbiNew"
6122
	pbi_add ${_opts} -o "${_pbiNewDir}" "${_pbiNew}" >/dev/null 2>/dev/null
6123
	echo "Extracting PBI: $_pbiOld"
6124
	pbi_add ${_opts} -o "${_pbiOldDir}" "${_pbiOld}" >/dev/null 2>/dev/null
6125

    
6126
	if [ ! -d "${_pbiNewDir}/${_pbiNewPrefix}" -o ! -d "${_pbiOldDir}/${_pbiOldPrefix}" ] ; then 
6127
		exit_err "Failed Extracting PBIs for comparision!"
6128
	fi
6129

    
6130
	# Get a list of files which are removed in the new PBI vs the old
6131
	gen_rem_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
6132
	_rFileList="$VAL"
6133
	if [ -n "$_rFileList" ] ; then
6134
		echo "Saving removed file list..."
6135
		mv "${_rFileList}" ${_pbiPatchDir}/PBI-rmList
6136
	fi
6137

    
6138
	# Get archive of files/dirs which are new to the PBI
6139
	gen_newfile_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
6140
	_nFileList="$VAL"
6141
	if [ -n "$_nFileList" ] ; then
6142
		echo "Saving new files archive..."
6143
		tar cvf "$_pbiPatchDir/PBI-newFiles.tar" \
6144
			-C "$_pbiNewDir/$_pbiNewPrefix" -T "$_nFileList" >/dev/null 2>/dev/null
6145
		rm "$_nFileList"
6146
	fi
6147

    
6148
	# Get a listing of permissions
6149
	gen_chmod_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
6150
	_cFileList="$VAL"
6151
	if [ -n "$_cFileList" ] ; then
6152
		echo "Saving permissions list..."
6153
		mv "${_cFileList}" ${_pbiPatchDir}/PBI-permList
6154
	fi
6155

    
6156
	# Generate diffs of files which have changed between the two
6157
	gen_bsdiffs_dirs "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix" "$_pbiPatchDir"
6158

    
6159
	# Make the file archive
6160
	if test_tar_lzma ; then _tcmp="J" ; else _tcmp="j" ; fi
6161
	echo "Creating compressed archive..."
6162
	tar cv${_tcmp}f "${_pbiPatchArchiveFile}" -C ${_pbiPatchDir} . 2>/dev/null 
6163

    
6164
	# Make the header file
6165
	if [ -e "$_pbiPatchHeaderDir" ] ; then rm -rf "$_pbiPatchHeaderDir"; fi
6166
	mkdir -p "$_pbiPatchHeaderDir"
6167
	open_header_tmp "${PBI_TMPDIR}"
6168
  	cp ${PBI_HEADER_TMPDIR}/* "$_pbiPatchHeaderDir/"
6169

    
6170
	# Save the mdate of the old PBI
6171
	echo "$_pbiOldMDate" > $_pbiPatchHeaderDir/pbi_patchmdate
6172

    
6173
	# Remove any signatures
6174
  	rm $_pbiPatchHeaderDir/*.sha1 >/dev/null 2>/dev/null
6175

    
6176
	# Get the archive checksum
6177
	sha256 -q "${_pbiPatchArchiveFile}" > "${_pbiPatchHeaderDir}/pbi_archivesum"
6178
	
6179
	# Set the tag that this is a patch file
6180
	echo "${_pbiOldVer}:${_pbiNewVer}" > "${_pbiPatchHeaderDir}/pbi_patchfile"
6181
	
6182
	# Sign the files if necessary
6183
	sign_pbi_files "${_pbiPatchHeaderDir}"
6184

    
6185
	# Make the header tmpfile
6186
	tar cvjf "${_pbiPatchHeaderFile}" -C ${_pbiPatchHeaderDir} . 2>/dev/null 
6187
	if [ "$?" != "0" ] ; then
6188
		echo "Warning: TAR returned error creating header archive!"
6189
	fi
6190
	rm -rf ${_pbiPatchHeaderDir} 
6191
	
6192
	# Make the pbp file
6193
	get_progname_from_pbi_file "$_pbiNew"
6194
        _pbilow="`echo ${VAL} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
6195
        
6196
        outfile="${_cDir}/${_pbilow}-${_pbiOldVer}_to_${_pbiNewVer}-${_pbiNewArch}.pbp"
6197
        mark1="${_cDir}/.pbimark1.$$"
6198
        mark2="${_cDir}/.pbimark2.$$"
6199
        
6200
        echo "
6201
${PBI_SS_ICON}" >$mark1
6202
        echo "
6203
${PBI_SS_ARCHIVE}" >$mark2
6204
                
6205
        # DO IT, DO IT NOW!!!
6206
        cat ${_pbiPatchHeaderFile} $mark1 ${PBI_PATCH_ICON} $mark2 ${_pbiPatchArchiveFile} > ${outfile}
6207
        sha256 -q ${outfile} > ${outfile}.sha256
6208

    
6209
	# Cleanup the archive stuff
6210
        rm $mark1
6211
        rm $mark2
6212
        rm ${_pbiPatchHeaderFile}
6213
        rm ${_pbiPatchArchiveFile}
6214
	
6215
	# Cleanup the directories
6216
	rm_pbipatchfiles
6217

    
6218
	# Do some smell testing, make sure the patch file isn't larger than the PBI itself
6219
	# This happens with some java programs occasionally
6220
	if [ `du -k ${outfile} | awk '{print $1}'` -gt `du -k ${_pbiNew} | awk '{print $1}'` ]; then
6221
		rm ${outfile}
6222
		rm ${outfile}.sha256
6223
		exit_err "The patch is larger than the new PBI, aborting!"
6224
	else
6225
		# We have a patch!
6226
           	echo "Created PBP: ${outfile}"
6227
	fi
6228

    
6229

    
6230
}
6231

    
6232
# Function which compares two directories, and returns a list of chmod commands to get them in line
6233
gen_chmod_list() {
6234

    
6235
	_chList="${PBI_TMPDIR}/.pbi.chList.$$"
6236
	if [ -e "$_chList" ] ; then rm "$_chList" ; fi
6237

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

    
6240
	echo "Getting permissions of changed files..."
6241

    
6242
	while read line
6243
	do
6244
		# Make sure this file exists in the new / old dirs
6245
		if [ -z "$line" ] ; then continue ; fi
6246
		if [ ! -f "${1}/$line" ] ; then continue ; fi
6247
		if [ ! -e "${2}/$line" ] ; then continue ; fi
6248

    
6249
		# Filter out any special files, we don't need diffs of them
6250
		if [ -L "${1}/$line" ] ; then continue ; fi
6251
		if [ -p "${1}/$line" ] ; then continue ; fi
6252
		if [ -S "${1}/$line" ] ; then continue ; fi
6253
		if [ -d "${1}/$line" ] ; then continue ; fi
6254
		if [ -b "${1}/$line" ] ; then continue ; fi
6255
		if [ -c "${1}/$line" ] ; then continue ; fi
6256

    
6257
		_newPerm=`stat -f %Op "${1}/$line"  | cut -c 3-6`
6258
		_oldPerm=`stat -f %Op "${1}/$line"  | cut -c 3-6`
6259
		if [ "$_newPerm" != "$_oldPerm" ] ; then
6260
			# We have new permissions! Lets be sure to save them
6261
			echo "chmod $_newPerm $line" >> $_chList
6262
		fi
6263

    
6264
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6265

    
6266
	# Remove the tmp list files
6267
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6268

    
6269
	if [ -e "$_chList" ] ; then
6270
		VAL="$_chList"
6271
	else
6272
		VAL=""
6273
	fi
6274
}
6275

    
6276

    
6277

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

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

    
6283
	echo "Getting bsdiffs of changed files..."
6284

    
6285
	while read line
6286
	do
6287
		# Make sure this file exists in the new / old dirs
6288
		if [ -z "$line" ] ; then continue ; fi
6289
		if [ ! -f "${1}/$line" ] ; then continue ; fi
6290
		if [ ! -e "${2}/$line" ] ; then continue ; fi
6291

    
6292
		# Filter out any special files, we don't need diffs of them
6293
		if [ -L "${1}/$line" ] ; then continue ; fi
6294
		if [ -p "${1}/$line" ] ; then continue ; fi
6295
		if [ -S "${1}/$line" ] ; then continue ; fi
6296
		if [ -d "${1}/$line" ] ; then continue ; fi
6297
		if [ -b "${1}/$line" ] ; then continue ; fi
6298
		if [ -c "${1}/$line" ] ; then continue ; fi
6299

    
6300
		# Check sha256 of each file, see if we have differences
6301
		sha1=`sha256 -q "${1}/${line}"`
6302
		sha2=`sha256 -q "${2}/${line}"`
6303
		if [ "$sha1" != "$sha2" ] ; then
6304
			# These files differ, get a binary patch made of them
6305
			_tDir="${3}/`dirname $line`"
6306
			_bName=`basename $line`
6307
			if [ ! -d "$_tDir" ] ; then mkdir -p "$_tDir" ; fi
6308
			
6309
			bsdiff "${2}/${line}" "${1}/${line}" "${_tDir}/${_bName}.bsdiff"
6310
			if [ "$?" != "0" ] ; then
6311
				exit_err "Failed creating bsdiff patch for $line"
6312
			fi
6313

    
6314
			# Save the sha256 of the file to be modified
6315
			sha256 -q "${2}/${line}" > "${_tDir}/${_bName}.sha256"
6316
		fi
6317

    
6318
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6319

    
6320
	# Remove the tmp list files
6321
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6322
}
6323

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

    
6327
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6328
	find ${2} | sed "s|^${2}/||g" | sed "s|^${2}||g" >${PBI_TMPDIR}/.pbi.oDir.$$
6329

    
6330
	echo "Finding removed files..."
6331

    
6332
	_rmList="${PBI_TMPDIR}/.pbi.rmList.$$"
6333
	if [ -e "$_rmList" ] ; then rm "$_rmList" ; fi
6334

    
6335
	while read line
6336
	do
6337
		if [ -z "$line" ] ; then continue ; fi
6338
		grep "^$line" ${PBI_TMPDIR}/.pbi.nDir.$$ >/dev/null 2>/dev/null
6339
		if [ "$?" != "0" ] ; then
6340
			#echo "Removed File: $line"
6341
			echo "$line" >> ${_rmList}
6342
		fi
6343

    
6344
	done < ${PBI_TMPDIR}/.pbi.oDir.$$
6345

    
6346
	# Remove the tmp list files
6347
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6348
	rm ${PBI_TMPDIR}/.pbi.oDir.$$
6349

    
6350
	if [ -e "$_rmList" ] ; then
6351
		VAL="$_rmList"
6352
	else
6353
		VAL=""
6354
	fi
6355
}
6356

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

    
6360
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6361
	echo "Finding new files..."
6362

    
6363
	_addList="${PBI_TMPDIR}/.pbi.addList.$$"
6364
	if [ -e "$_addList" ] ; then rm "$_addList" ; fi
6365

    
6366
	while read line
6367
	do
6368
		# Search for all new files + symlinks to include in tarball
6369
		if [ -z "$line" ] ; then continue ; fi
6370
		if [ ! -e "${2}/$line" -o -L "${1}/$line" ] ; then
6371
			#echo "New File: $line"
6372
			echo "./$line" >> ${_addList}
6373
		fi
6374

    
6375
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6376

    
6377
	# Remove the tmp list files
6378
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6379

    
6380
	if [ -e "$_addList" ] ; then
6381
		VAL="$_addList"
6382
	else
6383
		VAL=""
6384
	fi
6385
}
6386

    
6387
# Read the version from a PBI file
6388
get_ver_from_pbi_file() 
6389
{
6390
	VAL="`pbi_add -i $1 | grep Version: | cut -d ':' -f 2 | tr -d ' '`"
6391
	export VAL
6392
}
6393

    
6394
# Read the version from a PBI file
6395
get_progname_from_pbi_file() 
6396
{
6397
	VAL="`pbi_add -i $1 | grep Name: | cut -d ':' -f 2 | tr -d ' '`"
6398
	export VAL
6399
}
6400

    
6401
get_prefix_from_pbi_file()
6402
{
6403
	VAL="`pbi_add -i $1 | grep Prefix: | cut -d ':' -f 2 | tr -d ' '`"
6404
	export VAL
6405
}
6406

    
6407
get_mdate_from_pbi_file()
6408
{
6409
	VAL="`pbi_add -i $1 | grep Built: | cut -d ' ' -f 2-5 | tr -s ' '`"
6410
	export VAL
6411
}
6412

    
6413
get_arch_from_pbi_file()
6414
{
6415
	VAL="`pbi_add -i $1 | grep Arch: | cut -d ' ' -f 2-5 | tr -s ' '`"
6416
	export VAL
6417
}
6418

    
6419
# Move old PBIs to the archive
6420
archive_old_pbis()
6421
{
6422
	local _od="$1"
6423
	local _keepnum="$2"
6424

    
6425
	# Make sure the archived dir exists
6426
	if [ ! -d "${_od}/archived" ] ; then mkdir "${_od}/archived"; fi
6427

    
6428
	# Make sure we have PBIs to archive
6429
	ls ${_od}/*.pbi >/dev/null 2>/dev/null
6430
        if [ "$?" != "0" ] ; then return ; fi
6431

    
6432
	#echo "Moving old PBIs from ${_od}/*.pbi -> ${_od}/archived/"
6433
	mv ${_od}/*.pbi ${_od}/archived/ 2>/dev/null
6434
	mv ${_od}/*pbi.sha256 ${_od}/archived/ 2>/dev/null
6435

    
6436
	# Prune anything beyond the _keepnum
6437
        #echo "Checking for more than $_keepnum PBIs in archive"
6438
	oCount="1"
6439
	for oFile in `ls -t ${_od}/archived/*.pbi 2>/dev/null`
6440
	do
6441
		if [ -z "$oFile" ] ; then continue ; fi
6442
		if [ "$oCount" -gt "$_keepnum" ] ; then
6443
			#echo "Removing old PBI ${oFile} from archive"
6444
			rm ${oFile}*
6445
		fi
6446
		oCount=`expr $oCount + 1`	
6447
	done
6448
}
6449

    
6450
# Check if we need to do an auto-build of the target PBI
6451
check_ab_needed() {
6452
	_port="$1"
6453
	_bk="$2"
6454
	_cd="$3"
6455
	local _abkey="$4"
6456
        internal_ab_priority="1"
6457
	export internal_ab_priority
6458
        unset PBI_PROGVERSION
6459

    
6460
	# Check PBI_BUILDKEY, see if we have a manual rebuild triggered
6461
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/pbi-buildkey" ] ; then
6462
		if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-buildkey`" != "$_bk" \
6463
			 -a -n "${_bk}" ]; then 
6464
                   #echo "$_port BUILDKEY bump, rebuild triggered."
6465
                   internal_ab_priority="9"
6466
                   return 0
6467
                fi
6468
	fi
6469

    
6470
	# Make sure this PBI hasn't already failed during this run
6471
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/.abkey" -a -e "${PBI_AB_OUTDIR}/${_cd}/pbi-result" ] ; then
6472
	  if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/.abkey`" = "$_abkey" ] ; then
6473
	    if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-result`" != "OK" ] ; then
6474
              #echo "$_port - Skipping failed from this run"
6475
	      return 1
6476
  	    fi
6477
  	  fi
6478
	fi
6479

    
6480
	#echo "Checking $_port for rebuild in ${PBI_AB_OUTDIR}/$_cd with key of $_bk"
6481

    
6482
	# Check if this is a failed port we should be skipping until its fixed
6483
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/.failed-csum" ] ; then
6484
		_fcsum="`cat ${PBI_AB_OUTDIR}/${_cd}/.failed-csum`"
6485
		_ncsum="`tar cvf - -C "${PORTSDIR}/${_port}" . 2>/dev/null | md5 -q`"
6486
		if [ "$_fcsum" = "$_ncsum" ] ; then
6487
            		#echo "$_port - Skipping failed"
6488
			return 1
6489
		fi
6490
 	fi	
6491

    
6492
	# See if we have an existing PBI
6493
	ls ${PBI_AB_OUTDIR}/${_cd}/*.pbi >/dev/null 2>/dev/null
6494
	if [ "${?}" != "0" ]; then 
6495
	  #echo "$_port - No existing PBI"
6496
          internal_ab_priority="8"
6497
          return 0 
6498
        fi
6499

    
6500
	# See if we have a saved version
6501
	if [ ! -e "${PBI_AB_OUTDIR}/${_cd}/pbi-version" ]; then 
6502
		#echo "No saved pbi-version"
6503
	  	#echo "$_port - No existing version"
6504
          	internal_ab_priority="7"
6505
		return 0
6506
	fi
6507

    
6508
	# Get the programs port version
6509
	get_pbi_progversion
6510

    
6511
	# See if the version is different now
6512
	oldVersion=`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-version`
6513
	if [ "$oldVersion" != "$PBI_PROGVERSION" ]; then 
6514
		oldPortVer="`echo $oldVersion | rev | cut -d '_' -f 2- | rev`"
6515
		if [ "$PORTVER" = "$oldPortVer" ] ; then
6516
			# Just a minor portrev bump
6517
          		internal_ab_priority="2"
6518
			#echo "$_port revision bump: $oldVersion -> $PBI_PROGVERSION"
6519
		else
6520
			# Real version change
6521
          		internal_ab_priority="3"
6522
			#echo "$_port version bump: $oldVersion -> $PBI_PROGVERSION"
6523
		fi
6524
		return 0
6525
	fi
6526

    
6527
	#echo "$_port - is Up2Date!"
6528
	return 1
6529
}
6530

    
6531
# start processing for make port / pbi compile
6532
pbi_make_init() {
6533

    
6534
  	require_root
6535

    
6536
  	parse_make_pbi_cmdline "$@"
6537
 
6538
  	do_pbi_make "$@"
6539
}
6540

    
6541
do_pbi_make() {
6542

    
6543
	# See if we need to enable pkgng
6544
	detect_pkgng
6545

    
6546
  	# Load the PBI settings
6547
	get_pbi_progversion
6548
	get_pbi_progname
6549
  	get_pbi_progdir
6550

    
6551
	# Check if this is being called from within chroot or outside
6552
	if [ "`basename $0`" = "pbi_makeport" ] ; then
6553
		# Extract the chroot 
6554
		chroot_extract
6555

    
6556
		# Now re-run pbi_makeport in chroot environment
6557
		chroot "${PBI_CHROOTDIR}" "/usr/local/sbin/pbi_makeport_chroot" "$@"
6558
		_err=$?
6559
		if [ "$_err" = "0" -a "${PBI_BUILDONLY}" != "YES" ] ; then
6560
			mv ${PBI_CHROOTDIR}/pbiout/*.pbi ${PBI_CREATE_OUTDIR}/ 
6561
			mv ${PBI_CHROOTDIR}/pbiout/*.sha256 ${PBI_CREATE_OUTDIR}/
6562
		fi
6563

    
6564
  		# Break here if we are only doing a build
6565
		if [ "${PBI_BUILDONLY}" = "YES" ] ; then exit_trap; fi
6566

    
6567
		# Lets cleanup the chroot environment
6568
		chroot_make_cleanup
6569
		rm_tmpdir
6570

    
6571
		# If running as an auto-build, show that we were successful
6572
		if [ -n "$PBI_AB_TMPDIR" ] ; then
6573
        		echo "$_err" > ${PBI_AB_TMPDIR}/${PBI_AB_BUILDER}.result
6574
		fi
6575
		exit $_err
6576
	fi
6577

    
6578
	if [ "`basename $0`" != "pbi_makeport_chroot" ] ; then return ; fi
6579
	
6580

    
6581
  	# Check if we have some specific make options to use
6582
  	load_pbi_conffile
6583

    
6584
  	# init tmpdir
6585
  	init_tmpdir
6586

    
6587
  	set_make_options
6588

    
6589
  	# See if we need to run a pre make script
6590
  	run_pbi_preportmake
6591

    
6592
  	# Start our build
6593
  	start_pbi_mkportbefore
6594
  	start_prebuild_script
6595
  	start_pbi_makeport
6596
  	start_postbuild_script
6597
  	start_pbi_mkportafter
6598

    
6599
  	# Prune any proto / build specific ports
6600
  	start_pbi_prune_ports
6601

    
6602
  	# See if we need to run a post make script
6603
  	run_pbi_postportmake
6604

    
6605
	# Check for any users / groups we need to save for install time
6606
	mk_pbi_users_file
6607
	mk_pbi_groups_file
6608

    
6609
	# Auto-generate a external_links directive from plist info
6610
	mk_auto_ext_linksfile
6611

    
6612
	# Check if we created a linux app, and need to copy files for it
6613
	auto_copy_linuxbase
6614

    
6615
  	# Break here if we are only doing a build
6616
	if [ "${PBI_BUILDONLY}" = "YES" ] ; then exit_trap; fi
6617

    
6618
	# Start creation of PBI
6619
	do_pbi_create
6620

    
6621
	# Got this far, lets exit with success
6622
	rm_buildfiles
6623
	rm_tmpdir
6624

    
6625
	exit 0
6626
}
6627

    
6628
# Check if we need to save a list of GROUPS to create at install
6629
mk_pbi_groups_file()
6630
{
6631
	if [ -z "$PBI_BUILD_GROUPS" ] ; then return ; fi
6632

    
6633
	for group in $PBI_BUILD_GROUPS
6634
	do
6635
		# Check /usr/ports/GIDs for group entry
6636
		gidLine=`cat /usr/ports/GIDs | grep "^$group:"`
6637
		if [ -z "$gidLine" ] ; then
6638
			echo "Warning: No entry for \"$group\" in GIDs file..."
6639
			continue
6640
		fi
6641
		grep -q "^$group:" ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE} 2>/dev/null
6642
		if [ $? -ne 0 ] ; then
6643
			echo "Saving gid details for group: $group"
6644
			echo "$gidLine" >> ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}
6645
		fi
6646
	done
6647
}
6648

    
6649
# Check if we need to save a list of users to create at install
6650
mk_pbi_users_file()
6651
{
6652
	if [ -z "$PBI_BUILD_USERS" ] ; then return ; fi
6653

    
6654
	for user in $PBI_BUILD_USERS
6655
	do
6656
		# Check /usr/ports/UIDs for user entry
6657
		uidLine=`cat /usr/ports/UIDs | grep "^$user:"`
6658
		if [ -z "$uidLine" ] ; then
6659
			echo "Warning: No entry for \"$user\" in UIDs file..."
6660
			continue
6661
		fi
6662
		grep -q "^$user:" ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE} 2>/dev/null
6663
		if [ $? -ne 0 ] ; then
6664
			echo "Saving uid details for user: $user"
6665
			echo "$uidLine" >> ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}
6666
		fi
6667
	done
6668
}
6669

    
6670
# Source any pre-build script to allow a custom script to modify the port
6671
start_prebuild_script()
6672
{
6673
	if [ -e "/pre-build.sh" ] ; then
6674
		chmod 755 /pre-build.sh
6675
		# Source the script
6676
		. /pre-build.sh
6677
	fi
6678
}
6679

    
6680
# Source any post-build script to allow a custom script to modify the port
6681
start_postbuild_script()
6682
{
6683
	if [ -e "/post-build.sh" ] ; then
6684
		chmod 755 /post-build.sh
6685
		# Source the script
6686
		. /post-build.sh
6687
	fi
6688
}
6689

    
6690
# Check if we created any linux stuff, and copy it into the correct PREFIX
6691
auto_copy_linuxbase()
6692
{
6693
	echo "Checking for Linux libraries to copy..."
6694
	if [ -d "/compat/linux/usr/lib" ] ; then
6695
		mkdir ${PBI_PROGDIRPATH}/linuxlib
6696
		echo "Copying /compat/linux/lib -> ${PBI_PROGDIRPATH}/linuxlib"
6697
		tar cvf - -C /compat/linux/lib . 2>/dev/null | \
6698
		tar xvf - -C ${PBI_PROGDIRPATH}/linuxlib 2>/dev/null
6699
		echo "Copying /compat/linux/usr/lib -> ${PBI_PROGDIRPATH}/linuxlib"
6700
		tar cvf - -C /compat/linux/usr/lib . 2>/dev/null | \
6701
		tar xvf - -C ${PBI_PROGDIRPATH}/linuxlib 2>/dev/null
6702
	fi
6703
}
6704

    
6705
# Clean the chroot environment
6706
chroot_make_cleanup() {
6707
	[ -z "${PBI_CHROOTDIR}" ] && return
6708
	[ -d "${PBI_CHROOTDIR}" ] || return
6709
	[ "${PBI_CHROOTDIR}" = "/" ] && return
6710
	
6711
	# Unmount /dev if mounted
6712
	echo "Cleaning $PBI_CHROOTDIR"
6713
	umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
6714
	umount -f ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
6715
	umount -f ${PBI_CHROOTDIR}/usr/ports >/dev/null 2>/dev/null
6716
	umount -f ${PBI_CHROOTDIR}/pkgs >/dev/null 2>/dev/null
6717
	umount -f ${PBI_CHROOTDIR}/.ccache >/dev/null 2>/dev/null
6718
	umount -f ${PBI_CHROOTDIR}/usr/wrkdirprefix >/dev/null 2>/dev/null
6719

    
6720
	# Sleep a moment before we try this again, seems it takes a moment to clear up
6721
	sleep 2
6722
	umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
6723

    
6724
	if [ "${PBI_KEEPBUILDFILES}" = "YES" ] ; then return ; fi
6725

    
6726
	# Cleanup ZFS dataset
6727
        isDirZFS "${PBI_CHROOTDIR}" "1"
6728
        if [ $? -eq 0 ] ; then
6729
   	     tank=`getZFSTank "$PBI_CHROOTDIR"`
6730
	     sleep 1
6731
	     # If we are running as a result of pbi_autobuild, let it do the ZFS cleanup
6732
	     if [ -z "${PBI_AB_TMPDIR}" ] ; then
6733
             	zfs destroy ${tank}${PBI_CHROOTDIR}
6734
  	     	rmdir ${PBI_CHROOTDIR} >/dev/null 2>/dev/null
6735
	     fi
6736
	     return
6737
        fi
6738

    
6739
	# Cleanup normal directory
6740
	rm -rf "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
6741
	chflags -R noschg ${PBI_CHROOTDIR} >/dev/null 2>/dev/null
6742
	rm -rf "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
6743
}
6744

    
6745
# Function which extracts the clean chroot environment for the PBI
6746
chroot_extract() {
6747

    
6748
	# If no freebsd base exists, make it first
6749
	isDirZFS "${PBI_APPDIR}"
6750
	if [ $? -eq 0 ] ; then
6751
		# Use ZFS base for cloning
6752
		PBI_CHROOTZFS="${PBI_APPDIR}/.pbi-world-$ARCH"
6753
		[ -e "${PBI_CHROOTZFS}/COPYRIGHT" ] || mk_chroot_file
6754
	else
6755
		# Use regular .txz file
6756
		PBI_CHROOTFILE="${PBI_APPDIR}/.pbi-world-$ARCH.txz"
6757
		[ -e "${PBI_CHROOTFILE}" ] || mk_chroot_file
6758
	fi
6759

    
6760
	# Set the chroot path
6761
	PBI_CHROOTDIR="${PBI_PROGDIRPATH}.chroot"
6762
	export PBI_CHROOTDIR
6763
	
6764
	# See if there is old chroot to clean first
6765
	chroot_make_cleanup
6766

    
6767
	# Create the new chroot dir
6768
	mkdir -p "${PBI_CHROOTDIR}"
6769

    
6770
	# If on ZFS, we can just clone our existing base system
6771
	if [ -n "$PBI_CHROOTZFS" ] ; then
6772
           tank=`getZFSTank "$PBI_CHROOTZFS"`
6773
	   echo "Cloning ${PBI_CHROOTZFS} -> ${PBI_CHROOTDIR}"
6774
	   if [ -n "${PBI_AB_TMPDIR}" ] ; then
6775
              echo "${tank}${PBI_CHROOTDIR}" > ${PBI_AB_TMPDIR}/${PBI_AB_BUILDER}.zmnt
6776
	   fi
6777
           zfs clone ${tank}${PBI_CHROOTZFS}@clean ${tank}${PBI_CHROOTDIR}
6778
	   if [ $? -ne 0 ] ; then exit_err "Failed creating clean ZFS base snapshot"; fi
6779
	else
6780
	   echo "Extracting chroot environment..."
6781
	   tar xvf ${PBI_CHROOTFILE} -C "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
6782
	   [ $? -ne 0 ] && exit_err "Failed extracting chroot environment!"
6783
	fi
6784

    
6785
	# If we plan on using TMPFS mount it now
6786
	mkdir -p ${PBI_CHROOTDIR}/usr/wrkdirprefix
6787
	if [ "$MKTMPFS" = "YES" ] ; then 
6788
		mount -t tmpfs tmpfs ${PBI_CHROOTDIR}/usr/wrkdirprefix
6789
	fi
6790

    
6791
	# Copy resolv.conf
6792
	cp /etc/resolv.conf ${PBI_CHROOTDIR}/etc/resolv.conf
6793

    
6794
	# Copy our binary wrapper
6795
	PBI_WRAPPERFILE="${PBI_APPDIR}/.pbiwrapper-$ARCH"
6796
	mkdir ${PBI_CHROOTDIR}${PBI_APPDIR} 2>/dev/null
6797
	cp ${PBI_WRAPPERFILE} ${PBI_CHROOTDIR}${PBI_WRAPPERFILE}
6798

    
6799
	# If we have a custom PBI_MAKECONF include it
6800
	[ -e "${PBI_MAKECONF}" ] && cp ${PBI_MAKECONF} ${PBI_CHROOTDIR}/etc/make.conf
6801

    
6802
	# Set any target arch vars
6803
        if [ "${ARCH}" = "i386" -a "${REALARCH}" = "amd64" ];then
6804
                LOGIN_ENV=",UNAME_p=i386,UNAME_m=i386"
6805
                cat >> ${PBI_CHROOTDIR}/etc/make.conf << EOF
6806
ARCH=i386
6807
MACHINE=i386
6808
MACHINE_ARCH=i386
6809
EOF
6810
        	sed -i .back -e "s/:\(setenv.*\):/:\1${LOGIN_ENV}:/" ${PBI_CHROOTDIR}/etc/login.conf
6811
        	cap_mkdb ${PBI_CHROOTDIR}/etc/login.conf
6812
        fi
6813

    
6814
	#echo "Copying ${PORTSDIR} -> ${PBI_CHROOTDIR}/usr/ports"
6815
	#tar cvf - -C "${PORTSDIR}" --exclude ./distfiles . 2>/dev/null | tar xvf - -C "${PBI_CHROOTDIR}/usr/ports" 2>/dev/null
6816
	[ -d "${PORTSDIR}/distfiles" ] || mkdir -p ${PORTSDIR}/distfiles
6817
	mkdir -p ${PBI_CHROOTDIR}/usr/ports 2>/dev/null
6818
	mount_nullfs ${PORTSDIR} ${PBI_CHROOTDIR}/usr/ports
6819

    
6820
	# Are we doing pkg caching?
6821
	if [ "$PBI_PKGCACHE" = "YES" ] ; then
6822
		mkdir ${PBI_CHROOTDIR}/pkgs
6823
		mount_nullfs ${PBI_PKGCACHEDIR} ${PBI_CHROOTDIR}/pkgs
6824
	fi
6825
	
6826
	# Now copy over the pbi_* scripts
6827
	mkdir ${PBI_CHROOTDIR}/usr/local/sbin 2>/dev/null
6828
	cp ${PROGBASE}/sbin/pbi_* ${PBI_CHROOTDIR}/usr/local/sbin
6829
	cp ${PBI_CHROOTDIR}/usr/local/sbin/pbi_makeport ${PBI_CHROOTDIR}/usr/local/sbin/pbi_makeport_chroot
6830
	chmod 755 ${PBI_CHROOTDIR}/usr/local/sbin/pbi_*
6831

    
6832
	# Copy the default icons
6833
	cp ${PBI_DEFAULT_ICON} ${PBI_CHROOTDIR}${PBI_DEFAULT_ICON_CHROOT}
6834

    
6835
	# Make sure the outgoing dir is created
6836
	mkdir -p ${PBI_CHROOTDIR}/pbiout 2>/dev/null
6837

    
6838
	# Copy over the PBI DB
6839
	mkdir -p ${PBI_CHROOTDIR}/var/db 2>/dev/null
6840
	cp -r ${PBI_DBDIR} ${PBI_CHROOTDIR}${PBI_DBDIR}
6841
	
6842
	# Copy over the confdir as well
6843
	if [ -n "${PBI_CONFDIR}" ] ; then
6844
		mkdir -p "${PBI_CHROOTDIR}/pbimodule"
6845
		echo "Copying ${PBI_CONFDIR} -> ${PBI_CHROOTDIR}/pbimodule"
6846
	 	tar cvf - -C "${PBI_CONFDIR}" . 2>/dev/null | tar xvf - -C "${PBI_CHROOTDIR}/pbimodule" 2>/dev/null
6847
	fi
6848

    
6849
	# Copy over the ssl priv key if used
6850
	if [ -n "$PBI_SSLPRIVKEY" ] ; then
6851
	 	cp "${PBI_SSLPRIVKEY}" "${PBI_CHROOTDIR}/privkey.pem"
6852
		chmod 600 "${PBI_CHROOTDIR}/privkey.pem"
6853
	fi
6854

    
6855
	# Check if we have a pre-make script to run
6856
	if [ -n "${PBI_PREMAKE_SCRIPT}" ] ; then
6857
		if [ -e "${PBI_PREMAKE_SCRIPT}" ] ; then
6858
			cp ${PBI_PREMAKE_SCRIPT} ${PBI_CHROOTDIR}/pre-build.sh
6859
		fi
6860
	fi
6861
	# Check if we have a post-make script to run
6862
	if [ -n "${PBI_POSTMAKE_SCRIPT}" ] ; then
6863
		if [ -e "${PBI_POSTMAKE_SCRIPT}" ] ; then
6864
			cp ${PBI_POSTMAKE_SCRIPT} ${PBI_CHROOTDIR}/post-build.sh
6865
		fi
6866
	fi
6867

    
6868
	# Start devfs in the chroot
6869
	if [ ! -d "${PBI_CHROOTDIR}/dev" ] ; then
6870
		mkdir ${PBI_CHROOTDIR}/dev
6871
	fi
6872
	mount -t devfs devfs ${PBI_CHROOTDIR}/dev
6873

    
6874
	# Mount linprocfs
6875
	mkdir -p ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
6876
	mount -t linprocfs linprocfs ${PBI_CHROOTDIR}/compat/linux/proc
6877

    
6878
	# Make sure the outgoing dir exists
6879
	mkdir -p ${PBI_CHROOTDIR}${PBI_CREATE_OUTDIR} >/dev/null 2>/dev/null
6880

    
6881
	# Check for ccache being enabled on the host and nullfs mount it to the chroot
6882
	if [ -n "${CCACHE_DIR}" -a -d "${CCACHE_DIR}" ] ; then
6883
		mkdir ${PBI_CHROOTDIR}/.ccache
6884
		mount_nullfs ${CCACHE_DIR} ${PBI_CHROOTDIR}/.ccache	
6885
	fi
6886

    
6887
}
6888

    
6889
# Get the default PC-BSD mirror to use
6890
get_pcbsd_mirror() {
6891

    
6892
  # Check if we already looked up a mirror we can keep using
6893
  if [ -n "$CACHED_PCBSD_MIRROR" ] ; then
6894
     VAL="$CACHED_PCBSD_MIRROR"
6895
     export VAL
6896
     return
6897
  fi
6898

    
6899
  # Set the mirror URL
6900
  VAL="`cat ${PCBSD_ETCCONF} 2>/dev/null | grep 'PCBSD_MIRROR: ' | sed 's|PCBSD_MIRROR: ||g'`"
6901
  if [ -n "$VAL" ] ; then
6902
     echo "Using mirror: $VAL"
6903
     CACHED_PCBSD_MIRROR="$VAL"
6904
     export VAL CACHED_PCBSD_MIRROR
6905
     return
6906
  fi
6907

    
6908
  echo "Getting regional mirror..."
6909
  . /etc/profile
6910

    
6911
  # No URL? Lets get one from the master server
6912
  local mFile="${HOME}/.mirrorUrl.$$"
6913
  touch $mFile
6914
  fetch -o $mFile http://getmirror.pcbsd.org >/dev/null 2>/dev/null
6915
  VAL="`cat $mFile | grep 'URL: ' | sed 's|URL: ||g'`"
6916
  rm $mFile
6917
  if [ -n "$VAL" ] ; then
6918
     echo "Using mirror: $VAL"
6919
     CACHED_PCBSD_MIRROR="$VAL"
6920
     export VAL CACHED_PCBSD_MIRROR
6921
     return
6922
  fi
6923

    
6924
  # Still no mirror? Lets try the PC-BSD FTP server...
6925
  VAL="ftp://ftp.pcbsd.org/pub/mirror"
6926
  CACHED_PCBSD_MIRROR="$VAL"
6927
  export VAL CACHED_PCBSD_MIRROR
6928
  echo "Using mirror: $VAL"
6929
  return 
6930
}
6931

    
6932
# No chroot environment tar file exists yet, lets build or extract
6933
mk_chroot_file() {
6934

    
6935
	# Check if on PC-BSD and we can instead fetch fbsd-release.txz
6936
	if [ -e "$PCBSD_ETCCONF" -a -z "$FORCE_FBSD_ONLY" ]; then
6937

    
6938
	  cd "$PBI_APPDIR"
6939

    
6940
	  # Set the mirror URL
6941
	  get_pcbsd_mirror
6942
          MIRRORURL="$VAL"
6943

    
6944
  	  # Get the system version we are checking for updates to
6945
  	  SYSVER="`pbreg get /PC-BSD/Version`" ; export SYSVER
6946

    
6947
  	  # To fetch the jail environment
6948
 	  echo "Fetching FreeBSD chroot environment... This may take a while..."
6949
  	  fetch -o rel-$ARCH.txz ${MIRRORURL}/${SYSVER}/${ARCH}/netinstall/fbsd-release.txz
6950
    	  fetch -o rel-$ARCH.md5 ${MIRRORURL}/${SYSVER}/${ARCH}/netinstall/fbsd-release.txz.md5
6951
  	  fetch -o src-$ARCH.txz ${MIRRORURL}/${SYSVER}/${ARCH}/netinstall/extras/components/src.txz
6952

    
6953
    	  [ `md5 -q rel-$ARCH.txz` != `cat rel-$ARCH.md5` ] && exit_err "Error in download data, checksum mismatch.. Please try again later."
6954

    
6955
	  isDirZFS "${PBI_APPDIR}"
6956
          if [ $? -eq 0 ] ; then   
6957
            # Use ZFS base for cloning
6958
	    echo "Creating ZFS ${PBI_CHROOTZFS} dataset..."
6959
            tank=`getZFSTank "$PBI_APPDIR"`
6960
	    isDirZFS "${PBI_CHROOTZFS}" "1"
6961
            if [ $? -ne 0 ] ; then   
6962
              zfs create -o mountpoint=${PBI_CHROOTZFS} -p ${tank}${PBI_CHROOTZFS}
6963
	      if [ $? -ne 0 ] ; then exit_err "Failed creating ZFS base dataset"; fi
6964
	    fi
6965
	    echo "Extracting rel-$ARCH.txz..."
6966
	    tar xvpf rel-$ARCH.txz -C ${PBI_CHROOTZFS} 2>/dev/null
6967
	    if [ $? -ne 0 ] ; then exit_err "Failed extracting ZFS base dataset"; fi
6968
	    mkdir -p ${PBI_CHROOTZFS}/usr/src 2>/dev/null
6969
	    echo "Extracting src-$ARCH.txz..."
6970
	    tar xvpf src-$ARCH.txz -C ${PBI_CHROOTZFS}/usr/src 2>/dev/null
6971
	    if [ $? -ne 0 ] ; then exit_err "Failed extracting ZFS base src dataset"; fi
6972
	    rm rel-$ARCH.txz
6973
	    rm src-$ARCH.txz
6974
	    rm rel-$ARCH.md5
6975
            zfs snapshot ${tank}${PBI_CHROOTZFS}@clean
6976
	    if [ $? -ne 0 ] ; then exit_err "Failed creating clean ZFS base snapshot"; fi
6977
	  else
6978
	    mv rel-$ARCH.txz ${PBI_CHROOTFILE}
6979
	    rm rel-$ARCH.md5
6980
	  fi
6981

    
6982
	  return
6983
 	fi
6984

    
6985
        local _srcdir="/usr/src"
6986
        if [ -z "${PBI_BUILDSRC}" ] ; then
6987
                PBI_BUILDSRC="${_srcdir}"
6988
        fi
6989

    
6990
        local _targetDir="${PBI_APPDIR}/.worldTarget.$$"
6991
        if [ -z "${PBI_BUILDTARGET}" ] ; then
6992
                PBI_BUILDTARGET="${_targetDir}"
6993
        fi
6994

    
6995
        # Delete source code/build if not /usr/src and PBI_DELETE_BUILD is true
6996
        if [ -z "${PBI_DELETE_BUILD}" ] ; then
6997
                PBI_DELETE_BUILD=1
6998
        fi
6999
 
7000
	# Use existing sources
7001
        if [ -e "${PBI_BUILDSRC}/COPYRIGHT" -a -z "${PBI_OSREL}" ] ; then
7002
		PBI_BUILDLOG="${PBI_APPDIR}/.buildWorldLog"
7003
		: > ${PBI_BUILDLOG}
7004
		mkdir -p "${PBI_BUILDTARGET}"
7005
	
7006
	else
7007
		# Make sure SVN is installed
7008
		which svn >/dev/null 2>/dev/null
7009
		[ "$?" -ne 0 ] && exit_err "Subversion is required to rebuild the chroot environment!"
7010

    
7011
                local _osRel=$FBSDREL
7012
                if [ -n "${PBI_OSREL}" ]; then
7013
                        _osRel="${PBI_OSREL}"
7014
                fi
7015

    
7016
		echo "Building the PBI chroot environment... This may take a while..."
7017
		PBI_BUILDLOG="${PBI_APPDIR}/.buildWorldLog"
7018
		echo "" > ${PBI_BUILDLOG}
7019
		mkdir -p "${PBI_BUILDSRC}"
7020
		mkdir -p "${PBI_BUILDTARGET}"
7021
	
7022
		# Figure out which version of FreeBSD to checkout
7023
		case $_osRel in
7024
			*RELEASE)
7025
				local _osMajor=${_osRel%%.*}
7026
				local svnUrl="svn://svn.freebsd.org/base/releng/${_osMajor}.0"
7027
				echo "Using $svnUrl for sources"
7028
				;;
7029
			*CURRENT)
7030
				local svnUrl="svn://svn.freebsd.org/base/head"
7031
				echo "Using $svnUrl for sources"
7032
				;;
7033
			*STABLE)
7034
				local _osMajor=${_osRel%%.*}
7035
				local svnUrl="svn://svn.freebsd.org/base/stable/${_osMajor}"
7036
				"Using $svnUrl for sources"
7037
				;;
7038
			*)
7039
				local svnUrl="svn://svn.freebsd.org/base/head"
7040
				echo "Using $svnUrl for sources"
7041
				echo "Assuming a BETA|RC or rarely used FreeBSD version. Using CURRENT!"
7042
				;;
7043
		esac
7044

    
7045
		echo "Checking out FreeBSD sources from $svnUrl"
7046
                if [ -e "${PBI_BUILDSRC}/COPYRIGHT" ] ; then
7047
                        svn update ${PBI_BUILDSRC} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7048
                else
7049
                        svn co ${svnUrl} ${PBI_BUILDSRC} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7050
                fi
7051

    
7052
                if [ "$?" != "0" ] ; then
7053
                        if [ "${PBI_DELETE_BUILD}" = "1" ] ; then
7054
                                rm -rf "${PBI_BUILDSRC}"
7055
                                rm -rf "${PBI_BUILDTARGET}"
7056
                        fi
7057
			exit_err "Subversion checkout failed! Logfile saved: ${PBI_BUILDLOG}"
7058
		fi
7059
	fi # End of subversion checkout
7060

    
7061
	echo "Running buildworld / installworld (into a chroot)"
7062
	touch ${PBI_BUILDSRC}/Makefile
7063
	cd ${PBI_BUILDSRC}
7064
        make ${PBI_BUILDFLAGS} TARGET=$ARCH buildworld >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7065
        if [ "$?" != "0" ] ; then
7066
                cd
7067
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7068
                        rm -rf "${PBI_BUILDSRC}"
7069
                        rm -rf "${PBI_BUILDTARGET}"
7070
                fi
7071
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
7072
        fi
7073

    
7074
	# See if we need to create a ZFS dataset
7075
	isDirZFS "${PBI_APPDIR}"
7076
        if [ $? -eq 0 ] ; then   
7077
            # Use ZFS base for cloning
7078
	    echo "Creating ZFS ${PBI_CHROOTZFS} dataset..."
7079
            tank=`getZFSTank "$PBI_APPDIR"`
7080
	    isDirZFS "${PBI_CHROOTZFS}" "1"
7081
            if [ $? -ne 0 ] ; then   
7082
              zfs create -o mountpoint=${PBI_CHROOTZFS} -p ${tank}${PBI_CHROOTZFS}
7083
	      if [ $? -ne 0 ] ; then exit_err "Failed creating ZFS base dataset"; fi
7084
	    fi
7085
            rmdir "${PBI_BUILDTARGET}"
7086
	    PBI_BUILDTARGET="$PBI_CHROOTZFS"
7087
	fi
7088

    
7089
        make ${PBI_BUILDFLAGS} installworld TARGET=$ARCH DESTDIR=${PBI_BUILDTARGET} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7090
        if [ "$?" != "0" ] ; then
7091
                cd
7092
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7093
                        rm -rf "${PBI_BUILDSRC}"
7094
                        rm -rf "${PBI_BUILDTARGET}"
7095
                fi
7096
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
7097
        fi
7098
        make ${PBI_BUILDFLAGS} distribution TARGET=$ARCH DESTDIR=${PBI_BUILDTARGET} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7099
        if [ "$?" != "0" ] ; then
7100
                cd
7101
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7102
                        rm -rf "${PBI_BUILDSRC}"
7103
                        rm -rf "${PBI_BUILDTARGET}"
7104
                fi
7105
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
7106
        fi
7107

    
7108
	# Copy the source since some ports need kern sources
7109
	echo "Copying FreeBSD sources to chroot environment"
7110
	mkdir -p ${PBI_BUILDTARGET}/usr/src >/dev/null 2>/dev/null
7111
	tar cvf - -C "${PBI_BUILDSRC}" --exclude "\.svn/" . 2>/dev/null | tar xvf - -C "${PBI_BUILDTARGET}/usr/src" 2>/dev/null
7112

    
7113
	# If using ZFS we can stop here
7114
	if [ -n "$PBI_CHROOTZFS" ] ; then
7115
           	zfs snapshot ${tank}${PBI_CHROOTZFS}@clean
7116
	    	if [ $? -ne 0 ] ; then exit_err "Failed creating clean ZFS base snapshot"; fi
7117
		rm ${PBI_BUILDLOG}
7118
		return
7119
	fi
7120

    
7121
	echo "Creating chroot environment tarball"
7122
	tar cvjf ${PBI_CHROOTFILE} -C ${PBI_BUILDTARGET} . >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
7123
	if [ $? -ne 0 ] ; then
7124
		cd
7125
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7126
                        rm -rf "${PBI_BUILDSRC}"
7127
                        rm -rf "${PBI_BUILDTARGET}"
7128
                fi
7129
		rm -rf "${PBI_CHROOTFILE}"
7130
		exit_err "Making chroot environment tarball failed! Logfile saved: ${PBI_BUILDLOG}"
7131
	fi
7132

    
7133
	# Cleanup after ourselves
7134
	chflags -R noschg "${PBI_BUILDTARGET}" >/dev/null 2>/dev/null
7135
        if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
7136
                rm -rf "${PBI_BUILDSRC}"
7137
        fi
7138
        if [ "${PBI_DELETE_BUILD}" = "1" ] ; then
7139
                rm -rf "${PBI_BUILDTARGET}" >/dev/null 2>/dev/null
7140
        fi
7141
	rm ${PBI_BUILDLOG}
7142
}
7143

    
7144
# Read the target ports plist, and generate a external_links config based upon it
7145
mk_auto_ext_linksfile() {
7146
	# Get ports name
7147
	get_pkgname "${PORTSDIR}/${PBI_MAKEPORT}"
7148
	_pname="${PKGNAME}"
7149

    
7150
	# Define some commands
7151
     	if [ $PKGNG -eq 1 ] ; then
7152
		pkgInf="pkg info -l"
7153
     	else
7154
		pkgInf="pkg_info -L"
7155
	fi
7156

    
7157
 	${pkgInf} ${_pname} | sed "s|^${PBI_PROGDIRPATH}/||g" \
7158
		| grep -v -e "^Information for" -e "^Files:" -e "owns the following" \
7159
		| tr -s '\t' ' ' \
7160
		| tr -d ' ' \
7161
		 > "${PBI_TMPDIR}/.pkg_flist.$$"
7162

    
7163
	_ef="${PBI_PROGDIRPATH}/${MOD_AUTOEXTLINKFILE}"
7164

    
7165
	[ -e "$_ef" ] && rm "$_ef"
7166

    
7167
	while read f
7168
	do
7169
		bin="NO"
7170
		[ -z "${f}" ] && continue
7171
		[ -e "${PBI_PROGDIRPATH}/${f}" ] || continue
7172

    
7173
		# See if this is executable and set it as binary
7174
		dirname ${f} | grep -e "bin" -e "sbin" >/dev/null 2>/dev/null
7175
		if [ -x "${PBI_PROGDIRPATH}/${f}" -a $? -eq 0 ] ; then
7176

    
7177
		   # Check this executable, if Linux binary, flag it
7178
		   file "${PBI_PROGDIRPATH}/${f}" | grep -iq "Linux"
7179
		   if [ $? -ne 0 ] ; then
7180
	  	      echo "${f}	${f}	binary,nocrash" >> "$_ef"
7181
		   else
7182
	  	      echo "${f}	${f}	linux,nocrash" >> "$_ef"
7183
 		   fi
7184
		else
7185
			echo "${f}	${f}	replace" >> "$_ef"
7186
		fi
7187
	done < ${PBI_TMPDIR}/.pkg_flist.$$
7188
	rm "${PBI_TMPDIR}/.pkg_flist.$$"
7189
}
7190

    
7191
# Init the crash handler routine
7192
pbi_crash_init() {
7193
	which "pbi-crashhandler-gui" >/dev/null 2>/dev/null
7194
	if [ "$?" = "0" -a -n "${DISPLAY}" ] ; then
7195
		#pbi-crashhandler-gui "$@"
7196
	fi
7197
}
7198

    
7199
# Get the hard-link counter for the specified file
7200
get_hard_link_count() {
7201
	HLINKS=`stat -f %l "${1}"`
7202
}
7203

    
7204
# Cleanup after caught exit
7205
exit_trap() {
7206
	# If a download is running, kill it
7207
	if [ -n  "${FETCH_PID}" ] ; then 
7208
	   echo "Killing ${FETCH_PID}"
7209
	   kill -s INT ${FETCH_PID}
7210
           sleep 2
7211
	fi
7212

    
7213
	# If we are running as an auto-build service we need to cleanup
7214
	if [ "`basename ${0}`" = "pbi_autobuild" ] ; then
7215
	   for j in `ls ${PBI_TMPDIR}/*.pid 2>/dev/null`
7216
	   do
7217
	      bNum=`basename $j | cut -d '.' -f 1 `
7218
	      if pgrep -qF "${j}" >/dev/null 2>&1; then 
7219
	         echo "===>Cleaning up processes [$bNum]"
7220
		 pkill -9 -P "`cat ${j}`"
7221
		 sleep 10 
7222
		 pkill -9 -F ${j}
7223
 		 sleep 10 
7224
		 # Do the ZFS destroy here, since running zfs destroy concurrently as we cleanup can cause a panic
7225
		 check_zfs_ab_destroy "$bNum"
7226
	      fi
7227
	   done
7228
	fi
7229

    
7230
        chroot_make_cleanup
7231
	rm_pbipatchfiles
7232
	rm_tmpdir
7233
	exit 0
7234
}
7235

    
7236
# Read in the global pbi.conf
7237
load_pbi_etcconf() {
7238

    
7239
	# FTP_PASSIVE_MODE needs to be enabled by default
7240
	FTP_PASSIVE_MODE=YES
7241
	export FTP_PASSIVE_MODE
7242

    
7243
	PBI_PUBKEYS="`ls ${PBI_DBKEYDIR}/*.ssl 2>/dev/null`"
7244

    
7245
	[ -e "${PBI_ETCCONF}" ] || return 0
7246

    
7247
	# See if we have a custom index refresh rate
7248
	_ckPBIIR="`sed -n 's/^PBI_INDEXREFRESH: //gp' ${PBI_ETCCONF}`"
7249
	if [ -n "${_ckPBIIR}" -a $(is_num "$_ckPBIIR") ] ; then 
7250
		PBI_INDEXREFRESH="${_ckPBIIR}"
7251
	fi
7252

    
7253
	# See if we have a custom pbid refresh time
7254
	_ckPBID="`cat ${PBI_ETCCONF} | grep '^PBID_REFRESH: ' | sed 's|PBID_REFRESH: ||g'`"
7255
	if [ -n "${_ckPBID}" -a $(is_num "$_ckPBID") ] ; then 
7256
		PBIDSLEEP="${_ckPBID}"
7257
	fi
7258

    
7259
}
7260

    
7261
# If the loaded file is a PBI PatchFile
7262
is_pbi_patch() {
7263
	if [ -z "$PBI_PATCHVERSION" ] ; then
7264
		return 1
7265
	else
7266
		return 0
7267
	fi
7268
}
7269

    
7270

    
7271
# Build the specified port
7272
do_port_build()
7273
{
7274
  local _lPort="$1"
7275

    
7276
  local iFile="$PORTSDIR/INDEX-$FBSDMAJOR"
7277
  if [ ! -e "$iFile" ] ; then
7278
     echo "Creating $iFile "
7279
     make -C ${PORTSDIR} index
7280
  fi
7281

    
7282
  echo "Checking port: $_lPort"
7283

    
7284
  # Make sure this port isn't already loaded
7285
  local pkgName=`make -V PKGNAME -C $_lPort PORTSDIR=${PORTSDIR}`
7286
  if [ $PKGNG -eq 1 ] ; then
7287
	pkg info -e ${pkgName}
7288
	if [ $? -eq 0 ] ; then return ; fi
7289
  else
7290
	if [ -e "/var/db/pkg/${pkgName}" ] ; then return ; fi
7291
  fi
7292

    
7293
  # Save any users / groups we need to create later
7294
  local pUsers="`make -V USERS -C $_lPort PORTSDIR=${PORTSDIR}`"
7295
  local pGroups="`make -V GROUPS -C $_lPort PORTSDIR=${PORTSDIR}`"
7296
  if [ -n "$pUsers" ] ; then
7297
     PBI_BUILD_USERS="$PBI_BUILD_USERS $pUsers"
7298
  fi
7299
  if [ -n "$pGroups" ] ; then
7300
     PBI_BUILD_GROUPS="$PBI_BUILD_GROUPS $pGroups"
7301
  fi
7302

    
7303
  # Parse the pkg deps 
7304
  for cPkg in `grep "^${pkgName}|" $iFile | cut -d '|' -f 8-9 | sed 's/|/ /g'`
7305
  do
7306
    if [ -z "$cPkg" ] ; then continue ; fi
7307

    
7308
    # is this installed?
7309
    if [ $PKGNG -eq 1 ] ; then
7310
	pkg info -e ${cPkg}
7311
        if [ $? -eq 0 ] ; then continue ; fi
7312
    else
7313
	if [ -e "/var/db/pkg/${cPkg}" ] ; then continue ; fi
7314
    fi
7315

    
7316
    local _port=`grep "^${cPkg}|" $iFile | cut -d '|' -f 2`
7317

    
7318
    # Not installed, do this one now until we drill down to the base
7319
    do_port_build "${_port}" >&1 2>&1
7320
  done
7321

    
7322
  if [ $PKGNG -eq 1 ] ; then
7323
  	pkgInf="pkg info -e"
7324
  	pkgDep="pkg info -d"
7325
  	pkgCreate="pkg create -f txz"
7326
  else
7327
  	pkgInf="pkg_info"
7328
  	pkgDep="pkg_info -r"
7329
  	pkgCreate="pkg_create -J -b"
7330
  fi
7331

    
7332
  # Not installed, see if we have a pkg to install instead
7333
  if [ -e "/pkgs/${pkgName}.txz" ] ; then
7334
     REBUILDPKG="NO"
7335
     echo "Checking package: ${pkgName}"
7336
     $pkgDep /pkgs/${pkgName}.txz | grep -v -e "^Information" -e "depends on:" -e "^Depends" | sed '/^$/d' | sed 's|Dependency: ||g' > /tmp/deps.$$
7337
     while read dLine
7338
     do
7339
     	$pkgInf $dLine >/dev/null 2>/dev/null
7340
        if [ $? -ne 0 ] ; then
7341
           echo "Package dependencies updated! Rebuilding port..."
7342
           REBUILDPKG="YES"
7343
	   break
7344
        fi
7345
     done < /tmp/deps.$$
7346
     rm /tmp/deps.$$
7347

    
7348
     # Fix some pkgs bugging us with license questions
7349
     PACKAGE_BUILDING=yes
7350
     export PACKAGE_BUILDING
7351

    
7352
     if [ "$REBUILDPKG" = "NO" ] ; then
7353
       echo "Adding package: ${pkgName}"
7354
       $PKG_ADD -f /pkgs/${pkgName}.txz
7355
       return
7356
     fi
7357
  fi
7358

    
7359
  # No package, lets do old-fashioned build
7360
  echo "Compiling port: ${_lPort}"
7361
  cd ${_lPort}
7362
  make rmconfig
7363
  make clean
7364
  make install
7365
  if [ "$?" != "0" ] ; then
7366
     echo "BUILDERROR1!!"
7367
     sleep 2
7368
     make install
7369
     if [ "$?" != "0" ] ; then
7370
	if [ "$MKDEBUG" = "YES" ] ; then
7371
  	  echo "Failed! Running /bin/sh for debugging, type 'exit' to finish."
7372
  	  /bin/sh
7373
	fi
7374
	make clean
7375
	exit_err "make install of ${PBI_MAKEPORT} failed!"
7376
     fi
7377
  fi
7378
  make clean
7379

    
7380
  # Are we caching packages?
7381
  if [ "${PBI_PKGCACHE}" = "YES" ] ; then
7382

    
7383
    # Prune outdated versions of cached pkg
7384
    local basePkgName
7385
    basePkgName="`echo ${pkgName} | rev | cut -d '-' -f 2- | rev`"
7386
    for rmPkg in `ls /pkgs/${basePkgName}* 2>/dev/null | sed 's|/pkgs/||g'`
7387
    do
7388
        testPkg="`echo ${rmPkg} | rev | cut -d '-' -f 2- | rev`"
7389
	if [ -n "$testPkg" -a "$testPkg" = "$basePkgName" ] ; then
7390
	   echo "Pruning old cache pkg: ${rmPkg}"
7391
	   rm /pkgs/${rmPkg}
7392
	fi
7393
    done
7394

    
7395
    # Create new pkg
7396
    ${pkgCreate} ${pkgName}
7397
    if [ $? -ne 0 ] ; then
7398
       exit_err "$pkgCreate ${pkgName} failed!"
7399
    fi
7400
    mv ${pkgName}.txz /pkgs/
7401
    sha256 -q /pkgs/${pkgName}.txz >/pkgs/${pkgName}.txz.sha256
7402
  fi
7403
};
7404

    
7405
# Check if the target directory is on ZFS
7406
# Arg1 = The dir to check
7407
# Arg2 = If set to 1, don't dig down to lower level directory
7408
isDirZFS() {
7409
  local _chkDir="$1"
7410
  while :
7411
  do
7412
     # Is this dir a ZFS mount
7413
     mount | grep -w "on $_chkDir " | grep -qw "(zfs," && return 0
7414
        
7415
     # Quit if not walking down
7416
     if [ "$2" = "1" ] ; then return 1 ; fi
7417
        
7418
     if [ "$_chkDir" = "/" ] ; then break ; fi
7419
     _chkDir=`dirname $_chkDir`
7420
  done
7421
 
7422
  return 1
7423
}
7424

    
7425
# Get the ZFS tank name for a directory
7426
# Arg1 = Directory to check
7427
getZFSTank() {
7428
  local _chkDir="$1"
7429
  while :
7430
  do
7431
     line=`mount | grep -w -e $_chkDir -e "(zfs,"`
7432
     mount | grep -qw -e $_chkDir -e "(zfs,"
7433
     if [ $? -eq 0 ] ; then
7434
        echo $line | cut -d '/' -f -1 | awk '{print $1}'
7435
        return 0
7436
     fi
7437

    
7438
     if [ "$_chkDir" = "/" ] ; then return 1 ; fi
7439
     _chkDir=`dirname $_chkDir`
7440
  done
7441

    
7442
  return 1
7443
}
7444

    
7445
# Main program operation
7446
##############################################################
7447
init_vars
7448
mk_required_dirs
7449
load_pbi_etcconf
7450

    
7451
trap exit_trap 1 2 3 9 15
7452

    
7453
# Figure out which mode we are running in
7454
case `basename ${0}` in
7455
   pbi_add) pbi_add_init "$@" ;;
7456
   pbi_addrepo) pbi_addrepo_init "$@" ;;
7457
   pbi_autobuild) pbi_autob_init "$@" ;;
7458
   pbi_browser) pbi_browser_init "$@" ;;
7459
   pbi_create) pbi_create_init "$@" ;;
7460
   pbi_deleterepo) pbi_deleterepo_init "$@" ;;
7461
   pbi_delete) pbi_delete_init "$@" ;;
7462
   pbi_icon) pbi_icon_init "$@" ;;
7463
   pbi_indextool) pbi_it_init "$@" ;;
7464
   pbi_info) pbi_info_init "$@" ;;
7465
   pbi_listrepo) pbi_listrepo_init "$@" ;;
7466
   pbi_makeport) pbi_make_init "$@" ;;
7467
   pbi_makeport_chroot) pbi_make_init "$@" ;;
7468
   pbi_makepatch) pbi_makepatch_init "$@" ;;
7469
   pbi_makerepo) pbi_makerepo_init "$@" ;;
7470
   pbi_metatool) pbi_mt_init "$@" ;;
7471
   pbi_patch) pbi_patch_init "$@" ;;
7472
   pbi_update) pbi_update_init "$@" ;;
7473
   pbi_update_hashdir) pbi_update_hashdir_init "$@" ;;
7474
   pbi-crashhandler) pbi_crash_init "$@" ;;
7475
   pbid) pbid_init "$@" ;;
7476
   *) echo "Error: Called with invalid basename!" ; exit_trap ;;
7477
esac
7478

    
7479
rm_tmpdir
7480
exit 0
(11-11/35)