Project

General

Profile

Download (197 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
  --genpatch   -- Generate patch files (*.pbp) from archived PBIs to current
64
  --keep <num> -- Keep <num> old versions in archive folder for each built PBI
65
  --prune      -- Remove files from 'outdir' that no longer have a module
66
  --pkgcache   -- Create and use a .txz pkg cache directory, in the <outdir> of each PBI
67
  --tmpfs      -- Use TMPFS for port WRKDIRPREFIX
68
  --sign key   -- Sign the PBI(s) with specified openssl key
69

    
70
EOF
71
        exit_trap
72
}
73

    
74

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

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

    
93
EOF
94
        exit_trap
95
}
96

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

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

    
105
EOF
106
        exit_trap
107
}
108

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

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

    
127
EOF
128
        exit_trap
129
}
130

    
131
usage_icon_pbi() {
132
        cat <<EOF
133
usage: `basename $0` [options] pbi
134

    
135
Options:
136
  add-desktop          -- Add desktop icons
137
  add-menu             -- Add menu icons
138
  add-mime             -- Add mime registration
139
  add-pathlnk          -- Add PATH links
140
  del-desktop          -- Remove desktop icons
141
  del-menu             -- Remove menu icons
142
  del-mime             -- Remove mime registration
143
  del-pathlnk          -- Remove PATH links
144

    
145
EOF
146
        exit_trap
147
}
148

    
149
usage_info_pbi() {
150
        cat <<EOF
151
usage: `basename $0` [options] pbi
152

    
153
Options:
154
  -a             -- Show all installed PBIs
155
  -v             -- Enable verbose output
156

    
157
EOF
158
        exit_trap
159
}
160

    
161
usage_makepatch_pbi() {
162
        cat <<EOF
163
usage: `basename $0` [options] oldpbi newpbi
164
                
165
Options:
166
  -o outdir      -- Save the .PBP file to outdir
167
  --sign key     -- Sign the PBI with specified openssl key
168
  --no-checksig  -- Ignore signature verification and force install
169

    
170

    
171
EOF
172
        exit_trap
173
}
174

    
175
usage_addrepo_pbi() {
176
        cat <<EOF
177
usage: `basename $0` <Repo File>
178
                
179
EOF
180
        exit_trap
181
}
182

    
183
usage_deleterepo_pbi() {
184
        cat <<EOF
185
usage: `basename $0` <Repo ID>
186
                
187
EOF
188
        exit_trap
189
}
190

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

    
211
EOF
212
	exit_trap
213
}
214

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

    
226
EOF
227
	exit_trap
228
}
229

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

    
239
EOF
240
	exit_trap
241
}
242

    
243

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

    
254
EOF
255
	exit_trap
256
}
257

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

    
266
EOF
267
	exit_trap
268
}
269

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

    
278
EOF
279
	exit_trap
280
}
281

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

    
291
EOF
292
        exit_trap
293
}
294

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

    
304
EOF
305
        exit_trap
306
}
307

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

    
319
EOF
320
        exit_trap
321
}
322

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

    
336
EOF
337
        exit_trap
338
}
339

    
340
# update usage
341
usage_update_pbi() {
342
        cat <<EOF
343
usage: `basename $0` [options] pbi
344

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

    
352
EOF
353
        exit_trap
354
}
355

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

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

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

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

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

    
469
        if [ -z "${PBI_FILENAME}" ]; then usage_makepatch_pbi ; fi
470
        if [ -z "${PBI_OLDFILENAME}" ]; then usage_makepatch_pbi ; fi
471
        if [ -z "${PBI_PATCHOUTDIR}" ]; then PBI_PATCHOUTDIR=`pwd` ; fi
472

    
473
        # Load all the information about this PBI / PBP
474
        load_info_from_header
475
}
476

    
477
# Parse the command line for editing a meta file
478
parse_mt_pbi_cmdline() {
479

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

    
542
 	if [ ! -f "${PBI_MT_METAFILE}" ] ; then 
543
		exit_err "No such file ${PBI_MT_METAFILE}"
544
        fi
545

    
546
	# Sanity check the values
547
	case ${PBI_MT_MODE} in
548
		ADD) # Check the common values 
549
		     if [ -z "${PBI_MT_ADDNAME}" ] ; then usage_mt_add ; fi
550
		     if [ -z "${PBI_MT_ADDICON}" ] ; then usage_mt_add ; fi
551
		     if [ -z "${PBI_MT_ADDDESC}" ] ; then usage_mt_add ; fi
552

    
553
	 	     if [ "$PBI_MT_TYPE" = "CAT" ]; then	      
554
		     elif [ "$PBI_MT_TYPE" = "APP" ]; then
555
		     	if [ -z "${PBI_MT_ADDCAT}" ]; then usage_mt_add ; fi
556
		     	if [ -z "${PBI_MT_ADDAUTHOR}" ]; then usage_mt_add ; fi
557
		     	if [ -z "${PBI_MT_ADDURL}" ]; then usage_mt_add ; fi
558
		     	if [ -z "${PBI_MT_ADDLIC}" ]; then usage_mt_add ; fi
559
		     	if [ -z "${PBI_MT_ADDTYPE}" ]; then usage_mt_add ; fi
560
		     	if [ -z "${PBI_MT_ADDKEYWORDS}" ]; then usage_mt_add;fi
561
		     else
562
		       usage_mt_add
563
		     fi
564
		;;
565
		REM) if [ "$PBI_MT_TYPE" != "CAT" -a "$PBI_MT_TYPE" != "APP" ]
566
		     then
567
		        usage_mt_rem
568
		     fi
569
		     if [ -z "${PBI_MT_REMNAME}" ] ; then usage_mt_rem ; fi
570
		;;
571
	esac
572

    
573
}
574

    
575
# Parse the command line for editing a index file
576
parse_it_pbi_cmdline() {
577

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

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

    
648
}
649

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

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

    
684
	PBI_BROWSE_REPOMD5=`ls ${PBI_DBREPODIR}/${PBI_BROWSE_RID}.* 2>/dev/null | cut -d '.' -f 2`
685
	PBI_BROWSE_METAFILE=`ls ${PBI_DBINDEXDIR}/${PBI_BROWSE_REPOMD5}*meta 2>/dev/null`
686
	if [ -z "${PBI_BROWSE_METAFILE}" ] ; then
687
		exit_err "The specified repo has no meta-file."
688
	fi
689

    
690
}
691

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

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

    
721
	if [ -n "${PBI_LISTREPO_ID}" ] ; then
722
		ls ${PBI_DBREPODIR}/${PBI_LISTREPO_ID}.* >/dev/null 2>/dev/null
723
		if [ "$?" != "0" ] ; then
724
			exit_err "The specified repoid ${PBI_LISTREPO_ID} does not exist!"
725
		fi
726
	fi
727
}
728

    
729
# Parse the command line for adding a new repo file
730
parse_addrepo_pbi_cmdline() {
731
        while [ $# -gt 0 ]; do
732
                case "$1" in
733
                 *)	if [ $# -gt 1  ]; then usage_addrepo_pbi; fi
734
                       	PBI_ADDREPO_FILE="$1"
735
                        ;;
736
                esac
737
                shift
738
        done
739

    
740
	if [ -z "$PBI_ADDREPO_FILE" ] ; then 
741
		usage_addrepo_pbi
742
	fi
743
	if [ ! -f "$PBI_ADDREPO_FILE" ] ; then 
744
		exit_err "Repo file ${PBI_ADDREPO_FILE} does not exist!"
745
	fi
746
}
747

    
748
# Parse the command line for deleting a repo
749
parse_deleterepo_pbi_cmdline() {
750
        while [ $# -gt 0 ]; do
751
                case "$1" in
752
                 *)	if [ $# -gt 1  ]; then usage_deleterepo_pbi; fi
753
                       	PBI_DELREPO_ID="$1"
754
                        ;;
755
                esac
756
                shift
757
        done
758

    
759
	if [ -z "$PBI_DELREPO_ID" ] ; then 
760
		usage_deleterepo_pbi
761
	fi
762
}
763

    
764

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

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

    
802
}
803

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

    
829
        if [ -z "${PBI_FILENAME}" ]; then usage_patch_pbi ; fi
830

    
831
	# Get the absolute patch to the file
832
        get_abspath "$PBI_FILENAME"
833
	PBI_FILENAME="$_ABSPATH"
834

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

    
837
        # Load all the information about this PBI / PBP
838
        load_info_from_header
839

    
840
	# Make sure this isn't a patch file
841
	is_pbi_patch
842
	if [ "$?" = "1" ] ; then
843
		exit_err "This is not a PBP patch file"
844
	fi
845

    
846
        if [ -z "${PBI_ORIGPROGDIRPATH}" ]; then usage_patch_pbi ; fi
847

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

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

    
915
        if [ -z "${PBI_FILENAME}" ]; then usage_add_pbi ; fi
916

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

    
928
		# Start fetching file
929
		pbi_add_fetch_remote
930
	
931
	fi
932

    
933
        # Load all the information about this PBI
934
        load_info_from_header
935

    
936
        if [ -z "${PBI_ORIGPROGDIRPATH}" ]; then usage_add_pbi ; fi
937

    
938
	# Make sure this isn't a patch file
939
	is_pbi_patch
940
	if [ "$?" = "0" ] ; then
941
		exit_err "This is a PBP patch file, use 'pbi_patch' instead"
942
	fi
943

    
944
        # Lastly set PBI_PROGDIRNAME
945
        PBI_PROGDIRNAME="`echo ${PBI_ORIGPROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
946

    
947

    
948
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then
949
		# If extracting to a alt-outdir, set it now
950
		PBI_PROGDIRPATH="`pwd`/${PBI_PROGDIRNAME}"
951

    
952
		if [ -n "${PBI_ALTEXTRACT_DIR}" ]; then
953
			PBI_PROGDIRPATH="${PBI_ALTEXTRACT_DIR}/${PBI_PROGDIRNAME}"
954
		fi
955
	else
956
		# Set the installation dir
957
		PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}"
958
	fi
959
}
960

    
961
# Parse the command line
962
parse_autob_pbi_cmdline() {
963
        while [ $# -gt 0 ]; do
964
                case "$1" in
965
                -c)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
966
                        if [ -n "${PBI_AB_CONFDIR}" ]; then usage_autob_pbi; fi
967
                        shift
968
                        get_abspath "$1"
969
                        PBI_AB_CONFDIR="$_ABSPATH"
970
                        if [ ! -d "${PBI_AB_CONFDIR}" ] ; then
971
                                exit_err "Invalid confdir (${PBI_AB_CONFDIR})"
972
                        fi
973
                        ;;
974
                -d)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
975
                        shift
976
                        get_abspath "$1"
977
                        PORTSDIR="$_ABSPATH"
978
                        ;;
979
                -o)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
980
                        shift
981
                        get_abspath "$1"
982
                        PBI_AB_OUTDIR="$_ABSPATH"
983
                        ;;
984
                -h)	if [ $# -eq 1 ]; then usage_autob_pbi; fi
985
                        shift
986
                        get_abspath "$1"
987
                        PBI_AB_HELPS="$_ABSPATH"
988
                        ;;
989

    
990
        --genpatch)     PBI_AB_GENPATCH="YES" 
991
                        ;;
992
        --pkgcache)     PBI_AB_PKGCACHE="YES" 
993
                        ;;
994
            --keep)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
995
                        shift; PBI_AB_ARCHIVENUM="$1"
996
			expr $PBI_AB_ARCHIVENUM + 1 >/dev/null 2>/dev/null
997
			if [ $? != 0 ] ; then usage_autob_pbi; fi
998
                        ;;
999
           --prune)     PBI_AB_PRUNE="YES" 
1000
                        ;;
1001
           --tmpfs)     PBI_AB_TMPFS="YES" 
1002
                        ;;
1003
            --sign)     if [ $# -eq 1 ]; then usage_autob_pbi; fi
1004
                        shift; PBI_AB_SSLPRIVKEY="$1"
1005
                        ;;
1006
                 *)     usage_autob_pbi ;;
1007
                esac
1008
                shift
1009
        done
1010

    
1011
	if [ -z "$PBI_AB_OUTDIR" ] ; then usage_autob_pbi ; fi
1012
	if [ -z "$PBI_AB_CONFDIR" ] ; then usage_autob_pbi ; fi
1013
}
1014

    
1015

    
1016
# Parse the command line
1017
parse_create_pbi_cmdline() {
1018
        while [ $# -gt 0 ]; do
1019
                case "$1" in
1020
                -a)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1021
                        shift; PBI_CAUTHOR="$1"
1022
                        ;;
1023
                -b)     PBI_CBACKUP="YES"
1024
                        ;;
1025
                -c)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1026
                        shift; 
1027
			get_abspath "$1"
1028
			PBI_CONFDIR="$_ABSPATH"
1029
			if [ ! -d "${PBI_CONFDIR}" ] ; then
1030
				exit_err "Invalid confdir (${PBI_CONFDIR})"
1031
			fi
1032
                        ;;
1033
                -d)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1034
                        shift; PORTSDIR="$1"
1035
                        ;;
1036
                -i)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1037
                        shift; PBI_CICON="$1"
1038
                        ;;
1039
                -n)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1040
                        shift; PBI_CNAME="$1"
1041
                        ;;
1042
                -o)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1043
                        shift; PBI_CREATE_OUTDIR="$1"
1044
                        ;;
1045
                -p)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1046
                        shift; PBI_MAKEPORT="$1"
1047
                        ;;
1048
                -r)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1049
                        shift; PBI_CVERSION="$1"
1050
                        ;;
1051
                -w)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1052
                        shift; PBI_CWEB="$1"
1053
                        ;;
1054
         --no-hash)     PBI_DISABLEHASHDIR="YES" ;;
1055
            --sign)	if [ $# -eq 1 ]; then usage_create_pbi; fi
1056
                        shift; PBI_SSLPRIVKEY="$1"
1057
                        ;;
1058
                 *)
1059
                        if [ $# -gt 1 ]; then usage_create_pbi; fi
1060
			if [ "$PBI_CBACKUP" = "YES" ] ; then
1061
				if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
1062
                       	        	exit_err "can't find installed pbi (${1})"
1063
                        	fi
1064
				PBI_CBACKUPTARGET="${1}"
1065
				PBI_PROGDIRPATH="${1}"
1066
			else
1067
				get_abspath "$1"
1068
				PBI_PROGDIRPATH="$_ABSPATH"
1069
                        	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then
1070
                                	exit_err "Invalid pbidir (${1})"
1071
                          	fi
1072
			fi
1073
                        ;;
1074
                esac
1075
                shift
1076
        done
1077

    
1078
	# Make sure this port exists
1079
        if [ -n "${PBI_MAKEPORT}" -a ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ]; then
1080
		exit_err "No port (${PORTSDIR}/${PBI_MAKEPORT})"
1081
	fi
1082

    
1083
	# Load the name / version from specified port
1084
        if [ -n "${PBI_MAKEPORT}" ]; then
1085
		get_pbi_progversion
1086
		get_pbi_progname
1087
        fi
1088

    
1089
        if [ -z "${PBI_PROGDIRPATH}" ]; then usage_create_pbi ; fi
1090

    
1091
	# Lastly set PBI_PROGDIRNAME
1092
	PBI_PROGDIRNAME="`echo ${PBI_PROGDIRPATH} | rev | cut -d '/' -f 1 | rev`"
1093
}
1094

    
1095
# Override any pbi.conf values with passed command-line values
1096
parse_cmdline_overrides() {
1097
	if [ -n "${PBI_CNAME}" ] ; then PBI_PROGNAME="${PBI_CNAME}" ; fi
1098
	if [ -n "${PBI_CVERSION}" ] ; then PBI_PROGVERSION="${PBI_CVERSION}" ; fi
1099
	if [ -n "${PBI_CWEB}" ] ; then PBI_PROGWEB="${PBI_CWEB}" ; fi
1100
	if [ -n "${PBI_CAUTHOR}" ] ; then PBI_PROGAUTHOR="${PBI_CAUTHOR}" ; fi
1101
	if [ -n "${PBI_CICON}" ] ; then PBI_PROGICON="${PBI_CICON}" ; fi
1102
}
1103

    
1104
# Parse the command line
1105
parse_make_pbi_cmdline() {
1106
        while [ $# -gt 0 ]; do
1107
                case "$1" in
1108
                -B)	PBI_BUILDONLY="YES"
1109
                        ;;
1110
                -c)
1111
                        if [ $# -eq 1 ]; then usage_make_pbi; fi
1112
                        if [ -n "${PBI_CONFDIR}" ]; then usage_make_pbi; fi
1113
                        shift
1114
			get_abspath "$1"
1115
			PBI_CONFDIR="$_ABSPATH"
1116
                        ;;
1117
                -d)
1118
                        if [ $# -eq 1 ]; then usage_make_pbi; fi
1119
                        shift; PORTSDIR="$1" ; export PORTSDIR
1120
                        ;;
1121

    
1122
                -k)	PBI_KEEPBUILDFILES="YES"
1123
                        ;;
1124

    
1125
                --delbuild)	MKDELBUILD="YES"
1126
                        ;;
1127
                --no-prune)	PBI_PRUNEBUILDPORTS="NO"
1128
                        ;;
1129
                --mkdebug)	MKDEBUG="YES"
1130
                        ;;
1131
                --tmpfs)	MKTMPFS="YES"
1132
                        ;;
1133
                -o)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1134
                        shift
1135
			get_abspath "$1"
1136
			PBI_CREATE_OUTDIR="$_ABSPATH"
1137
                        ;;
1138
                -p)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1139
                        if [ -n "${PBI_MAKEPREFIX}" ]; then usage_make_pbi; fi
1140
                        shift; PBI_MAKEPREFIX="$1"
1141
                        ;;
1142
            --pkgdir)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1143
			shift
1144
			get_abspath "$1"
1145
			PBI_PKGCACHEDIR="$_ABSPATH"
1146
			PBI_PKGCACHE="YES"
1147
                        ;;
1148
            --sign)	if [ $# -eq 1 ]; then usage_make_pbi; fi
1149
			shift
1150
			get_abspath "$1"
1151
			PBI_SSLPRIVKEY="$_ABSPATH"
1152
                        ;;
1153
                 *)
1154
                        if [ $# -gt 1 ]; then usage_make_pbi; fi
1155
                        PBI_MAKEPORT="$1"
1156
                        ;;
1157
                esac
1158
                shift
1159
        done
1160

    
1161
	# Override some locations if working in chroot environment
1162
	if [ "`basename $0`" = "pbi_makeport_chroot" ] ; then 
1163
		if [ -n "${PBI_CONFDIR}" ] ; then PBI_CONFDIR="/pbimodule" ; fi
1164
		if [ -n "${PBI_SSLPRIVKEY}" ] ; then PBI_SSLPRIVKEY="/privkey.pem" ; fi
1165
		if [ -n "${PBI_CREATE_OUTDIR}" ] ; then PBI_CREATE_OUTDIR="/pbiout" ; fi
1166
		if [ -n "${PORTSDIR}" ] ; then PORTSDIR="/usr/ports" ; fi
1167
	else
1168
	# If running as pbi_makeport
1169

    
1170
		# Make sure the PBI_PKGCACHEDIR exists
1171
		if [ -n "${PBI_PKGCACHEDIR}" -a ! -d "${PBI_PKGCACHEDIR}" ] ; then
1172
			exit_err "No such directory: ${PBI_PKGCACHEDIR}"
1173
		fi
1174
	fi
1175

    
1176

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

    
1182
	# Make sure we have a valid PBI_CONFDIR
1183
	if [ -n "${PBI_CONFDIR}" -a ! -d "${PBI_CONFDIR}" ] ; then
1184
		exit_err "Invalid confdir (${PBI_CONFDIR})"
1185
	fi
1186

    
1187
	# Source the config file
1188
	if [ -n "${PBI_CONFDIR}" ]; then load_pbi_conffile ; fi
1189

    
1190
        if [ -z "${PBI_MAKEPORT}" ]; then
1191
                usage_make_pbi
1192
        fi
1193
}
1194

    
1195
# Parse the update command line
1196
parse_update_pbi_cmdline() {
1197
        while [ $# -gt 0 ]; do
1198
                case "$1" in
1199
                -c)	PBI_UPCHECK="YES" ;; 
1200
       --check-all)	PBI_UPCHECK="ALL" ;; 
1201
    --disable-auto)	PBI_UPENABLEAUTO="NO" ;; 
1202
     --enable-auto)	PBI_UPENABLEAUTO="YES" ;; 
1203
      --update-all)	PBI_UPDATEAPP="ALL" ;; 
1204
                 *)     if [ $# -gt 1 ]; then usage_update_pbi; fi
1205
			if [ -n "$PBI_UPDATEAPP" ] ; then usage_update_pbi ; fi
1206
			if [ ! -e "${PBI_DBAPPDIR}/${1}" ] ; then
1207
                                exit_err "can't find installed pbi (${1})"
1208
                        fi
1209
                        PBI_UPDATEAPP="$1"
1210
                        ;;
1211
                esac
1212
                shift
1213
        done
1214

    
1215
	if [ "${PBI_UPDATEAPP}" = "ALL" -a -n "${PBI_UPCHECK}" ] ; then
1216
                usage_update_pbi
1217
        fi
1218

    
1219
	# Make sure we aren't trying to enable auto-updating for ALL
1220
	if [ "${PBI_UPDATEAPP}" = "ALL" -a -n "${PBI_UPENABLEAUTO}" ] ; then
1221
                usage_update_pbi
1222
        fi
1223
	if [ -z "${PBI_UPDATEAPP}" -a -n "${PBI_UPENABLEAUTO}" ] ; then
1224
                usage_update_pbi
1225
        fi
1226

    
1227
        if [ -z "${PBI_UPDATEAPP}" -a "${PBI_UPCHECK}" != "ALL" ]; then
1228
                usage_update_pbi
1229
        fi
1230
}
1231

    
1232
# Make some of our required PBI dirs
1233
mk_required_dirs() {
1234
	if [ ! -d "${PBI_APPDIR}" ] ; then mkdir -p ${PBI_APPDIR} >/dev/null 2>/dev/null ; fi
1235
	if [ ! -d "${PBI_RCDIR}" ] ; then mkdir -p ${PBI_RCDIR} >/dev/null 2>/dev/null ; fi
1236
	if [ ! -d "${PBI_HASHDIR}" ] ; then mkdir -p ${PBI_HASHDIR} >/dev/null 2>/dev/null ; fi
1237
	if [ ! -d "${PBI_DBAPPDIR}" ] ; then mkdir -p ${PBI_DBAPPDIR} >/dev/null 2>/dev/null ; fi
1238
	if [ ! -d "${PBI_DBKEYDIR}" ] ; then mkdir -p ${PBI_DBKEYDIR} >/dev/null 2>/dev/null ; fi
1239
	if [ ! -d "${PBI_DBMIRRORDIR}" ] ; then mkdir -p ${PBI_DBMIRRORDIR} >/dev/null 2>/dev/null ; fi
1240
	if [ ! -d "${PBI_DBICONDIR}" ] ; then mkdir -p ${PBI_DBICONDIR} >/dev/null 2>/dev/null ; fi
1241
	if [ ! -d "${PBI_DBINDEXDIR}" ] ; then mkdir -p ${PBI_DBINDEXDIR} >/dev/null 2>/dev/null ; fi
1242
	if [ ! -d "${PBI_DBREPODIR}" ] ; then mkdir -p ${PBI_DBREPODIR} >/dev/null 2>/dev/null ; fi
1243
	if [ ! -d "${PBI_DBHASHQUEUEDIR}" ] ; then mkdir -p ${PBI_DBHASHQUEUEDIR} >/dev/null 2>/dev/null ; fi
1244

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

    
1248
	for cDir in $PBI_APPDIR $PBI_DBAPPDIR $PBI_DBHASHQUEUEDIR
1249
	do	
1250
		chown root:${PBI_INSTALLGROUP} ${cDir}
1251
		chmod 775 ${cDir}
1252
	done
1253

    
1254
	# Make sure the hash-dirty file can be written to by all
1255
	touch ${PBI_DBDIRTYFILE}
1256
	chown root:${PBI_INSTALLGROUP} ${PBI_DBDIRTYFILE}
1257
	chmod 664 ${PBI_DBDIRTYFILE}
1258
}
1259

    
1260
# Get the absolute path of a dir, even a realative dir. 'realpath' doesn't work here
1261
get_abspath() {
1262
	D=`dirname "$1"`
1263
	B=`basename "$1"`
1264
	if [ "$D" = "/" ] ; then
1265
		_ABSPATH="/$B"
1266
	else
1267
		_ABSPATH="`cd \"$D\" 2>/dev/null && pwd || echo \"$D\"`/$B"
1268
	fi
1269
}
1270

    
1271

    
1272
# Initialize some vars
1273
init_vars() {
1274

    
1275
        # Where is pbi-manager installed?
1276
	FBSDMAJOR=`uname -r | cut -c 1`
1277
        PROGBASE="/usr/local" 
1278
	SYS_LOCALBASE="/usr/local"
1279
	if [ -z "${PBI_APPDIR}" -o "`basename $0`" = "pbi_makeport_chroot" ] ; then
1280
		PBI_APPDIR="/usr/pbi"
1281
        fi
1282
	PBI_WRAPPERFILE="${PBI_APPDIR}/.pbiwrapper"
1283
	PBI_CHROOTFILE="${PBI_APPDIR}/.pbi-world.txz"
1284
	if [ `id -u` = "0" ] ; then 
1285
		PBI_HASHDIR="${PBI_APPDIR}/.hashdir"
1286
	else
1287
		PBI_HASHDIR="${PBI_APPDIR}/.hashdir-`whoami`"
1288
	fi
1289
	PBI_RCDIR="${SYS_LOCALBASE}/etc/rc.d"
1290
	PBI_ETCCONF="${SYS_LOCALBASE}/etc/pbi.conf"
1291
	PCBSD_ETCCONF="${SYS_LOCALBASE}/etc/pcbsd.conf"
1292
	PBI_DEFAULT_ICON="${PROGBASE}/share/pbi-manager/icons/default.png"
1293
	PBI_DEFAULT_ICON_CHROOT="/default.png"
1294
	PBI_PATCH_ICON="${PROGBASE}/share/pbi-manager/icons/patch.png"
1295
	PBI_LDCONFIGFILE="${PROGBASE}/etc/ldpbiconfig"
1296
	PBI_LDCONFIGRC="${PROGBASE}/etc/rc.d/ldpbiconfig"
1297
	PROGVERSION="1.0"
1298
	PBIDSLEEP="300"		# Amount of time to sleep before waking up pbid
1299
	PBI_LOG_LINES="500"
1300
	PBI_INSTALLGROUP="operator"
1301

    
1302
	# What dirs do we build hash-lists of
1303
	HASH_SEARCH_DIRS="lib kde4/lib share include info man"
1304

    
1305
	# What dbus dirs do we parse for setting up services
1306
	DBUS_SEARCH_DIRS="share/dbus-1 kde4/share/dbus-1 gnome/share/dbus-1"
1307

    
1308
	# Don't modify unless you know what your doing!
1309
	MOD_PREINS="pre-install.sh"
1310
	MOD_POSTINS="post-install.sh"
1311
	MOD_PREREM="pre-remove.sh"
1312
	MOD_XDGDESK_DIR="xdg-desktop"
1313
	MOD_XDGMENU_DIR="xdg-menu"
1314
	MOD_XDGMIME_DIR="xdg-mime"
1315
	MOD_EXTLINKFILE="external-links"
1316
	MOD_AUTOEXTLINKFILE=".auto-external-links"
1317
	PBI_ADD_GUIDISPLAY="NO"
1318
	PBI_ADD_INFODISPLAY="NO"
1319
	PBI_ADD_LICDISPLAY="NO"
1320
	PBI_APPDESK_DIR=".${MOD_XDGDESK_DIR}"
1321
	PBI_APPMENU_DIR=".${MOD_XDGMENU_DIR}"
1322
	PBI_APPMIME_DIR=".${MOD_XDGMIME_DIR}"
1323
	PBI_BUILD_USERS=""
1324
	PBI_BUILD_GROUPS=""
1325
	PBI_INS_USERSFILE=".pbi-uids"
1326
	PBI_INS_GROUPSFILE=".pbi-gids"
1327
	PBI_DESKADD="NO"
1328
	PBI_MENUADD="NO"
1329
	PBI_MIMEADD="NO"
1330
	PBI_PATHADD="NO"
1331
	PBI_DESKDEL="NO"
1332
	PBI_MAKECONF="/etc/pbi-make.conf"
1333
	PBI_MENUDEL="NO"
1334
	PBI_MIMEDEL="NO"
1335
	PBI_PATHDEL="NO"
1336
	PBI_DELETENAME=""
1337
	PBI_FAKEBIN_DIR=".sbin"
1338
	PBI_FILENAME=""
1339
	PBI_FORCEADD="NO"
1340
	PBI_HASHLIST=".pbi-hash-list"
1341
	PBI_INDEXREFRESH="24" # Hours to wait until we re-download PBI indexes
1342
	PBI_INDEXUPFILE="pbi-index-$FBSDMAJOR"
1343
	PBI_METAUPFILE="pbi-meta-$FBSDMAJOR"
1344
	PBI_INFONAME=""
1345
	PBI_INS_DESKSCRIPT="install-desktop-icons.sh"
1346
	PBI_INS_MENUSCRIPT="install-menu-icons.sh"
1347
	PBI_INS_MIMESCRIPT="install-mime.sh"
1348
	PBI_INS_PATHSCRIPT="install-pathlinks.sh"
1349
	PBI_LISTREPO_UP=""
1350
	PBI_LISTREPO_DOWN=""
1351
	PBI_LISTREPO_MIRROR=""
1352
	PBI_LICAGREE="NO"
1353
	PBI_LICENSEFILE="LICENSE"
1354
	PBI_PATCHVERSION=""
1355
	PBI_PATCHTARGET=""
1356
	PBI_REMOTEFETCH=""
1357
	PBI_REMOTEFETCHONLY=""
1358
	PBI_RESOURCE_DIR="resources"
1359
	PBI_SS_ICON="__PBI_ICON__"
1360
	PBI_SS_ARCHIVE="__PBI_ARCHIVE__"
1361
	PBI_SSLPRIVKEY=""
1362
	PBI_TMPDIR="/tmp/.PBI.$$"
1363
	PBI_TMPHASHLIST=""
1364
	PBI_UPCHECK=""
1365
	PBI_UPDATEAPP=""
1366
	PBI_UNINS_DESKSCRIPT="uninstall-desktop-icons.sh"
1367
	PBI_UNINS_MENUSCRIPT="uninstall-menu-icons.sh"
1368
	PBI_UNINS_MIMESCRIPT="uninstall-mime.sh"
1369
	PBI_UNINS_PATHSCRIPT="uninstall-pathlinks.sh"
1370

    
1371
        # User overridable variables
1372
	MKDELBUILD=""
1373
	MKDEBUG=""
1374
	MKTMPFS=""
1375
	PBI_AB_ARCHIVENUM=""
1376
	PBI_AB_CONFDIR=""
1377
	PBI_AB_GENPATCH="NO"
1378
	PBI_AB_HELPS=""
1379
	PBI_AB_OUTDIR=""
1380
	PBI_AB_SSLPRIVKEY=""
1381
	PBI_AB_PRUNE=""
1382
	PBI_AB_TMPFS=""
1383
	PBI_BUILDONLY="NO"
1384
	PBI_CAUTHOR=""
1385
	PBI_CBACKUP=""
1386
	PBI_CBACKUPTARGET=""
1387
	PBI_CHECKSCRIPTS=""
1388
	PBI_CICON=""
1389
	PBI_CNAME=""
1390
        PBI_CONFDIR=""
1391
	PBI_CONFFILE="pbi.conf"
1392
        PBI_CONF_SCRIPTSDIR="scripts/"
1393
	PBI_CREATE_OUTDIR="$HOME"
1394
	PBI_CREATE_HASHLIST="YES"
1395
	PBI_CUPDATE=""
1396
	PBI_CWEB=""
1397
	if [ -z "${PBI_DBDIR}" ] ; then
1398
		PBI_DBDIR="/var/db/pbi"
1399
	fi
1400
	PBI_DBAPPDIR="${PBI_DBDIR}/installed"
1401
	PBI_DBDIRTYFILE="${PBI_DBDIR}/.hashdirty"
1402
	PBI_DBHASHQUEUEDIR="${PBI_DBDIR}/.hashqueue"
1403
	PBI_DBICONDIR="${PBI_DBDIR}/repo-icons"
1404
	PBI_DBINDEXDIR="${PBI_DBDIR}/index"
1405
	PBI_DBKEYDIR="${PBI_DBDIR}/keys"
1406
	PBI_DBMIRRORDIR="${PBI_DBDIR}/mirrors"
1407
	PBI_DBREPODIR="${PBI_DBDIR}/repos"
1408
	PBI_DISABLEHASHDIR="NO"
1409
	PBI_GUITOPBANNER="gui_banner.png"
1410
	PBI_GUISIDEBANNER="gui_sidebanner.png"
1411
	PBI_KEEPBUILDFILES="NO"
1412
	PBI_MAKEPORT=""
1413
	PBI_MAKEPREFIX=""
1414
	PBI_MAKEOPTS=""
1415
	PBI_MKPORTBEFORE=""
1416
	PBI_MKPORTAFTER=""
1417
	PBI_PORTSDIR=""
1418
	PBI_PROGAUTHOR=""
1419
	PBI_PROGMDATE=""
1420
	PBI_PROGEPOCH=""
1421
	PBI_PROGNAME=""
1422
	PBI_PROGDIRNAME=""
1423
	PBI_PROGDIRPATH=""
1424
	PBI_PROGICON=""
1425
	PBI_PROGREVISION=""
1426
	PBI_PROGVERSION=""
1427
	PBI_PROGWEB=""
1428
	PBI_PRUNEBUILDPORTS="YES"
1429
	PBI_SKIPCHECKSUM=""
1430
	PBI_SKIPSIGVERIFY=""
1431
	PBI_USESYSGL="YES"
1432
	PBI_USESYSFONTS="YES"
1433
	PBI_VERBOSE="NO"
1434
	PORTSDIR="/usr/ports"
1435
}
1436

    
1437
# Set and export vars used by module scripts
1438
export_script_vars() {
1439
	# Load some initial values
1440
	get_pbi_progdir
1441
	get_pbi_progversion
1442

    
1443
	export PBI_PROGNAME PBI_PROGDIRNAME PBI_PROGDIRPATH PBI_PROGVERSION PBI_RCDIR 
1444
	export SYS_LOCALBASE PBI_FAKEBIN_DIR
1445
}
1446

    
1447
# init tmpdir
1448
init_tmpdir() {
1449
	if [ -d "${PBI_TMPDIR}" ] ; then return; fi
1450
	if [ -z "${PBI_TMPDIR}" ] ; then return ; fi
1451
	if [ "${PBI_TMPDIR}" = "/" ] ; then return ; fi
1452
	if [ -e "${PBI_TMPDIR}" ] ; then rm -rf "${PBI_TMPDIR}" ; fi
1453
	mkdir -p "${PBI_TMPDIR}"
1454
}
1455

    
1456
# rm tmpdir
1457
rm_tmpdir() {
1458
	if [ -z "${PBI_TMPDIR}" -o "${PBI_TMPDIR}" = "/" ] ; then return 0; fi
1459
	if [ -e "${PBI_TMPDIR}" ] ; then rm -rf "${PBI_TMPDIR}" ; fi
1460
}
1461

    
1462
# rm tmpdir
1463
rm_buildfiles() {
1464
	if [ "${PBI_KEEPBUILDFILES}" = "YES" ] ; then return ; fi
1465
	if [ -z "${PBI_PROGDIRPATH}" ] ; then return ; fi
1466
	if [ "`basename $0`" = "pbi_makeport_chroot" -a -d "${PBI_PROGDIRPATH}" ] ; then 
1467
		echo "Cleaning ${PBI_PROGDIRPATH}"
1468
		rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
1469
		chflags -R noschg "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
1470
		rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
1471
	fi
1472
	if [ -z "$PBI_CHROOTDIR" ] ; then return ; fi
1473
	chroot_make_cleanup
1474
}
1475

    
1476
# Load PBI conf options
1477
load_pbi_conffile() {
1478
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
1479
  	if [ -e "${PBI_CONFDIR}/${PBI_CONFFILE}" ] ; then
1480
		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
1481
		. ${PBI_CONFDIR}/${PBI_CONFFILE}
1482
	fi
1483
}
1484

    
1485
# Get the PBI_PROGVERSION
1486
get_pbi_progversion() {
1487

    
1488
	if [ -z "${PBI_PROGVERSION}" ] ; then
1489
		load_pbi_conffile
1490

    
1491
		# If we have PBI_PROGVERSION now set
1492
		if [ -n "${PBI_PROGVERSION}" ] ; then return 0 ; fi
1493
	else
1494
		return 0
1495
	fi
1496

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

    
1500
  		# Check if we have a portrevision to use in version number
1501
  		PORTREV=""
1502
  		PORTREV="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PORTREVISION 2>/dev/null`"
1503
  		if [ -n "${PORTREV}" -a "${PORTREV}" != "0" ]
1504
 		then
1505
   			PORTVER="${PORTVER}_${PORTREV}"
1506
		fi
1507
		PBI_PROGVERSION="${PORTVER}"
1508

    
1509
		if [ -z "${PBI_PROGVERSION}" ] ; then
1510
			echo "Warning: Unable to set PBI_PROGVERSION with:"
1511
		        echo "make -C ${PORTSDIR}/${PBI_MAKEPORT} -V DISTVERSION"
1512
		fi
1513
	else
1514
		echo "PBI_PROGVERSION - $PBI_PROGVERSION - PORTSDIR - ${PORTSDIR} - $PBI_MAKEPORT - $PBI_MAKE_PORT - pbi - $pbi"
1515
		exit_err "Failed to locate PBI_PROGVERSION"
1516
	fi
1517

    
1518
	# If we have a REVISION, use it as well
1519
	if [ -n "$PBI_PROGREVISION" ] ; then
1520
		PBI_PROGVERSION="${PBI_PROGVERSION}_${PBI_PROGREVISION}"
1521
	fi
1522
}
1523

    
1524

    
1525
# Get the PBI_PROGNAME
1526
get_pbi_progname() {
1527
	if [ -z "${PBI_PROGNAME}" ] ; then
1528
		load_pbi_conffile
1529
	else
1530
		return 0
1531
	fi
1532

    
1533
	if [ -z "${PBI_PROGNAME}" -a -n "${PORTSDIR}" -a -n "${PBI_MAKEPORT}" ] ; then
1534
		PBI_PROGNAME="`make -C ${PORTSDIR}/${PBI_MAKEPORT} -V PORTNAME`"
1535
	else
1536
		exit_err "Failed to locate PBI_PROGNAME"
1537
	fi
1538
}
1539

    
1540
# Get the PBI PROGDIR Name
1541
get_pbi_progdir() {
1542
	if [ -z "${PBI_PROGNAME}" ] ; then
1543
		get_pbi_progname
1544
	fi
1545

    
1546
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
1547
	ARCH="`uname -m`"
1548
	if [ -n "${PBI_OSARCH}" ] ; then
1549
		ARCH="${PBI_OSARCH}"
1550
	fi
1551
	if [ -z "${PBI_PROGDIRNAME}" ] ; then
1552
		PBI_PROGDIRNAME="${tmp}-${ARCH}"
1553
	fi
1554
	if [ -z "${PBI_PROGDIRPATH}" ] ; then
1555
		PBI_PROGDIRPATH="${PBI_APPDIR}/${PBI_PROGDIRNAME}"
1556
	fi
1557
}
1558

    
1559
# Helper function to exit after a error, and do some cleanup
1560
exit_err() {
1561
	echo -e "`basename ${0}`: ${1}"
1562
	rm_tmpdir
1563
	rm_buildfiles
1564
	rm_pbipatchfiles
1565
	chroot_make_cleanup
1566
	clean_remote_dl
1567
	exit 255
1568
}
1569

    
1570
# Check if we need to cleanup patch files
1571
rm_pbipatchfiles() {
1572
	if [ -z "${_pbiNewDir}${_pbiOldDir}${_pbiPatchDir}" ] ; then
1573
		return
1574
	else
1575
		echo "Cleaning up patch data..."
1576
	fi
1577

    
1578
	if [ -n "${_pbiNewDir}" -a -d "${_pbiNewDir}" -a "${_pbiNewDir}" != "/" ] ; then
1579
	 	rm -rf "${_pbiNewDir}" >/dev/null 2>/dev/null
1580
	 	chflags -R noschg "${_pbiNewDir}" >/dev/null 2>/dev/null
1581
	 	rm -rf "${_pbiNewDir}" >/dev/null 2>/dev/null
1582
	fi
1583
	if [ -n "${_pbiOldDir}" -a -d "${_pbiOldDir}" -a "${_pbiOldDir}" != "/" ] ; then
1584
	 	rm -rf "${_pbiOldDir}" >/dev/null 2>/dev/null
1585
	 	chflags -R noschg "${_pbiOldDir}" >/dev/null 2>/dev/null
1586
	 	rm -rf "${_pbiOldDir}" >/dev/null 2>/dev/null
1587
	fi
1588
	if [ -n "${_pbiPatchDir}" -a -d "${_pbiPatchDir}" -a "${_pbiPatchDir}" != "/" ] ; then
1589
	 	rm -rf "${_pbiPatchDir}" >/dev/null 2>/dev/null
1590
	 	chflags -R noschg "${_pbiPatchDir}" >/dev/null 2>/dev/null
1591
	 	rm -rf "${_pbiPatchDir}" >/dev/null 2>/dev/null
1592
	fi
1593
}
1594

    
1595
# Check if we need to delete a remotely dl'd file
1596
clean_remote_dl() {
1597
	# If this was a remote fetch, remove dl'd file
1598
	if [ "$PBI_REMOTEFETCH" = "YES" -a -n "$PBI_FILENAME" ]; then 
1599
		rm "$PBI_FILENAME" >/dev/null 2>/dev/null
1600
	fi
1601
}
1602

    
1603
# Set port make options from config
1604
set_make_options() {
1605

    
1606
	# Set the LOCALBASE
1607
	LOCALBASE="${PBI_PROGDIRPATH}"
1608
	if [ -e "${LOCALBASE}" ] ; then 
1609
		if [ "$MKDELBUILD" != "YES" ] ; then
1610
			exit_err "${LOCALBASE} already exists! Delete it before doing a rebuild"
1611
		else
1612
			if [ -z "${LOCALBASE}" ] ; then
1613
				exit_err "null LOCALBASE, this shouldn't happen"
1614
			fi
1615
			rm -rf "${LOCALBASE}"
1616
		fi
1617
	fi
1618

    
1619
	local MAKE_CONF="/etc/make.conf"
1620

    
1621
	echo "LOCALBASE=${LOCALBASE}" >> ${MAKE_CONF}
1622
	echo "PACKAGE_BUILDING=yes" >> ${MAKE_CONF}
1623
	echo "BATCH=yes" >> ${MAKE_CONF}
1624
	echo "NO_IGNORE=yes" >> ${MAKE_CONF}
1625
	echo "PACKAGE_BUILDING=yes" >> ${MAKE_CONF}
1626

    
1627
	# If we plan on using TMPFS set it now
1628
	if [ "$MKTMPFS" = "YES" ] ; then 
1629
		echo "WRKDIRPREFIX=/tmpfs" >> ${MAKE_CONF}
1630
		echo "DEPENDS_CLEAN=YES" >> ${MAKE_CONF}
1631
	else
1632
		mkdir /usr/wrkdirprefix
1633
		echo "WRKDIRPREFIX=/usr/wrkdirprefix" >> ${MAKE_CONF}
1634
	fi
1635

    
1636
	if [ -n "$PBI_MAKEOPTS" ] ; then
1637
		# Check if we have custom make opts
1638
		echo "${PBI_MAKEOPTS}" >> ${MAKE_CONF}
1639
	fi
1640

    
1641
	# Link LOCALBASE -> /usr/local
1642
	mkdir -p ${LOCALBASE}
1643
	rm -rf /usr/local
1644
	ln -s ${LOCALBASE} /usr/local
1645

    
1646
	# Make sure ldconfig is primed
1647
	/etc/rc.d/ldconfig start
1648

    
1649
	# Check if using ccache directory
1650
	if [ -d "/.ccache" ] ; then
1651
		echo "Enabling ccache..."
1652
		cd /usr/ports/devel/ccache 
1653
		make install clean
1654
		if [ $? -eq 0 ] ; then
1655
			# Setup environment variables
1656
			CCACHE_PATH="/usr/bin:${LOCALBASE}/bin"
1657
			export CCACHE_PATH
1658
			CCACHE_DIR="/.ccache"
1659
			export CCACHE_DIR
1660
			PATH="${LOCALBASE}/libexec/ccache:${PATH}"
1661
			export PATH
1662

    
1663
			# Setup make configuration
1664
			echo ".if !defined(NO_CCACHE)" >> ${MAKE_CONF}
1665
			echo "  CC=${LOCALBASE}/libexec/ccache/world/cc" >> ${MAKE_CONF}
1666
			echo "  CXX=${LOCALBASE}/libexec/ccache/world/c++" >> ${MAKE_CONF}
1667
			echo ".endif" >> ${MAKE_CONF}
1668
		else
1669
			echo "Failed installing ccache! Continuing without it..."
1670
		fi
1671
	fi
1672

    
1673
	PATH="${PATH}:/usr/local/bin:/usr/local/sbin:${LOCALBASE}/bin:${LOCALBASE}/sbin"
1674
	export PATH
1675

    
1676
	FORCE_PKG_REGISTER="Y"
1677
	export FORCE_PKG_REGISTER
1678

    
1679
}
1680

    
1681
# Confirm we are running as root
1682
require_root() {
1683
  if [ `id -u` != "0" ] ; then
1684
     exit_err "Must be run as root!"
1685
  fi 
1686
}
1687

    
1688
# Confirm we are running as root or the proper group for installation
1689
require_root_or_group() {
1690
  if [ `id -u` = "0" ] ; then return 0 ; fi 
1691
  touch ${PBI_APPDIR}/.ptest.$$ >/dev/null 2>/dev/null
1692
  if [ "$?" = "0" ] ; then 
1693
	rm ${PBI_APPDIR}/.ptest.$$ >/dev/null 2>/dev/null
1694
	return 0
1695
  fi
1696
  exit_err "Must be run as root or a member of the $PBI_INSTALLGROUP group!"
1697
}
1698

    
1699
# Function to get the username from a file
1700
get_username_from_file() {
1701
	if [ -f "${1}" ] ; then 
1702
		FILEUSER=`ls -al ${1} | awk '{print $3}'`
1703
		export FILEUSER
1704
		return 0
1705
	fi
1706
	if [ -d "${1}" ] ; then 
1707
		FILEUSER=`ls -al ${1} | grep -v "total" | head -n 1 | awk '{print $3}'`
1708
		export FILEUSER
1709
		return 0
1710
	fi
1711
	exit_err "Invalid file for usercheck!"
1712
}
1713

    
1714
# Start the make patch process
1715
pbi_makepatch_init() {
1716
  	require_root
1717
	init_tmpdir
1718
	parse_makepatch_pbi_cmdline "$@"
1719

    
1720
	# Create a new patch file from the two PBIs specified
1721
	make_pbi_patchfile "${PBI_FILENAME}" "${PBI_OLDFILENAME}" "${PBI_PATCHOUTDIR}"
1722
}
1723

    
1724
# Remove a repo from the DB
1725
pbi_deleterepo_init() {
1726
  	require_root
1727
	parse_deleterepo_pbi_cmdline "$@"
1728

    
1729
	delete_pbi_repo
1730
}
1731

    
1732
# Do the removal of a PBI repo
1733
delete_pbi_repo() {
1734
	# Make sure this repo exists
1735
	ls ${PBI_DBREPODIR}/${PBI_DELREPO_ID}.* >/dev/null 2>/dev/null
1736
	if [ "$?" != "0" ] ; then
1737
		exit_err "No such repo ID: ${PBI_DELREPO_ID}"
1738
	fi
1739
	
1740
	_md5=`ls ${PBI_DBREPODIR}/${PBI_DELREPO_ID}.* | sed "s|^${PBI_DBREPODIR}/${PBI_DELREPO_ID}.||g"`
1741
	if [ -e "${PBI_DBREPODIR}/${PBI_DELREPO_ID}.${_md5}" ] ; then
1742
		rm "${PBI_DBREPODIR}/${PBI_DELREPO_ID}.${_md5}"
1743
	else
1744
		echo "Warning: ${PBI_DELREPO_ID}.${_md5} does not exist in the database."
1745
	fi
1746
	if [ -e "${PBI_DBKEYDIR}/${_md5}.ssl" ] ; then
1747
		rm "${PBI_DBKEYDIR}/${_md5}.ssl"
1748
	else
1749
		echo "Warning: ${_md5}.ssl does not exist in the keys database."
1750
	fi
1751
	if [ -e "${PBI_DBMIRRORDIR}/${_md5}" ] ; then
1752
		rm "${PBI_DBMIRRORDIR}/${_md5}"
1753
	else
1754
		echo "Warning: ${_md5} does not exist in the mirror database."
1755
	fi
1756
	
1757
	# See if we need to remove a downloaded index file
1758
	if [ -e "${PBI_DBINDEXDIR}/${_md5}-index" ] ; then
1759
		rm "${PBI_DBINDEXDIR}/${_md5}-index"
1760
		rm "${PBI_DBINDEXDIR}/${_md5}-index.time"
1761
	fi
1762

    
1763
	# Make sure we renumber the repos
1764
	renumber_repos
1765

    
1766
	echo "Deleted Repository ${PBI_DELREPO_ID}."
1767

    
1768
}
1769

    
1770
# After deleting a repo, this can be run to renumber the IDs
1771
renumber_repos() {
1772
	_rNum="1"
1773
	for i in `ls ${PBI_DBREPODIR} | sort`
1774
	do
1775
		case `echo ${_rNum} | wc -m | tr -d ' '` in
1776
			2) _rNum="00${_rNum}" ;;
1777
			3) _rNum="0${_rNum}" ;;
1778
			*) ;;
1779
		esac
1780

    
1781
		_md5=`echo ${i} | cut -d '.' -f 2`
1782
		mv "${PBI_DBREPODIR}/${i}" "${PBI_DBREPODIR}/${_rNum}.${_md5}"
1783

    
1784
		_rNum=`expr ${_rNum} + 1`
1785
	done
1786
}
1787

    
1788
# Add a new repo to the db
1789
pbi_addrepo_init() {
1790
  	require_root
1791
	parse_addrepo_pbi_cmdline "$@"
1792

    
1793
	# Create a new repo file
1794
	add_pbi_repo
1795
}
1796

    
1797
# Extract the repo and add it to the DB
1798
add_pbi_repo() {
1799
	init_tmpdir
1800
	tar xvf "${PBI_ADDREPO_FILE}" -C ${PBI_TMPDIR} >/dev/null 2>/dev/null
1801
	if [ "$?" != "0" ] ; then
1802
		exit_err "Failed to read ${PBI_ADDREPO_FILE}"
1803
	fi
1804
	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
1805
		exit_err "Improperly packaged repo file!"
1806
	fi
1807

    
1808
	# Make sure we don't have a duplicate repo key
1809
	for tr in ${PBI_PUBKEYS}
1810
	do
1811
		diff -q ${tr} ${PBI_TMPDIR}/repokey.ssl >/dev/null 2>/dev/null
1812
		if [ "$?" = "0" ] ; then
1813
			exit_err "Repo with identical key already registered!"
1814
		fi
1815
	done
1816

    
1817
	# Figure out the next repo number
1818
	get_next_repo_num
1819

    
1820
	_md5=`md5 -q ${PBI_TMPDIR}/repo-url`
1821
	_url=`cat ${PBI_TMPDIR}/repo-url`
1822
	_desc=`cat ${PBI_TMPDIR}/repo-desc`
1823
	echo "URL: ${_url}" > ${PBI_DBREPODIR}/${_rNum}.${_md5}
1824
	echo "Desc: ${_desc}" >> ${PBI_DBREPODIR}/${_rNum}.${_md5}
1825
	cp ${PBI_TMPDIR}/repo-mirror ${PBI_DBMIRRORDIR}/${_md5}
1826
	cp "${PBI_TMPDIR}/repokey.ssl" "${PBI_DBKEYDIR}/${_md5}.ssl"
1827
	chmod 755 "${PBI_DBKEYDIR}/${_md5}.ssl"
1828
	
1829
	rm_tmpdir
1830

    
1831
	echo "Added new repo: \"${_desc}\" to the database."
1832

    
1833
}
1834

    
1835
# Function to do listing of installed repos, and return next available number
1836
get_next_repo_num() {
1837
	_rNum="0"
1838
	for i in `ls ${PBI_DBREPODIR} | sort`
1839
	do
1840
		_rNum=`expr ${_rNum} + 1`
1841
	done
1842

    
1843
	_rNum=`expr ${_rNum} + 1`
1844

    
1845
	case `echo ${_rNum} | wc -m | tr -d ' '` in
1846
		2) _rNum="00${_rNum}" ;;
1847
		3) _rNum="0${_rNum}" ;;
1848
		*) ;;
1849
	esac
1850

    
1851
	export _rNum
1852
}
1853

    
1854
# Start the make patch process
1855
pbi_makerepo_init() {
1856
  	require_root
1857
	parse_makerepo_pbi_cmdline "$@"
1858

    
1859
	# Create a new repo file
1860
	make_pbi_repo
1861
}
1862

    
1863
# Create the repo .rpo file
1864
make_pbi_repo() {
1865
	init_tmpdir
1866

    
1867
	mkdir ${PBI_TMPDIR}/.mkrepo
1868
	cp ${PBI_MKREPO_KEY} ${PBI_TMPDIR}/.mkrepo/repokey.ssl
1869
	echo "${PBI_MKREPO_URL}" >  ${PBI_TMPDIR}/.mkrepo/repo-url
1870
	echo "${PBI_MKREPO_DESC}" >  ${PBI_TMPDIR}/.mkrepo/repo-desc
1871
	echo "${PBI_MKREPO_MIRROR}" | sed 's|,|\
1872
|g' > ${PBI_TMPDIR}/.mkrepo/repo-mirror
1873

    
1874

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

    
1878
	rm_tmpdir
1879
}
1880

    
1881
# Init the metatool
1882
pbi_mt_init() {
1883
	parse_mt_pbi_cmdline "$@"
1884
	case $PBI_MT_MODE in
1885
		ADD) if [ "$PBI_MT_TYPE" = "CAT" ] ; then
1886
			do_pbi_mt_add_cat
1887
		     else
1888
			do_pbi_mt_add_app
1889
		     fi ;;
1890
		REM) if [ "$PBI_MT_TYPE" = "CAT" ] ; then
1891
			do_pbi_mt_rem_cat "${PBI_MT_REMNAME}" "${PBI_MT_METAFILE}"
1892
		     else
1893
			do_pbi_mt_rem_app "${PBI_MT_REMNAME}" "${PBI_MT_METAFILE}"
1894
		     fi ;;
1895
		  *) ;;
1896
	esac
1897
}
1898

    
1899
do_pbi_mt_add_cat() {
1900
	init_tmpdir
1901

    
1902
	# Remove any duplicate name
1903
	do_pbi_mt_rem_cat "${PBI_MT_ADDNAME}" "${PBI_MT_METAFILE}"
1904

    
1905
	cp ${PBI_MT_METAFILE} ${PBI_TMPDIR}/.meta.$$
1906
	echo "Cat=${PBI_MT_ADDNAME};${PBI_MT_ADDICON};${PBI_MT_ADDDESC};" \
1907
	>> ${PBI_TMPDIR}/.meta.$$
1908
	sort ${PBI_TMPDIR}/.meta.$$ > "${PBI_MT_METAFILE}"
1909
	rm ${PBI_TMPDIR}/.meta.$$
1910
	
1911
}
1912

    
1913
do_pbi_mt_add_app() {
1914
	init_tmpdir
1915
	# Remove any duplicate name
1916
	do_pbi_mt_rem_app "${PBI_MT_ADDNAME}" "${PBI_MT_METAFILE}"
1917

    
1918
	cp ${PBI_MT_METAFILE} ${PBI_TMPDIR}/.meta.$$
1919
	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;" \
1920
	>> ${PBI_TMPDIR}/.meta.$$
1921
	sort ${PBI_TMPDIR}/.meta.$$ > "${PBI_MT_METAFILE}"
1922
	rm ${PBI_TMPDIR}/.meta.$$
1923
}
1924

    
1925
do_pbi_mt_rem_cat() {
1926
	sed -i '' "\|^Cat=${1};|d" "${2}"
1927
}
1928

    
1929
do_pbi_mt_rem_app() {
1930
	sed -i '' "\|^App=${1};|d" "${2}"
1931
}
1932

    
1933
# Init the indextool
1934
pbi_it_init() {
1935
	parse_it_pbi_cmdline "$@"
1936
	case $PBI_IT_MODE in
1937
		ADD) do_pbi_it_add ;; 
1938
		REM) do_pbi_it_rem ;; 
1939
		  *) ;;
1940
	esac
1941
}
1942

    
1943
# Remove a target PBI from an index
1944
do_pbi_it_rem() {
1945
	init_tmpdir
1946
	_pbilow="`echo ${PBI_IT_REMNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
1947

    
1948
	cat "${PBI_IT_REMINDEX}" | grep -v "^${_pbilow}:${PBI_IT_REMARCH}:${PBI_IT_REMVER}" \
1949
		> "${PBI_TMPDIR}/.indextmp"
1950
	sort ${PBI_TMPDIR}/.indextmp > "${PBI_IT_REMINDEX}"
1951

    
1952
	rm_tmpdir
1953
}
1954

    
1955
# Add a new PBI to the specified INDEX file
1956
do_pbi_it_add() {
1957
	init_tmpdir
1958

    
1959
	# First load values from the target PBI
1960
	PBI_FILENAME="$PBI_IT_ADDFILE"
1961
	load_info_from_header
1962

    
1963
	# Get the name in lower-case
1964
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
1965
	
1966
	# Prune any old copies of this app from the index
1967
	prune_from_index "$_pbilow" "$PBI_APPARCH"
1968
	
1969
	# Prune any old copies of this app from the index
1970
	mark_current_active_index "$_pbilow" "$PBI_APPARCH"
1971

    
1972
	# Add the new index entry
1973
	add_to_index
1974
	rm_tmpdir
1975
}
1976

    
1977
# Mark any current versions of this PBI as active in the index
1978
mark_current_active_index() {
1979

    
1980
	while read iLine
1981
	do
1982
		echo "$iLine" | grep "^${1}:${2}:" >/dev/null 2>/dev/null
1983
		if [ "$?" != "0" ] ; then
1984
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
1985
			continue
1986
		fi
1987
	 	echo "$iLine" | sed 's|:current|:active|' >> ${PBI_TMPDIR}/.indextmp	
1988

    
1989
	done < $PBI_IT_ADDINDEX	
1990
	mv "${PBI_TMPDIR}/.indextmp" "${PBI_IT_ADDINDEX}"
1991
}
1992

    
1993
# Add the specified PBI to the index
1994
add_to_index() {
1995
	mv "${PBI_IT_ADDINDEX}" "${PBI_TMPDIR}/.indextmp"
1996
	local _date=`date '+%s'`
1997
	local _sha256=`sha256 -q ${PBI_FILENAME}`
1998
	local _psize=`du -k ${PBI_FILENAME} | cut -f 1`
1999
	echo "${_pbilow}:${PBI_APPARCH}:${PBI_PROGVERSION}:${_sha256}:${PBI_PROGMDATE}:${PBI_IT_ADDURL}:$_date:${PBI_IT_ADDBPVERS}:current:${_psize}:" >>"${PBI_TMPDIR}/.indextmp"
2000
	sort ${PBI_TMPDIR}/.indextmp > "${PBI_IT_ADDINDEX}"
2001
}
2002

    
2003

    
2004
# Remove a set number of PBIs from the index
2005
prune_from_index() {
2006
	if [ -z "$PBI_IT_ADDKEEP" ]; then return ; fi
2007

    
2008
	local found="0"
2009
	while read iLine
2010
	do
2011
		echo "$iLine" | grep "^${1}:${2}:" >/dev/null 2>/dev/null
2012
		if [ "$?" != "0" ] ; then
2013
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
2014
			continue
2015
		fi
2016
		if [ $found -lt $PBI_IT_ADDKEEP ] ; then
2017
	 		echo "$iLine" >> ${PBI_TMPDIR}/.indextmp	
2018
			found=`expr $found + 1`
2019
		fi
2020
	done < $PBI_IT_ADDINDEX	
2021
	mv "${PBI_TMPDIR}/.indextmp" "${PBI_IT_ADDINDEX}"
2022
}
2023

    
2024
# Add a new repo to the db
2025
pbi_browser_init() {
2026
	parse_browse_pbi_cmdline "$@"
2027
	init_tmpdir
2028

    
2029
	# Check if we are doing a category listing, the default if no options
2030
	if [ "$PBI_BROWSE_LISTCATS" = "YES" -o -z "${PBI_BROWSE_LISTALLPBI}${PBI_BROWSE_CAT}${PBI_BROWSE_SEARCH}" ] ; then
2031
		pbi_browse_listcats
2032
	else
2033
		pbi_browse_listpbi
2034
	fi
2035

    
2036
}
2037

    
2038
# List PBIs from a repo
2039
pbi_browse_listpbi() {
2040
	_rArch=`uname -m`
2041

    
2042
	# Figure out which type of display we are doing
2043
	if [ -n "$PBI_BROWSE_LISTALLPBI" ] ; then
2044
		echo "Using RepoID: $PBI_BROWSE_RID"
2045
		echo "Listing all available PBIs"
2046
		grep -i -e "^App=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2047
	elif [ -n "$PBI_BROWSE_CAT" ] ; then
2048
		echo "Using RepoID: $PBI_BROWSE_RID"
2049
		echo "Available PBIs for Category: $PBI_BROWSE_CAT"
2050
		grep -i -e "^App=" -i -e ";${PBI_BROWSE_CAT};" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2051
	elif [ -n "$PBI_BROWSE_SEARCH" ] ; then
2052
		echo "Using RepoID: $PBI_BROWSE_RID"
2053
		echo "Searching for: $PBI_BROWSE_SEARCH"
2054
		grep -i -e "^App=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2055
	else
2056
		exit_err "No valid search variable set!"
2057
	fi
2058

    
2059
	while read app
2060
	do
2061
		line=`echo $app | sed 's|^App=||g'`
2062
		catCheck=`echo $line | cut -d ';' -f 2 2>/dev/null`
2063
		aName=`echo $line | cut -d ';' -f 1 2>/dev/null`
2064

    
2065
		# Make sure this is from the correct category
2066
		if [ -n "$PBI_BROWSE_CAT" ] ; then
2067
			_cCheck=`echo $catCheck | tr '[:lower:]' '[:upper:]'`
2068
			_cCheck2=`echo $PBI_BROWSE_CAT | tr '[:lower:]' '[:upper:]'`
2069
			if [ "$_cCheck" != "$_cCheck2" ]; then 
2070
			continue
2071
			fi
2072
		fi
2073

    
2074
		# Set the displayed arch type
2075
		aArch="$_rArch"
2076

    
2077
		# Make sure this application has an associated PBI available
2078
		check_pbi_update "$aName" "nodisplay" \
2079
		 "$aName" "current" \
2080
		 "`uname -r`" "$_rArch" "${PBI_BROWSE_RID}"
2081
		if [ "$?" != "0" ] ; then
2082
			# On amd64, see if 32bit version exists
2083
			if [ "$_rArch" = "amd64" ] ; then
2084
				check_pbi_update "$aName" "nodisplay" \
2085
		 		"$aName" "current" \
2086
		 		"`uname -r`" "i386" "${PBI_BROWSE_RID}"
2087
				if [ "$?" != "0" ] ; then 
2088
					continue
2089
				else
2090
					# Found a 32bit version of the app
2091
					aArch="i386"
2092
				fi
2093
			else
2094
				# Not on amd64, continue on
2095
				continue
2096
			fi
2097
		fi
2098

    
2099
		aIcon=`echo $line | cut -d ';' -f 3`
2100
		aAuthor=`echo $line | cut -d ';' -f 4`
2101
		aUrl=`echo $line | cut -d ';' -f 5`
2102
		aLic=`echo $line | cut -d ';' -f 6`
2103
		aType=`echo $line | cut -d ';' -f 7`
2104
		aKeywords=`echo $line | cut -d ';' -f 8`
2105
		aDesc=`echo $line | cut -d ';' -f 9`
2106
		aRoot=`echo $line | cut -d ';' -f 10`
2107

    
2108
		# Check for a translation to the description
2109
		get_meta_trans "App" "$cName" "${PBI_BROWSE_METAFILE}"
2110
		if [ -n "$MTRANS" ] ; then
2111
			aDesc="$MTRANS"
2112
		fi
2113

    
2114
		# Search the description / keywords
2115
		if [ -n "$PBI_BROWSE_SEARCH" ] ; then
2116
			echo "$aName,$aDesc,$aKeywords,$MTRANS" | grep -i "$PBI_BROWSE_SEARCH" >/dev/null 2>/dev/null
2117
			if [ "$?" != "0" ]; then continue ; fi
2118
		fi
2119

    
2120
		# Get the local icon file
2121
		ext=`echo $aIcon | sed 's/.*\.//'`
2122
		aIcon="${PBI_DBICONDIR}/${PBI_BROWSE_REPOMD5}-${aName}.${ext}"
2123

    
2124
		echo "------------------------------------"
2125
		echo "Application: $aName"
2126
		echo "Version: $PBI_UPNVER"
2127
		if [ -n "$PBI_UPSIZE" ] ; then
2128
			echo "Size: $PBI_UPSIZE"
2129
		fi
2130
		if [ -n "$PBI_BROWSE_LISTALLPBI" ] ; then
2131
			echo "Category: $catCheck"
2132
		fi
2133
		echo "Created: `echo $PBI_UPMDATE`"
2134
		if [ "$aRoot" = "YES" ] ; then
2135
			echo "RootInstall: YES"
2136
		else
2137
			echo "RootInstall: NO"
2138
		fi
2139
		echo "Arch: $aArch"
2140
		echo "Author: $aAuthor"
2141
		echo "URL: $aUrl"
2142
		echo "License: $aLic"
2143
		echo "Type: $aType"
2144
		echo "Keywords: $aKeywords"
2145
		echo "Icon: $aIcon"
2146
		echo "Description: $aDesc"
2147
		echo ""
2148
		if [ "$aRoot" = "YES" ] ; then
2149
			echo "To install this PBI (As Root):"
2150
		else
2151
			echo "To install this PBI:"
2152
		fi
2153
		echo "# pbi_add --rArch $aArch --repo $PBI_BROWSE_RID -r $aName"
2154
		echo ""
2155

    
2156
		
2157
	done < ${PBI_TMPDIR}/.meta.$$
2158

    
2159
}
2160

    
2161
# List available categories for this repository
2162
pbi_browse_listcats() {
2163

    
2164
	echo "Using RepoID: $PBI_BROWSE_RID"
2165
	echo "Available Categories:"
2166
	grep "^Cat=" $PBI_BROWSE_METAFILE > ${PBI_TMPDIR}/.meta.$$
2167
	while read cat
2168
	do
2169
		line=`echo $cat | sed 's|^Cat=||g'`
2170
		cName=`echo $line | cut -d ';' -f 1`
2171
		cIcon=`echo $line | cut -d ';' -f 2`
2172
		cDesc=`echo $line | cut -d ';' -f 3`
2173
		
2174
		# Check for a translation to the description
2175
		get_meta_trans "Cat" "$cName" "${PBI_BROWSE_METAFILE}"
2176
		if [ -n "$MTRANS" ] ; then
2177
			cDesc="$MTRANS"
2178
		fi
2179

    
2180
		# Get the local icon file
2181
		ext=`echo $cIcon | sed 's/.*\.//'`
2182
		cIcon="${PBI_DBICONDIR}/${PBI_BROWSE_REPOMD5}-${cName}.${ext}"
2183

    
2184
		echo "------------------------------------"
2185
		echo "Category: $cName"
2186
		echo "Icon: $cIcon"
2187
		echo "Description: $cDesc"
2188
		echo ""
2189

    
2190
	done < ${PBI_TMPDIR}/.meta.$$
2191

    
2192
	echo "To view available PBIs for a particular category:"
2193
	echo " % pbi_browser -c <category> <repoid>"
2194
}
2195

    
2196
# Function to check if we have a translated description
2197
get_meta_trans() {
2198
	local tag="$1"
2199
	local name="$2"
2200
	local metaFile="$3"
2201

    
2202
	# Check if we have a translation to overwrite with
2203
	MTRANS=""
2204
	if [ -z "$LANG" ] ; then return; fi
2205

    
2206
	lCheck="`echo $LANG | cut -d '_' -f 1` `echo $LANG | cut -d '.' -f 1`"
2207
	for l in $lCheck
2208
	do
2209
		catTrans=`grep "^${tag}\[$l\]=${name}" ${metaFile}`	
2210
		if [ -n "$catTrans" ] ; then
2211
			MTRANS=`echo $catTrans | cut -d ";" -f 2`
2212
			return
2213
		fi
2214
	done
2215
}
2216

    
2217
# List repos in the db
2218
pbi_listrepo_init() {
2219
  	require_root_or_group
2220
	parse_listrepo_pbi_cmdline "$@"
2221

    
2222
	# List the repos
2223
	if [ -z "$PBI_LISTREPO_ID" ] ; then
2224
		list_all_pbi_repo
2225
	else
2226
		if [ -n "${PBI_LISTREPO_UP}" ]; then
2227
			require_root
2228
			move_repo_up "${PBI_LISTREPO_ID}" 
2229
			list_all_pbi_repo
2230
		elif [ -n "${PBI_LISTREPO_DOWN}" ] ; then
2231
			require_root
2232
			move_repo_down "${PBI_LISTREPO_ID}"
2233
			list_all_pbi_repo
2234
		elif [ -n "${PBI_LISTREPO_MIRROR}" ] ; then
2235
			require_root
2236
			change_repo_mirror "${PBI_LISTREPO_ID}"
2237
			listrepo_details "${PBI_LISTREPO_ID}"
2238
		else
2239
			listrepo_details "${PBI_LISTREPO_ID}"
2240
		fi
2241
	fi
2242
}
2243

    
2244
# Function to change a specific repos mirror URL
2245
change_repo_mirror() {
2246
	local _rMd5=`ls ${PBI_DBREPODIR}/${1}.* | cut -d '.' -f 2`
2247
	echo "$PBI_LISTREPO_MIRROR" | sed 's|,|\
2248
|g' > "${PBI_DBMIRRORDIR}/${_rMd5}"
2249
}
2250

    
2251
# Move a repo down in priority
2252
move_repo_down() {
2253
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2254
	_uNum=`expr ${1} + 1`
2255

    
2256
	case `echo ${_uNum} | wc -m | tr -d ' '` in
2257
		2) _uNum="00${_uNum}" ;;
2258
		3) _uNum="0${_uNum}" ;;
2259
		*) ;;
2260
	esac
2261
	_uFile=`ls ${PBI_DBREPODIR}/${_uNum}.* 2>/dev/null`
2262
	if [ -z "$_uFile" ] ; then exit_err "This repo is already at the lowest priority!" ; fi
2263

    
2264
	_umd5=`echo $_uFile | cut -d '.' -f 2`
2265
	mv "${_uFile}" "${PBI_DBREPODIR}/${1}.${_umd5}"
2266
	_rmd5=`echo $_rFile | cut -d '.' -f 2`
2267
	mv "${_rFile}" "${PBI_DBREPODIR}/${_uNum}.${_rmd5}"
2268
}
2269

    
2270
# Move a repo up in priority
2271
move_repo_up() {
2272
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2273
	_uNum=`expr ${1} - 1`
2274

    
2275
	case `echo ${_uNum} | wc -m | tr -d ' '` in
2276
		2) _uNum="00${_uNum}" ;;
2277
		3) _uNum="0${_uNum}" ;;
2278
		*) ;;
2279
	esac
2280
	_uFile=`ls ${PBI_DBREPODIR}/${_uNum}.* 2>/dev/null`
2281
	if [ -z "$_uFile" ] ; then exit_err "This repo is already at the highest priority!" ; fi
2282

    
2283
	_umd5=`echo $_uFile | cut -d '.' -f 2`
2284
	mv "${_uFile}" "${PBI_DBREPODIR}/${1}.${_umd5}"
2285
	_rmd5=`echo $_rFile | cut -d '.' -f 2`
2286
	mv "${_rFile}" "${PBI_DBREPODIR}/${_uNum}.${_rmd5}"
2287
}
2288

    
2289
# List all PBI repos
2290
listrepo_details() {
2291
	_rFile=`ls ${PBI_DBREPODIR}/${1}.*`
2292
	_md5=`ls ${PBI_DBREPODIR}/${1}.* | cut -d '.' -f 2`
2293
	_desc=`cat ${_rFile} | grep "Desc: " | sed "s|Desc: ||g"` 
2294
	_url=`cat ${_rFile} | grep "URL: " | sed "s|URL: ||g"` 
2295
	_mirror=`cat ${PBI_DBMIRRORDIR}/$_md5` 
2296
	echo "Repo ID: ${1}"
2297
	echo "Description: ${_desc}"
2298
	echo "IndexURL: ${_url}"
2299
	echo "MD5: ${_md5}"
2300
	echo "LocalMeta: `ls ${PBI_DBINDEXDIR}/${_md5}*meta 2>/dev/null`"
2301
	echo "LocalIndex: `ls ${PBI_DBINDEXDIR}/${_md5}*index 2>/dev/null`"
2302
	echo "Mirror(s):"
2303
	echo "$_mirror"
2304
}
2305

    
2306
# List all PBI repos
2307
list_all_pbi_repo() {
2308
	echo "[ID]	[Description]"
2309
	echo "-----------------------------------------------------"
2310
	for repo in `ls ${PBI_DBREPODIR} | sort `
2311
	do
2312
		_id=`echo $repo | cut -d '.' -f 1`
2313
		_desc=`cat ${PBI_DBREPODIR}/${repo} | grep "Desc: " | sed "s|Desc: ||g"` 
2314
		echo "${_id}	${_desc}"
2315
	done
2316
}
2317

    
2318
# Start the patch process
2319
pbi_patch_init() {
2320
  	require_root_or_group
2321
	init_tmpdir
2322
	parse_patch_pbi_cmdline "$@"
2323

    
2324
	# Check if we are only displaying information
2325
	check_pbi_info_display
2326
	check_pbi_gui_display
2327
	check_pbi_scripts_display
2328
	check_pbi_license_display
2329
	if [ "$PBI_ADD_GUIDISPLAY" = "YES" -o "$PBI_ADD_INFODISPLAY" = "YES" -o "$PBI_CHECKSCRIPTS" = "YES" -o "${PBI_ADD_LICDISPLAY}" = "YES" ] 
2330
	then 
2331
		exit_trap
2332
	fi
2333

    
2334
	# Try to apply this patch file
2335
	do_pbi_patch
2336
}
2337

    
2338
# Start the PBI patch process
2339
do_pbi_patch() {
2340
	
2341
	# Verify the target PBI is installed
2342
	verify_pbi_update_target
2343

    
2344
        pbi_verify_signatures
2345
        pbi_verify_archivesum
2346
        
2347
	# Extract the archive contents
2348
        mk_pbi_extract_dir
2349
        pbi_extract_archive
2350

    
2351
	set_patch_wrkdir
2352

    
2353
	init_tmpdir
2354

    
2355
	# Run the uninstall script
2356
	if [ -e "${PBI_PATCHWRKDIR}/.sbin/.pbi-uninstall.sh" ] ; then
2357
		echo "Removing old xdg data..."
2358
		sh "${PBI_PATCHWRKDIR}/.sbin/.pbi-uninstall.sh"	>/dev/null 2>/dev/null
2359
	fi
2360

    
2361
	# Remove old files from the installed PBI
2362
	patch_rm_old_files
2363
	
2364
	# Extract the new files
2365
	patch_extract_new_files
2366

    
2367
	# Merge in the bsdiffs
2368
	patch_merge_bsdiffs
2369

    
2370
	# Make sure we have good permissions on this PBI
2371
	patch_apply_chmod
2372

    
2373
	# Run the install script
2374
	if [ -e "${PBI_PATCHWRKDIR}/.sbin/.pbi-install.sh" ] ; then
2375
		echo "Adding new xdg data..."
2376
		sh "${PBI_PATCHWRKDIR}/.sbin/.pbi-install.sh"	>/dev/null 2>/dev/null
2377
	fi
2378

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

    
2382
	# Update the registered version of the PBI
2383
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2384
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2385
        newDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHVERSION}-${PBI_APPARCH}"
2386
	mv "$oldDir" "$newDir"
2387
	rm ${newDir}/*.sha1 >/dev/null 2>/dev/null
2388

    
2389
	# Register the app
2390
	pbi_add_register_app	
2391

    
2392
        # Check if we need to run a post-install.sh script again
2393
	if [ -e "${newDir}/${MOD_POSTINS}" ] ; then
2394
          export_script_vars
2395
          sh "${newDir}/${MOD_POSTINS}"
2396
        fi
2397

    
2398
	# Cleanup after our selves
2399
	if [ -d "$PBI_EXTRACTDIR" ] ; then
2400
		echo "Cleaning up..."
2401
		rm -rf "$PBI_EXTRACTDIR"
2402
	fi
2403

    
2404
	# Update the hashdir
2405
	add_hashdir_trigger
2406

    
2407
	# Mark the hash-dir as dirty as well
2408
	make_hashdir_dirty
2409

    
2410
	echo "Finished patching ${_pbilow}: $PBI_PATCHTARGET -> $PBI_PATCHVERSION"
2411
}
2412

    
2413
# Mark the hashdir as dirty
2414
make_hashdir_dirty() {
2415
	date "+%s" > "${PBI_DBDIRTYFILE}"
2416
}
2417

    
2418
# Do any chmod stuff after patching
2419
patch_apply_chmod()
2420
{
2421
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-permList" ] ; then return; fi
2422

    
2423
	cuDir=`pwd`
2424

    
2425
	cd "${PBI_PATCHWRKDIR}"
2426
	echo "Applying updated permissions..."
2427
	while read chLine
2428
	do
2429
		$chLine >/dev/null 2>/dev/null
2430
	done < "${PBI_EXTRACTDIR}/PBI-permList"
2431

    
2432
	cd "$cuDir"
2433
}
2434

    
2435
# Function which does the merge of bsdiff files
2436
patch_merge_bsdiffs()
2437
{
2438
	echo "Applying patch data..."
2439
	find ${PBI_EXTRACTDIR} | grep '.bsdiff' | sed "s|${PBI_EXTRACTDIR}/||g" > ${PBI_TMPDIR}/.PBI.bspatch.$$
2440

    
2441
	while read pLine
2442
	do
2443
		if [ -z "$pLine" ] ; then continue; fi
2444
		_tFile="`echo $pLine | sed 's|.bsdiff$||g'`"
2445
		
2446
		if [ ! -e "${PBI_EXTRACTDIR}/${_tFile}.sha256" ] ; then
2447
			exit_err "Missing checksums for \"${_tFile}\" this patch is corrupt"
2448
		fi
2449

    
2450
		if [ ! -e "${PBI_PATCHWRKDIR}/${_tFile}" ] ; then
2451
			echo "Warning: Missing target file for patching: $_tFile"
2452
			continue
2453
		fi
2454
		
2455
		# Make sure we really are trying to patch the same file
2456
		sha1="`sha256 -q ${PBI_PATCHWRKDIR}/${_tFile}`"
2457
		sha2="`cat ${PBI_EXTRACTDIR}/${_tFile}.sha256`"
2458
		if [ "$sha1" != "$sha2" ] ; then
2459
			echo "Warning: Checksum failed for ${_tFile}, skipping."
2460
			continue
2461
		fi
2462

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

    
2465
		# See if we have a hard-link to take care of first
2466
		get_hard_link_count "${PBI_PATCHWRKDIR}/${_tFile}"
2467
       	 	if [ "$HLINKS" != "1" ] ; then
2468
			mv "${PBI_PATCHWRKDIR}/${_tFile}" "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2469
			cp "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$" "${PBI_PATCHWRKDIR}/${_tFile}"
2470
			rm -f "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2471
        	fi
2472
		
2473
		# Now do the patching
2474
	 	#echo "Patching $_tFile"	
2475
		mv "${PBI_PATCHWRKDIR}/${_tFile}" "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2476
		bspatch "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$" \
2477
			"${PBI_PATCHWRKDIR}/${_tFile}" \
2478
			"${PBI_EXTRACTDIR}/$pLine" >/dev/null 2>/dev/null
2479
		if [ "$?" != "0" ] ; then
2480
			echo "Warning: Failed to apply patch to \"$_tFile\""
2481
		fi
2482

    
2483
		# Re-apply the same permissions to the new file
2484
		chmod $_fPerm "${PBI_PATCHWRKDIR}/${_tFile}"
2485

    
2486
		# Remove the old file
2487
		rm "${PBI_PATCHWRKDIR}/${_tFile}.patch.$$"
2488

    
2489
	done < "${PBI_TMPDIR}/.PBI.bspatch.$$"
2490

    
2491
	rm "${PBI_TMPDIR}/.PBI.bspatch.$$"
2492
}
2493

    
2494
# Function which does the new file extraction for this PBI
2495
patch_extract_new_files()
2496
{
2497
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-newFiles.tar" ] ; then return; fi
2498
	echo "Installing new files..."
2499
	tar xvf "${PBI_EXTRACTDIR}/PBI-newFiles.tar" -C "${PBI_PATCHWRKDIR}" >/dev/null 2>/dev/null 
2500
	if [ "$?" != "0" ] ; then
2501
		echo "Warning: Error during new file extraction, PBI may not function correctly."
2502
	fi
2503
}
2504

    
2505
# Function which removes files that no longer exist in this updated PBI
2506
patch_rm_old_files()
2507
{
2508
	if [ ! -e "${PBI_EXTRACTDIR}/PBI-rmList" ] ; then return; fi
2509
	
2510
	echo "Removing old files..."
2511
	while read rmLine
2512
	do
2513
		if [ -z "$rmLine" ] ; then continue ; fi
2514
		if [ ! -e "${PBI_PATCHWRKDIR}/$rmLine" ] ; then
2515
			continue
2516
		fi
2517

    
2518
		rm -rf "${PBI_PATCHWRKDIR}/${rmLine}"
2519
	done < "${PBI_EXTRACTDIR}/PBI-rmList"
2520

    
2521
}
2522

    
2523
# Sets the workdir of the target PBI we are patching
2524
set_patch_wrkdir()
2525
{
2526
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2527
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2528

    
2529
	if [ ! -e "${oldDir}/pbi_defaultpath" ] ; then
2530
        	exit_err "Can not fild default path for \"$PBI_PROGNAME\"!"
2531
        fi
2532

    
2533
	PBI_PATCHWRKDIR="`cat ${oldDir}/pbi_defaultpath`"
2534

    
2535
	if [ ! -d "$PBI_PATCHWRKDIR" ] ; then
2536
        	exit_err "Path for \"$PBI_PROGNAME\" does not exist!"
2537
	fi
2538
}
2539

    
2540
# Confirms that the target PBI for this patch is installed
2541
# Exits if not and we are not doing a extract only
2542
verify_pbi_update_target()
2543
{
2544
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then return ; fi
2545
	
2546
	# Make sure the target PBI is installed
2547
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
2548
        oldDir="${PBI_DBAPPDIR}/${_pbilow}-${PBI_PATCHTARGET}-${PBI_APPARCH}"
2549

    
2550
	if [ ! -e "${oldDir}" ] ; then
2551
        	exit_err "\"${_pbilow}\" does not appear to be installed!"
2552
        fi
2553

    
2554
	# Check the arch type
2555
	if [ "`cat ${oldDir}/pbi_arch`" != "$PBI_APPARCH" ] ; then
2556
     		exit_err "Installed \"${PBI_PROGNAME}\" is not compiled for $PBI_APPARCH"
2557
	fi
2558

    
2559
	# Check the taret version
2560
	if [ "`cat ${oldDir}/pbi_version`" != "$PBI_PATCHTARGET" ] ; then
2561
     		exit_err "\"${_pbilow}\" patch is for \"$PBI_PROGVERSION\" only!"
2562
	fi
2563

    
2564
	# Check the fbsd version
2565
	_pFbsdVer="`cat ${oldDir}/pbi_fbsdver | cut -c 1`"
2566
	_sFbsdVer="`echo $PBI_FBSDVER | cut -c 1`"
2567
	if [ "$_pFbsdVer" != "$_sFbsdVer" ] ; then
2568
     		exit_err "\"${_pbilow}\" patch is for FreeBSD ${_sFbsdVer}.X only!"
2569
	fi
2570

    
2571
	# Check the mdate of the pbi
2572
	_pMDate="`cat ${oldDir}/pbi_mdate`"
2573
	_sMDate="$PBI_PATCHMDATE"
2574
	if [ "$_pMDate" != "$_sMDate" ] ; then
2575
     		exit_err "\"${_pbilow}\" patch is for the $PBI_PATCHMDATE build!"
2576
	fi
2577
}
2578

    
2579
# Start the pbi_add process
2580
pbi_add_init() {
2581
	init_tmpdir
2582
	parse_add_pbi_cmdline "$@"
2583

    
2584

    
2585
	# Check if we are only displaying information
2586
	check_pbi_info_display
2587
	check_pbi_gui_display
2588
	check_pbi_scripts_display
2589
	check_pbi_license_display
2590
	if [ "$PBI_ADD_GUIDISPLAY" = "YES" -o "$PBI_ADD_INFODISPLAY" = "YES" -o "$PBI_CHECKSCRIPTS" = "YES" -o "${PBI_ADD_LICDISPLAY}" = "YES" ] 
2591
	then 
2592
		clean_remote_dl
2593
		exit_trap
2594
	fi
2595

    
2596
  	require_root_or_group
2597

    
2598
	# If this app can only be installed as root
2599
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then require_root ; fi
2600

    
2601
	check_agree_lic
2602
	check_existing_pbi
2603
	do_pbi_add
2604
}
2605

    
2606
# Check if this PBI exists and exit if so
2607
check_existing_pbi() {
2608
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then return 0; fi
2609
	get_dbdir
2610
	dir="${APPDBDIR}"
2611

    
2612
	# See if this PBI is already installed
2613
	if [ -d "$dir" ]; then
2614
		get_username_from_file "${APPDBDIR}/pbi_name"
2615
		if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
2616
			exit_err "Permission denied to modify PBI installed by: $FILEUSER"     
2617
		fi
2618

    
2619
		if [ "${PBI_FORCEADD}" = "YES" ] ; then return 0; fi
2620
		exit_err "${PBI_PROGNAME} ${PBI_PROGVERSION} is already installed! Use -f to force installation."
2621
	fi
2622

    
2623
	if [ -e "${PBI_PROGDIRPATH}" ]; then
2624
		get_username_from_file "${PBI_PROGDIRPATH}"
2625
		if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
2626
			exit_err "Permission denied to modify PBI installed by: $FILEUSER"     
2627
		fi
2628
		if [ "${PBI_FORCEADD}" = "YES" ] ; then return 0; fi
2629
		exit_err "${PBI_PROGDIRPATH} already exists! Use -f to force installation."
2630
	fi
2631

    
2632

    
2633
}
2634

    
2635
# Check if we have a license to agree to, and if we've provided the flag to do so
2636
check_agree_lic() {
2637
        open_header_tmp
2638
        if [ -f "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}" -a "${PBI_LICAGREE}" = "NO" ] ; then
2639
        	delete_header_tmp
2640
		exit_err "LICENSE must be agreed to (--licagree) before this PBI can be installed."
2641
        fi
2642
        delete_header_tmp
2643
}
2644

    
2645
# See if we need to display pbi license
2646
check_pbi_license_display() {
2647
	if [ "$PBI_ADD_LICDISPLAY" != "YES" ] ; then return 0 ; fi
2648
	open_header_tmp
2649
	
2650
	if [ -f "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}" ] ; then 
2651
		echo "LICENSE:"
2652
		cat "${PBI_HEADER_TMPDIR}/${PBI_LICENSEFILE}"	
2653
	else
2654
		echo "`basename $0`: No LICENSE included with this PBI"
2655
	fi
2656
	delete_header_tmp
2657
}
2658

    
2659
# See if we need to display pbi info
2660
check_pbi_info_display() {
2661
	if [ "$PBI_ADD_INFODISPLAY" != "YES" ] ; then return 0 ; fi
2662
	pbi_display_info
2663
}
2664

    
2665
# Display pbi information to stdout
2666
pbi_display_info() {
2667

    
2668
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
2669
        _appname="${tmp}-${PBI_PROGVERSION}-${PBI_APPARCH}"
2670

    
2671
	if [ -z "$PBI_PATCHVERSION" ] ; then
2672
		echo "PBI Information for: $_appname"
2673
	else
2674
		echo "PBP Information for: $_appname"
2675
	fi
2676
	echo "-----------------------------------------------------"
2677
	echo "Name: ${PBI_PROGNAME}"
2678

    
2679
	if [ -n "$PBI_PATCHVERSION" ] ; then
2680
		echo "PatchTarget: $PBI_PATCHTARGET"
2681
	fi
2682

    
2683
	if [ -n "$PBI_INSTALLED_BY" ] ; then
2684
		echo "InstalledBy: $PBI_INSTALLED_BY"
2685
	fi
2686

    
2687
	# Does this PBI need root to install?
2688
	if [ "$PBI_REQUIRESROOT" = "YES" ] ; then
2689
		echo "RootInstall: YES"
2690
	else
2691
		echo "RootInstall: NO"
2692
	fi
2693

    
2694
	echo "Version: ${PBI_PROGVERSION}"
2695
	echo "Built: ${PBI_PROGMDATE}"
2696
	echo "Prefix: ${PBI_ORIGPROGDIRPATH}"
2697
	echo "Author: ${PBI_PROGAUTHOR}"
2698
	echo "Website: ${PBI_PROGWEB}"
2699
	echo "Arch: ${PBI_APPARCH}"
2700
	echo "FbsdVer: ${PBI_FBSDVER}"
2701
	echo "CreatorVer: ${PBI_APPCREATEVER}"
2702
	echo "ArchiveCount: ${PBI_ARCHIVE_COUNT}"
2703
	echo "ArchiveSum: ${PBI_ARCHIVE_CHECKSUM}"
2704
	case ${PBI_SIGVALID} in
2705
		0) echo "Signature: Verified" ;;
2706
  	       -1) echo "Signature: Not Signed" ;;
2707
  	        1) echo "Signature: Bad" ;;
2708
		*) echo "Signature: <Unknown>" ;;
2709
	esac
2710

    
2711
	if [ -n "${PBI_REPO}" ] ; then
2712
		local _rDesc="`cat ${PBI_DBREPODIR}/*.${PBI_REPO} | grep "Desc:" | sed 's|Desc: ||g'`"
2713
		local _rID="`ls ${PBI_DBREPODIR}/*.${PBI_REPO}`"
2714
		_rID=`basename $_rID | cut -d '.' -f 1`
2715
		echo "Associated Repo: ${_rID} (${_rDesc})"
2716
	fi
2717
	
2718
	# Check if autoupdate is enable or not
2719
	if [ "${PBI_ENABLEAUTOUPDATE}" = "YES" ] ; then
2720
		echo "AutoUpdate: YES"
2721
	else
2722
		echo "AutoUpdate: NO"
2723
	fi
2724

    
2725
	# See if we have any XDG stuff
2726
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-desktop/install-desktop-icons.sh" ] ; then
2727
		echo "DesktopIcons: YES"
2728
	fi
2729
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-menu/install-menu-icons.sh" ] ; then
2730
		echo "MenuIcons: YES"
2731
	fi
2732
	if [ -e "${PBI_ORIGPROGDIRPATH}/.xdg-mime/install-mime.sh" ] ; then
2733
		echo "MimeRegistration: YES"
2734
	fi
2735

    
2736
}
2737

    
2738
# See if we need to display gui header info
2739
check_pbi_gui_display() {
2740
	if [ "$PBI_ADD_GUIDISPLAY" != "YES" ] ; then return 0 ; fi
2741
	open_header_tmp
2742
	
2743
	pbi_display_gui "$PBI_HEADER_TMPDIR" "COPY"
2744

    
2745
	delete_header_tmp
2746

    
2747
}
2748

    
2749
# Display location of PBI graphics
2750
pbi_display_gui() {
2751
	dir="$1"
2752
	copy="$2"
2753
	if [ -e "${dir}/top-banner.png" ] ; then 
2754
		if [ "$copy" = "COPY" ] ; then
2755
			pbi_guitop="/tmp/.PBI-top.$$.png"
2756
			cp "${dir}/top-banner.png" "$pbi_guitop"
2757
		else
2758
			pbi_guitop="${dir}/top-banner.png"
2759
		fi
2760
		echo "TopBanner: ${pbi_guitop}"
2761
	fi
2762
	if [ -e "${dir}/side-banner.png" ] ; then 
2763
		if [ "$copy" = "COPY" ] ; then
2764
			pbi_guiside="/tmp/.PBI-side.$$.png"
2765
			cp "${dir}/side-banner.png" "$pbi_guiside"
2766
		else
2767
			pbi_guiside="${dir}/side-banner.png"
2768
		fi
2769
		echo "SideBanner: ${pbi_guiside}"
2770
	fi
2771

    
2772
	# Try to find an icon
2773
	ls ${dir}/pbi_icon.* >/dev/null 2>/dev/null
2774
	if [ "$?" = "0" ] ; then
2775
		_iconExt=`ls ${dir}/pbi_icon.* | head -n 1 | awk -F . '{print $NF}'`
2776
		if [ "$copy" = "COPY" ] ; then
2777
			pbi_guiicon="/tmp/.PBI-icon.$$.${_iconExt}"
2778
			cp "${dir}/pbi_icon.${_iconExt}" "$pbi_guiicon"
2779
		else
2780
			pbi_guiicon="${dir}/pbi_icon.${_iconExt}"
2781
		fi
2782
		echo "Icon: ${pbi_guiicon}"
2783
	fi
2784

    
2785
}
2786

    
2787
open_header_tmp() {
2788
	init_tmpdir
2789

    
2790
	# If we have a custom extract dir, use it
2791
	if [ -z "$1" ] ; then
2792
		PBI_HEADER_TMPDIR="${PBI_TMPDIR}/.PBI-header.$$"
2793
	else
2794
		PBI_HEADER_TMPDIR="${1}/.PBI-header.$$"
2795
	fi
2796

    
2797
	if [ -e "${PBI_HEADER_TMPDIR}" ] ; then rm -rf "${PBI_HEADER_TMPDIR}" ; fi
2798
	mkdir -p "${PBI_HEADER_TMPDIR}"
2799
	
2800
	# Extract the header files 
2801
	tar xvf "${PBI_FILENAME}" -C "${PBI_HEADER_TMPDIR}" >/dev/null 2>/dev/null
2802
	if [ "$?" != "0" ] ; then exit_err "Failed to read PBI header! Possible corrupt PBI, or wrong PBI version for this OS." ; fi
2803

    
2804
}
2805

    
2806
delete_header_tmp() {
2807
	if [ -z "${PBI_HEADER_TMPDIR}" ] ; then return 0 ; fi
2808
	if [ -d "${PBI_HEADER_TMPDIR}" ] ; then rm -rf "${PBI_HEADER_TMPDIR}" ; fi
2809
}
2810

    
2811
# Load in all the configuration data from the header
2812
load_info_from_header() {
2813
	open_header_tmp
2814

    
2815
	# Start loading our variables
2816
	load_info_from_dir "${PBI_HEADER_TMPDIR}"
2817

    
2818
	delete_header_tmp
2819
}
2820

    
2821
# See if we need to display scripts
2822
check_pbi_scripts_display() {
2823
	if [ "$PBI_CHECKSCRIPTS" != "YES" ] ; then return 0 ; fi
2824

    
2825
	# Display our scripts
2826
	open_header_tmp
2827
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_PREINS}" ] ; then
2828
		echo -e "\n${MOD_PREINS}:"
2829
		echo "--------------------------------"
2830
		cat "${PBI_HEADER_TMPDIR}/${MOD_PREINS}"
2831
	fi
2832
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}" ] ; then
2833
		echo -e "\n${MOD_POSTINS}:"
2834
		echo "--------------------------------"
2835
		cat "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}"
2836
	fi
2837
	if [ -e "${PBI_HEADER_TMPDIR}/${MOD_PREREM}" ] ; then
2838
		echo -e "\n${MOD_PREREM}:"
2839
		echo "--------------------------------"
2840
		cat "${PBI_HEADER_TMPDIR}/${MOD_PREREM}"
2841
	fi
2842
	delete_header_tmp
2843
}
2844

    
2845
# Load pbi information from the specified directory
2846
load_info_from_dir() {
2847
	REQUIRED_FILES="pbi_defaultpath pbi_name pbi_version pbi_author pbi_web pbi_arch pbi_fbsdver pbi_createver"
2848
	for f in $REQUIRED_FILES
2849
	do
2850
		if [ ! -e "${1}/${f}" ] ; then echo "Warning: Missing file: ${f}" ; fi
2851
	done
2852
        PBI_APPARCH=""
2853
        PBI_APPCREATEVER=""
2854
        PBI_ARCHIVE_CHECKSUM=""
2855
        PBI_ARCHIVE_COUNT=""
2856
	PBI_ENABLEAUTOUPDATE=""
2857
        PBI_FBSDVER=""
2858
	PBI_ORIGPROGDIRPATH=""
2859
	PBI_PATCHMDATE=""
2860
	PBI_PATCHVERSION=""
2861
	PBI_PATCHTARGET=""
2862
	PBI_PROGNAME=""
2863
        PBI_PROGVERSION=""
2864
        PBI_PROGAUTHOR=""
2865
        PBI_PROGMDATE=""
2866
        PBI_PROGWEB=""
2867
	PBI_REPO=""
2868
	PBI_REQUIRESROOT=""
2869
	PBI_SIGVALID=""
2870

    
2871
	PBI_ORIGPROGDIRPATH="`cat ${1}/pbi_defaultpath`"
2872
        PBI_PROGNAME="`cat ${1}/pbi_name`"
2873
        PBI_PROGVERSION="`cat ${1}/pbi_version`"
2874
        PBI_PROGAUTHOR="`cat ${1}/pbi_author`"
2875
        PBI_PROGWEB="`cat ${1}/pbi_web 2>/dev/null`"
2876
        PBI_PROGMDATE="`cat ${1}/pbi_mdate 2>/dev/null`"
2877
        PBI_APPARCH="`cat ${1}/pbi_arch 2>/dev/null`"
2878
        PBI_FBSDVER="`cat ${1}/pbi_fbsdver 2>/dev/null`"
2879
        PBI_APPCREATEVER="`cat ${1}/pbi_createver 2>/dev/null`"
2880
        PBI_ARCHIVE_COUNT="`cat ${1}/pbi_archivecount 2>/dev/null`"
2881
        PBI_ARCHIVE_CHECKSUM="`cat ${1}/pbi_archivesum 2>/dev/null`"
2882

    
2883
	# Check if auto-update is enabled
2884
	if [ -e "${1}/autoupdate-enable" ] ; then
2885
		PBI_ENABLEAUTOUPDATE="YES"
2886
	fi
2887

    
2888
	# Does this PBI need to be installed as root
2889
	if [ -e "${1}/pbi_requiresroot" ] ; then
2890
		PBI_REQUIRESROOT="YES"
2891
	fi
2892
	
2893
	# Check if this is a patch file
2894
	if [ -e "${1}/pbi_patchfile" ] ; then
2895
        	PBI_PATCHVERSION=`cat ${1}/pbi_patchfile | cut -d ':' -f 2`
2896
		PBI_PATCHTARGET=`cat ${1}/pbi_patchfile | cut -d ':' -f 1`
2897
	fi
2898
	
2899
	# Check if this associates with a particular repo
2900
	if [ -e "${1}/pbi_repo" ] ; then
2901
        	PBI_REPO=`cat ${1}/pbi_repo`
2902
	fi
2903

    
2904
	# See if this patch is for a particular mdate
2905
	if [ -e "${1}/pbi_patchmdate" ] ; then
2906
        	PBI_PATCHMDATE=`cat ${1}/pbi_patchmdate`
2907
	fi
2908

    
2909
	# See if this PBI was signed
2910
	if [ -e "${1}/pbi_archivesum.sha1" ] ; then
2911
		check_valid_sigs "${1}"
2912
		if [ "$?" = "0" ] ; then
2913
			PBI_SIGVALID="0"
2914
		else
2915
			PBI_SIGVALID="1"
2916
		fi
2917
	else
2918
		PBI_SIGVALID="-1"
2919
	fi
2920
}
2921

    
2922
# Start installing the PBI
2923
do_pbi_add() {
2924
	pbi_verify_signatures
2925
	pbi_verify_archivesum
2926

    
2927
	check_preinstall_script
2928

    
2929
	mk_pbi_extract_dir
2930
	pbi_extract_archive
2931
	
2932
	pbi_add_check_gids
2933
	pbi_add_check_uids
2934

    
2935
	pbi_add_run_script
2936
	check_postinstall_script
2937

    
2938
	pbi_add_register_app
2939

    
2940
	# Be sure to let the pbid know we have a new hash-dir to register
2941
	add_hashdir_trigger
2942

    
2943
	clean_remote_dl
2944
}
2945

    
2946
# Check for any GIDs we need to create
2947
pbi_add_check_gids() {
2948
	if [ ! -e "${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}" ] ; then return ; fi
2949
	runUID=`id -u`
2950

    
2951
	while read gidLine
2952
	do
2953
		gName=`echo $gidLine | cut -d ':' -f 1`
2954
		gID=`echo $gidLine | cut -d ':' -f 3`
2955
		gUsers=`echo $gidLine | cut -d ':' -f 4`
2956

    
2957
		# Is this group already on the system?
2958
		pw groupshow $gName >/dev/null 2>/dev/null
2959
		if [ $? -eq 0 ] ; then 
2960
			echo "Using existing group: $gName"
2961
		else
2962
			# Are we installing as root?
2963
			if [ "$runUID" != "0" ] ; then
2964
				echo "Please create group \"$gName\" manually or re-install PBI as root."
2965
			else
2966
				echo "Adding group: $gName"
2967
				pw groupadd $gName -g $gID;
2968
			fi
2969
		fi
2970

    
2971
		if [ -n "$gUsers" ] ; then
2972
			for gUser in `echo $gUsers | sed 's|,| |g'`
2973
			do
2974
				pw groupshow ${gName} | grep -qw ${gUser}
2975
				if [ $? -ne 0 ] ; then
2976
					# Are we installing as root?
2977
					if [ "$runUID" != "0" ] ; then
2978
						echo "Please add user \"$gUser\" to group \"$gName\" manually or re-install PBI as root."
2979
						continue
2980
					fi
2981

    
2982
					echo "Adding user ${gUser} to group ${gName}"
2983
					pw groupmod ${gName} -m ${gUser}
2984
				fi
2985
			done
2986
		fi
2987
	done < ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}
2988
}
2989

    
2990
# Check for any UIDs we need to create
2991
pbi_add_check_uids() {
2992
	if [ ! -e "${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}" ] ; then return ; fi
2993
	runUID=`id -u`
2994

    
2995
	while read uidLine
2996
	do
2997
		uName=`echo $uidLine | cut -d ':' -f 1`
2998

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

    
3003
		# Are we installing as root?
3004
		if [ "$runUID" != "0" ] ; then
3005
			echo "Please create user \"$uName\" manually or re-install PBI as root."
3006
			continue
3007
		fi
3008

    
3009
		uID=`echo $uidLine | cut -d ':' -f 3`
3010
		gID=`echo $uidLine | cut -d ':' -f 4`
3011
		uClass=`echo $uidLine | cut -d ':' -f 5`
3012
		uGecos=`echo $uidLine | cut -d ':' -f 8`
3013
		uHomedir=`echo $uidLine | cut -d ':' -f 9 | sed "s|^/usr/local|${PBI_PROGDIRPATH}|"`
3014
		uShell=`echo $uidLine | cut -d ':' -f 10`
3015

    
3016
		echo "Adding user: $uName"
3017
		pw useradd $uName -u $uID -g $gID $uClass -c "$uGecos" -d $uHomedir -s $uShell;
3018

    
3019
		# Create homedir
3020
		case $uHomedir in 
3021
			/nonexistent|/var/empty) ;; 
3022
			*) install -d -g $gID -o $uID $uHomedir ;;
3023
		esac 
3024
	done < ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}
3025
}
3026

    
3027
add_hashdir_trigger() {
3028
	get_dbdir
3029
        _htrig=`echo ${APPDBDIR} | sed "s|${PBI_DBAPPDIR}|${PBI_DBHASHQUEUEDIR}|g"`
3030
	if [ ! -e "${_htrig}" ] ; then
3031
		touch "${_htrig}"
3032
	fi
3033
}
3034

    
3035
# Run the install script if exists
3036
pbi_add_run_script() {
3037

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

    
3041
	insc="${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/.pbi-install.sh"
3042
	if [ ! -e "${insc}" ] ; then return 0 ; fi
3043
	export_script_vars
3044
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3045
		${insc}
3046
	else
3047
		${insc} >/dev/null 2>/dev/null
3048
	fi
3049

    
3050
}
3051

    
3052
# If we need to, update the hashdir
3053
pbi_add_update_hashdir() {
3054
	if [ "${PBI_NOHASHDIR}" = "YES" ] ; then return 0 ; fi
3055
	if [ ! -e "${1}/${PBI_HASHLIST}" ] ; then return 0; fi
3056

    
3057
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3058
		echo "HASHCOUNT: `wc -l ${1}/${PBI_HASHLIST} | tr -d ' ' | cut -d '/' -f 1`"
3059
	else
3060
	
3061
		echo -e "Merging with hashdir...\c"
3062
	fi
3063
	
3064
	# Read the hashfile, and start making links to identical files
3065
	while read hl
3066
	do
3067
		file="`echo $hl | sed 's/:::.*$//g'`"
3068

    
3069
		# If we are trying to merge a PBI which was deleted, stop
3070
		if [ -n "${2}" -a -e "${2}" ] ; then
3071
			echo "HASHDONE - Deleted" 
3072
			return
3073
		fi
3074

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

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

    
3081
		if [ -f "${PBI_HASHDIR}/${hl}" ] ; then
3082
			use_hashfile "$hl" "${1}/$file"
3083
		else
3084
			mv_ln_hashfile "$hl" "${1}/$file"
3085
		fi
3086
	done < "${1}/${PBI_HASHLIST}"
3087

    
3088
	if [ "$PBI_VERBOSE" = "YES" ] ; then 
3089
		echo "HASHDONE"
3090
	else 
3091
		echo -e "Done!" 
3092
	fi
3093
}
3094

    
3095
# Use an existing hashfile
3096
use_hashfile() {
3097
	tfile="$1"
3098
	file="$2"
3099
	dir="`dirname ${tfile}`"
3100
	if [ ! -d "${PBI_HASHDIR}/${dir}" ] ; then
3101
		mkdir -p ${PBI_HASHDIR}/${dir}
3102
	fi
3103

    
3104
	# We have a match!
3105
	ln -f "${PBI_HASHDIR}/${tfile}" "${file}"
3106
	if [ $? -ne 0 ] ; then 
3107
		echo "Warning: Unable to make hash-link ${PBI_HASHDIR}/${tfile} -> ${file}"
3108
		return
3109
	fi
3110
	
3111
	# Make sure the hard-linked file doesn't get changed
3112
	chmod u-w,g-w,o-w "${file}"
3113
	if [ $? -ne 0 ] ; then 
3114
		echo "Warning: Unable to chmod ${file}"
3115
		return
3116
	fi
3117
	
3118
}
3119

    
3120
# New file we can save to hashdir
3121
mv_ln_hashfile() {
3122
	tfile="$1"
3123
	file="$2"
3124
	dir="`dirname ${tfile}`"
3125
	if [ ! -d "${PBI_HASHDIR}/${dir}" ] ; then
3126
		mkdir -p ${PBI_HASHDIR}/${dir}
3127
	fi
3128

    
3129
	ln -f "${file}" "${PBI_HASHDIR}/${tfile}"
3130
	if [ $? -ne 0 ] ; then 
3131
		echo "Warning: Unable to make hash-link ${file} -> ${PBI_HASHDIR}/${tfile}"
3132
		return
3133
	fi
3134

    
3135
	# Make sure the hard-linked file doesn't get changed
3136
	chmod u-w,g-w,o-w "${file}"
3137
	if [ $? -ne 0 ] ; then 
3138
		echo "Warning: Unable to chmod ${file}"
3139
		return
3140
	fi
3141

    
3142
	# Make sure the hard-linked file doesn't get changed
3143
	chmod u-w,g-w,o-w "${PBI_HASHDIR}/${tfile}"
3144
	if [ $? -ne 0 ] ; then 
3145
		echo "Warning: Unable to chmod ${PBI_HASHDIR}/${tfile}"
3146
		return
3147
	fi
3148

    
3149
	if [ "$PBI_VERBOSE" = "YES" ] ; then echo "L" ; fi
3150
}
3151

    
3152
# Return the dbdir for this PBI
3153
get_dbdir() {
3154
	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
3155
        APPDBDIR="${PBI_DBAPPDIR}/${tmp}-${PBI_PROGVERSION}-${PBI_APPARCH}"
3156
}
3157

    
3158
# Register this app as installed
3159
pbi_add_register_app() {
3160
	if [ ! -d "$PBI_DBAPPDIR" ] ; then mkdir -p ${PBI_DBAPPDIR} ; fi
3161
        open_header_tmp
3162
	get_dbdir
3163
	dir="${APPDBDIR}"
3164

    
3165
	# Make sure we remove any existing meta-data if forcing an installation
3166
	if [ "$PBI_FORCEADD" = "YES" ] ; then
3167
	  	tmp="`echo ${PBI_PROGNAME} | tr -d ' ' | tr '[A-Z]' '[a-z]'`"
3168
          	rm -rf ${PBI_DBAPPDIR}/${tmp}-*-${PBI_APPARCH}
3169
	fi
3170

    
3171
	mkdir -p "${dir}"
3172
	
3173
        tar cvf - -C "${PBI_HEADER_TMPDIR}" . 2>/dev/null | tar xvf - -C "$dir" 2>/dev/null
3174

    
3175
	# If this was a patch, use the original path
3176
	if [ -n "${PBI_ORIGPROGDIRPATH}" ] ; then
3177
		echo "${PBI_ORIGPROGDIRPATH}" >${dir}/pbi_installedpath
3178
	else
3179
		echo "${PBI_PROGDIRPATH}" >${dir}/pbi_installedpath
3180
	fi
3181

    
3182
	# See which repo / key this PBI associates to, if any
3183
	check_valid_sigs "${dir}"
3184
	if [ -n "$PBI_VALIDKEYSIG" ] ; then
3185
		_rMd5="`echo ${PBI_VALIDKEYSIG} | cut -d '.' -f 1`"
3186
		echo "$_rMd5" | sed "s|${PBI_DBKEYDIR}/||g" > ${dir}/pbi_repo
3187
	fi
3188

    
3189
	# Dont need any patch version info
3190
	if [ -e "${dir}/pbi_patchfile" ] ; then
3191
		rm "${dir}/pbi_patchfile"
3192
	fi
3193

    
3194
        delete_header_tmp
3195

    
3196
	echo "Installed: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3197
}
3198

    
3199
# Check if we have a postinstall script we need to use
3200
check_postinstall_script() {
3201
        open_header_tmp
3202

    
3203
        if [ ! -e "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}" ] ; then
3204
                delete_header_tmp
3205
                return 0
3206
        fi
3207

    
3208
        export_script_vars
3209
        sh "${PBI_HEADER_TMPDIR}/${MOD_POSTINS}"
3210
        delete_header_tmp
3211
}
3212

    
3213
# Check if we have a preinstall script we need to use
3214
check_preinstall_script() {
3215
	open_header_tmp
3216

    
3217
	if [ ! -e "${PBI_HEADER_TMPDIR}/${MOD_PREINS}" ] ; then 
3218
		delete_header_tmp
3219
		return 0 
3220
	fi
3221

    
3222
	export_script_vars
3223
	sh "${PBI_HEADER_TMPDIR}/${MOD_PREINS}"
3224
	if [ "$?" != "0" ] ; then
3225
        	delete_header_tmp
3226
		exit_err "${MOD_PREINS} returned error status"
3227
	fi
3228
        delete_header_tmp
3229
}
3230

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

    
3238
}
3239

    
3240
# Check if we have valid signatures, and return "0" if success, "1" if failure
3241
check_valid_sigs() {
3242
	PBI_VALIDKEYSIG=""
3243

    
3244
	for _pk in ${PBI_PUBKEYS}
3245
	do
3246
		good="true"
3247
		_sf="${1}/pbi_archivesum ${1}/${MOD_PREINS} ${1}/${MOD_POSTINS} ${1}/${MOD_PREREM}"
3248
       		for _ts in $_sf
3249
        	do
3250
                	openssl dgst -sha1 \
3251
                        -verify ${_pk} \
3252
                        -signature ${_ts}.sha1 \
3253
                        ${_ts} >/dev/null 2>/dev/null
3254
			if [ "$?" != "0" ] ; then
3255
				good="false" ; break
3256
			fi
3257
			PBI_VALIDKEYSIG="$_pk"
3258
		done
3259
		if [ "$good" = "true" ] ; then return 0 ; fi
3260
        done
3261
	return 1	
3262
}
3263

    
3264
# Verify if the archive checksum is good
3265
pbi_verify_archivesum() {
3266
	if [ "${PBI_SKIPCHECKSUM}" = "YES" ] ; then return 0 ; fi
3267
	echo -e "Verifying Checksum...\c"
3268

    
3269
        pbi_find_archive_header
3270
	sum=`tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | sha256 -q`
3271
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3272
		echo "Archive checksum: ${sum}"
3273
		echo "Saved checksum: ${PBI_ARCHIVE_CHECKSUM}"
3274
	fi
3275
	if [ "$sum" != "$PBI_ARCHIVE_CHECKSUM" ] ; then
3276
		exit_err "${PBI_FILENAME} failed checksum, the archive may be corrupt."
3277
	fi
3278
	echo -e "OK"
3279

    
3280
}
3281

    
3282
# Make our PBI extraction dir
3283
mk_pbi_extract_dir() {
3284
	PBI_EXTRACTDIR="${PBI_PROGDIRPATH}"
3285
	if [ -e "${PBI_EXTRACTDIR}" ] ; then
3286
               rm -rf "$PBI_EXTRACTDIR"
3287
	fi
3288
	mkdir -p "${PBI_EXTRACTDIR}" >/dev/null 2>/dev/null
3289
	if [ "$?" != "0" ] ; then 
3290
		exit_err "Failed to create directory: ${PBI_PROGDIRPATH}"
3291
	fi
3292
}
3293

    
3294
pbi_find_archive_header() {
3295
	# Find the header for the archive
3296
	# SEARCH FOR: $PBI_SS_ARCHIVE
3297
	PBI_SKIP_ARCHLINES=`awk "/^${PBI_SS_ARCHIVE}/ { print NR + 1; exit 0; }" "${PBI_FILENAME}"`
3298
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3299
		echo "SKIP_ARCHLINES: $PBI_SKIP_ARCHLINES"
3300
	fi
3301
}
3302

    
3303
# Extract the PBI archive file
3304
pbi_extract_archive() {
3305
	pbi_find_archive_header	
3306

    
3307
	echo "Extracting to: ${PBI_EXTRACTDIR}"
3308
	tar="xvf -"
3309

    
3310
	if [ "$PBI_VERBOSE" = "YES" ] ; then
3311
		echo "TOTALFILES: ${PBI_ARCHIVE_COUNT}"
3312
		tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar ${tar} -C "${PBI_EXTRACTDIR}"
3313
		err="$?"
3314
	else
3315
		tail +$PBI_SKIP_ARCHLINES "${PBI_FILENAME}" | tar ${tar} -C "${PBI_EXTRACTDIR}" >/dev/null 2>/dev/null
3316
		err="$?"
3317
	fi
3318
	
3319
	if [ "$err" != "0" ] ; then exit_err "Failed extracting ${PBI_FILENAME}" ; fi
3320

    
3321
	if [ "$PBI_VERBOSE" = "YES" ] ; then echo "Extraction Finished!" ; fi
3322

    
3323
	# If this is an extract only, do it and exit
3324
	if [ "${PBI_EXTRACTONLY}" = "YES" ] ; then exit_trap ; fi
3325
}
3326
	
3327

    
3328
# Starting pbi_create
3329
pbi_create_init() {
3330

    
3331
	require_root
3332

    
3333
	parse_create_pbi_cmdline "$@"
3334

    
3335
	# If we are making a backup copy of an installed PBI
3336
	if [ "$PBI_CBACKUP" = "YES" ] ; then
3337
		init_tmpdir
3338
		do_pbi_create_backup
3339
		exit_trap
3340
	fi
3341

    
3342
	PBI_CREATEONLY="YES"
3343

    
3344
	load_pbi_conffile
3345

    
3346
	parse_cmdline_overrides
3347

    
3348
	check_create_required_vars
3349

    
3350
	do_pbi_create
3351
}
3352

    
3353
# Start the pbi_create backup process
3354
do_pbi_create_backup() {
3355

    
3356
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_CBACKUPTARGET}"
3357
	echo "Creating backup PBI: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3358

    
3359
	# Start by making a fresh archive of the installed PBI
3360
	PBI_STAGEDIR="$PBI_ORIGPROGDIRPATH"
3361
	mk_archive_file
3362

    
3363
	# Now make the header dir
3364
	_hDir="${PBI_TMPDIR}/.header.$$"
3365
	PBI_HEADERDIR="${_hDir}"
3366
	mkdir -p "${_hDir}"
3367
	cp ${PBI_DBAPPDIR}/${PBI_CBACKUPTARGET}/* "${_hDir}"
3368
	rm ${_hDir}/*.sha1 >/dev/null 2>/dev/null
3369

    
3370
	# Get the total number of files in the STAGEDIR
3371
	get_filetotal_dir "${PBI_STAGEDIR}"
3372
	echo "${FILETOTAL}" > "${PBI_HEADERDIR}/pbi_archivecount"
3373

    
3374
	# Save a checksum of archive file
3375
	sha256 -q "${PBI_CREATE_ARCHIVE}" > "${PBI_HEADERDIR}/pbi_archivesum"
3376

    
3377
	# Sign any header files
3378
	sign_pbi_files "$PBI_HEADERDIR"
3379

    
3380
	# Make the header archive
3381
	mk_header_file
3382

    
3383
	# Remove the new headerdir
3384
	rm -rf "$PBI_HEADERDIR"
3385
	
3386
	# Now finish up and make the resulting PBI file
3387
	mk_output_pbi
3388

    
3389
}
3390

    
3391

    
3392
# Vars required for creation
3393
check_create_required_vars() {
3394
	if [ -z "${PBI_PROGNAME}" ] ; then exit_err "Missing PBI_PROGNAME"; fi
3395
	if [ -z "${PBI_PROGVERSION}" ] ; then exit_err "Missing PBI_PROGVERSION"; fi
3396
	if [ -z "${PBI_PROGAUTHOR}" ] ; then exit_err "Missing PBI_PROGAUTHOR"; fi
3397
	if [ -z "${PBI_PROGWEB}" ] ; then exit_err "Missing PBI_PROGWEB"; fi
3398
}
3399

    
3400
# Start the pbi_create process
3401
do_pbi_create() {
3402
	echo "Creating PBI: ${PBI_PROGNAME}-${PBI_PROGVERSION}"
3403

    
3404
	mk_header_dir
3405
	mk_stage_dir
3406
	
3407
	copy_resource_dir
3408
	clean_stage_dir
3409

    
3410
	mk_extlink_entries
3411
	mk_xdg_scripts
3412

    
3413
	mk_install_script
3414
	mk_deinstall_script
3415

    
3416
	mk_hash_list
3417

    
3418
	mk_archive_file
3419
 	save_pbi_details_to_header
3420
	mk_header_file
3421
	mk_output_pbi
3422

    
3423
	rm_header_dir
3424
	rm_stage_dir
3425
}
3426

    
3427
# Start looping through and creating a hash-list of files
3428
mk_hash_list() {
3429
  	if [ "${PBI_CREATE_HASHLIST}" = "NO" ] ; then return 0 ; fi
3430
	echo "Creating hash list..."
3431

    
3432
	hashfile="${PBI_STAGEDIR}/${PBI_HASHLIST}"
3433

    
3434
	if [ -e "${hashfile}" ] ; then rm "${hashfile}" ; fi
3435

    
3436
	for hdir in ${HASH_SEARCH_DIRS}
3437
	do
3438
		if [ ! -d "${PBI_STAGEDIR}/${hdir}" ] ; then continue ; fi
3439
	 	save_dir_hash_list "${hdir}" "${hashfile}"	
3440
	done
3441
}
3442

    
3443
#  Read the specified directory and save hashsums of each file
3444
save_dir_hash_list() {
3445
	cd ${PBI_STAGEDIR}
3446
	tmp_hashdir="${PBI_STAGEDIR}/.tmp-hash.$$"
3447
	find "${1}" -type f > ${tmp_hashdir}
3448
	while read line
3449
	do
3450
		if [ ! -f "$line" -o -h "$line" ] ; then continue ; fi
3451
		
3452
		# Make sure this isn't a binary executable
3453
		file "${line}" | grep "executable," >/dev/null 2>/dev/null
3454
		if [ "$?" = "0" ] ; then continue ; fi
3455

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

    
3460
		# Check if this hash file is excluded
3461
		_hfound="0"
3462
		if [ -n "${PBI_HASH_EXCLUDES}" ] ; then
3463
			for _hexcl in ${PBI_HASH_EXCLUDES}
3464
			do
3465
				if [ "$_hexcl" = "$line" ] ; then
3466
					_hfound="1"
3467
				fi
3468
			done
3469
			if [ "$_hfound" = "1" ] ; then
3470
				continue
3471
			fi
3472
		fi	
3473

    
3474
		# Get the file size
3475
		tSize=`du -k "${line}" | awk '{print $1}'`
3476
		if [ $(is_num "$tSize") ] ; then 
3477
			# If the file is less than 10Kb, we can skip
3478
			if [ $tSize -lt 10 ] ; then continue ; fi
3479

    
3480
			# Add to the hash-dir
3481
	 		sha=`sha256 -q "$line"`
3482
			echo "${line}:::${sha}" >> ${2}
3483
		fi
3484
	done < ${tmp_hashdir}
3485
	rm ${tmp_hashdir}
3486
	cd /
3487
}
3488

    
3489
# Parse any external link directives
3490
mk_extlink_entries() {
3491
	echo "Creating external link entries..."
3492
	init_tmpdir
3493
	_extf="${PBI_CONFDIR}/${MOD_EXTLINKFILE}"
3494
	_autoextf="${PBI_STAGEDIR}/${MOD_AUTOEXTLINKFILE}"
3495
	_tmpextf="${PBI_TMPDIR}/${MOD_AUTOEXTLINKFILE}.$$"
3496
  	if [ ! -e "${_extf}" -a ! -e "${_autoextf}" ] ; then return 0 ; fi
3497

    
3498
	dir="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}"
3499
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3500

    
3501
	# Create the headers for the PATH link scripts
3502
        echo "#!/bin/sh" >"${dir}/${PBI_INS_PATHSCRIPT}"
3503
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_PATHSCRIPT}"
3504

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

    
3509
	touch "$_tmpextf"
3510
	if [ -e "$_autoextf" ]; then cat "${_autoextf}" >> "${_tmpextf}" ; fi
3511
	if [ -e "$_extf" ]; then cat "${_extf}" >> "${_tmpextf}" ; fi
3512

    
3513
        while read line
3514
        do
3515
		_bin="NO"
3516
		_wraponly="NO"
3517
		_crashhandle="YES"
3518
		_keep="YES"
3519
		_linux="NO"
3520
                echo $line | tr '\t' ' ' | tr -s ' ' | grep "^#" >/dev/null 2>/dev/null
3521
                if [ "$?" != "0" ] ; then
3522
                        src="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 1`"
3523
                        tar="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 2`"
3524
                        act="`echo $line | tr '\t' ' ' | tr -s ' ' | cut -d ' ' -f 3`"
3525

    
3526
			if [ -z "$src" -o -z "$tar" ] ; then continue ; fi
3527

    
3528
			if [ ! -e "${PBI_STAGEDIR}/$src" ] ; then
3529
				echo "WARN: external_link target: \"$src -> $tar $act\" does not exist!"
3530
				continue
3531
			fi
3532

    
3533
			# Check for act directives
3534
			for i in `echo ${act} | sed 's|,| |g'`
3535
  			do
3536
				case ${i} in
3537
					binary) _bin="YES" ;;
3538
	  			    binwrapper) _bin="YES" ; _wraponly="YES" ;;
3539
				       nocrash) _crashhandle="NO" ;;
3540
				          keep) _keep="YES" ;;
3541
				       replace) _keep="NO" ;;
3542
				         linux) _bin="YES" ; _linux="YES" ;;
3543
					*) echo "Warning: Unknown option \"$i\" in ${MOD_EXTLINKFILE}";;
3544
				esac
3545
				
3546
			done
3547

    
3548
			# Make sure SYS_LOCALBASE/$tar dir exists
3549
			echo "_bd=\"\`dirname \$SYS_LOCALBASE/$tar\`\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3550
			echo "if [ ! -d \"\$_bd\" ] ; then" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3551
			echo "	mkdir -p \"\${_bd}\"" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3552
			echo "fi" >> "${dir}/${PBI_INS_PATHSCRIPT}"
3553

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

    
3557
				# Make sure we don't create any duplicates
3558
				echo "$_donewrap" | grep "#${src}#" >/dev/null 2>/dev/null
3559
				if [ "$?" = "0" ] ; then continue ; fi
3560
				
3561
				# Make the binary wrapper
3562
				mk_path_wrappers "$src" "$tar" "$_crashhandle" "$_wraponly" "$_linux"
3563

    
3564
				# This binary is done, save it now so we don't duplicate later
3565
				_donewrap="$_donewrap #${src}#"
3566
			else
3567
				# Make our link commands
3568
				if [ "$_keep" = "YES" ] ; then _lop="-fs"; else _lop="-s"; fi
3569
				echo "ln ${_lop} $PBI_PROGDIRPATH/${src} \$SYS_LOCALBASE/${tar}" \
3570
					>> "${dir}/${PBI_INS_PATHSCRIPT}"
3571
			fi
3572

    
3573
			# Make the uninstall command
3574
			echo "ls -al \"\$SYS_LOCALBASE/$tar\" | grep \"> $PBI_PROGDIRPATH\" >/dev/null 2>/dev/null " \
3575
				>> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3576
			echo "if [ \"\$?\" = \"0\" ] ; then" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3577
			echo "	rm \"\$SYS_LOCALBASE/${tar}\"" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3578
			echo "fi" >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3579

    
3580
			echo " " >> "${dir}/${PBI_INS_PATHSCRIPT}"
3581
			echo " " >> "${dir}/${PBI_UNINS_PATHSCRIPT}"
3582

    
3583

    
3584

    
3585
                fi
3586

    
3587
        done < "${_tmpextf}"
3588
	rm "${_tmpextf}"
3589

    
3590
	chmod 755 "${dir}/${PBI_INS_PATHSCRIPT}"
3591
	chmod 755 "${dir}/${PBI_UNINS_PATHSCRIPT}"
3592
}
3593

    
3594

    
3595
# Create the wrapper scripts for the specified binaries 
3596
mk_path_wrappers() {
3597
	dir="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}"
3598
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3599

    
3600
	bin="${1}"
3601
	fbin="`basename ${bin}`"
3602
	tar="${2}"
3603
	ch="${3}"
3604
	onlywrap="${4}"
3605
	linwrap="${5}"
3606

    
3607
	# Check if the fake-bin wrapper already exists, and if so use
3608
	# a different name
3609
	if [ -e "${dir}/${fbin}" ] ; then
3610
		fbin=`echo $bin | sed 's|/|-|g'`
3611
	fi
3612

    
3613
	# Make our link to the system localbase if its not a wrapper only
3614
 	if [ "$onlywrap" != "YES" ] ; then	
3615
		echo "ln -fs $PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${fbin} \$SYS_LOCALBASE/${tar}" \
3616
			>> "${dir}/${PBI_INS_PATHSCRIPT}"
3617
	fi
3618

    
3619
	# Copy the wrapper binary
3620
	cp ${PBI_WRAPPERFILE} ${dir}/${fbin}
3621
	chmod 755 ${dir}/${fbin}
3622

    
3623
	# Create the wrapper .pbiopt
3624
	echo "PROGDIR: ${PBI_PROGDIRPATH}" >${dir}/${fbin}.pbiopt
3625
	echo "TARGET: ${bin}" >>${dir}/${fbin}.pbiopt
3626

    
3627
	# Figure out the extra ldconfig dirs
3628
	LDCONFIGDIRS=""
3629
	if [ -d "${PBI_STAGEDIR}/libdata/ldconfig" ] ; then
3630
	  for _ldc in `ls ${PBI_STAGEDIR}/libdata/ldconfig 2>/dev/null`
3631
 	  do
3632
   	     while read TMP
3633
  	     do
3634
      	       echo $LDCONFIGDIRS | grep "${TMP}:" >/dev/null 2>/dev/null
3635
      	       if [ "$?" != "0" ]; then
3636
        	 LDCONFIGDIRS="${TMP}:${LDCONFIGDIRS}"
3637
     	       fi
3638
    	     done < ${PBI_STAGEDIR}/libdata/ldconfig/${_ldc}
3639
          done
3640
        fi
3641

    
3642
	# If this is marked as a linux app, make sure we point to the linux libs first
3643
	if [ "$linwrap" = "YES" ] ; then
3644
	  LDCONFIGDIRS="${PROGDIR}/linuxlib"
3645
	fi
3646

    
3647
	# Create the wrapper .ldhints
3648
	echo "${LDCONFIGDIRS}" >${dir}/${fbin}.ldhints
3649
}
3650

    
3651
# Create any XDG script for install / deinstall
3652
mk_xdg_scripts() {
3653
 	echo "Creating xdg scripts..."
3654
  	mk_xdg_desktop_script
3655
  	mk_xdg_menu_script
3656
  	mk_xdg_mime_script
3657
}
3658

    
3659
# Create any XDG script for desktop icons
3660
mk_xdg_desktop_script() {
3661
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGDESK_DIR}" ] ; then return 0 ; fi
3662
	_dFound=0
3663

    
3664
	dir="${PBI_STAGEDIR}/${PBI_APPDESK_DIR}"
3665
	if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3666
	echo "#!/bin/sh" >"${dir}/${PBI_INS_DESKSCRIPT}"
3667
	echo "#!/bin/sh" >"${dir}/${PBI_UNINS_DESKSCRIPT}"
3668

    
3669
  	cd "${PBI_CONFDIR}/${MOD_XDGDESK_DIR}"
3670
  	for i in `ls *.desktop 2>/dev/null`
3671
  	do
3672
		_dFound=1
3673

    
3674
		# Copy over the .desktop file, modifying any variables within
3675
	        cat "${i}" \
3676
           	| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
3677
		| sed "s|%%PBI_APPDIR%%|$PBI_PROGDIRPATH|g" \
3678
		> "${dir}/PBI-${i}"
3679

    
3680
		ifi="$PBI_PROGDIRPATH/${PBI_APPDESK_DIR}/PBI-${i}"
3681

    
3682
		echo "xdg-desktop-icon install --novendor ${ifi}" \
3683
			 >> "${dir}/${PBI_INS_DESKSCRIPT}"
3684
		echo "xdg-desktop-icon uninstall ${ifi}" \
3685
			 >> "${dir}/${PBI_UNINS_DESKSCRIPT}"
3686
		
3687
  	done
3688

    
3689
	chmod 755 "${dir}/${PBI_INS_DESKSCRIPT}"
3690
	chmod 755 "${dir}/${PBI_UNINS_DESKSCRIPT}"
3691

    
3692
	# No desktop entries
3693
        if [ "$_dFound" = "0" ] ; then
3694
                rm "${dir}/${PBI_INS_DESKSCRIPT}"
3695
                rm "${dir}/${PBI_UNINS_DESKSCRIPT}"
3696
        fi
3697
}
3698

    
3699
# Create any XDG script for menu icons
3700
mk_xdg_menu_script() {
3701
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGMENU_DIR}" ] ; then return 0 ; fi
3702

    
3703
	_mFound=0
3704

    
3705
	dir="${PBI_STAGEDIR}/${PBI_APPMENU_DIR}"
3706
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3707
        echo "#!/bin/sh" >"${dir}/${PBI_INS_MENUSCRIPT}"
3708
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_MENUSCRIPT}"
3709

    
3710
  	cd "${PBI_CONFDIR}/${MOD_XDGMENU_DIR}"
3711
  	for i in `ls *.desktop 2>/dev/null`
3712
  	do
3713
		_mFound=1
3714

    
3715
		# Copy the desktop file, changing any included vars
3716
	        cat "${i}" \
3717
           	| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
3718
		| sed "s|%%PBI_APPDIR%%|$PBI_PROGDIRPATH|g" \
3719
		> "${dir}/PBI-${i}"
3720

    
3721
		ifi="$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/PBI-${i}"
3722

    
3723
		# Check for a .directory file associated with this .desktop
3724
		ifd=""
3725
		dirfile="`basename -s .desktop ${i}`"
3726
		if [ -e "${dirfile}.directory" ] ; then
3727
	        	cat "${dirfile}.directory" \
3728
           		| sed "s|%%PBI_EXEDIR%%|$PBI_PROGDIRPATH/$PBI_FAKEBIN_DIR|g" \
3729
			| sed "s|%%PBI_APPDIR%%|$PBI_PROGDIRPATH|g" \
3730
			> "${dir}/PBI-${dirfile}.directory"
3731
			#cp "${dirfile}.directory" "${dir}/PBI-${dirfile}.directory"
3732
			ifd="$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/PBI-${dirfile}.directory "	
3733
		fi
3734

    
3735
		echo "xdg-desktop-menu install --novendor ${ifd}${ifi}" \
3736
			 >> "${dir}/${PBI_INS_MENUSCRIPT}"
3737
		echo "xdg-desktop-menu uninstall ${ifd}${ifi}" \
3738
			 >> "${dir}/${PBI_UNINS_MENUSCRIPT}"
3739

    
3740
  	done
3741

    
3742
	chmod 755 "${dir}/${PBI_INS_MENUSCRIPT}"
3743
	chmod 755 "${dir}/${PBI_UNINS_MENUSCRIPT}"
3744

    
3745
	# No mime entries
3746
        if [ "$_mFound" = "0" ] ; then
3747
                rm "${dir}/${PBI_INS_MENUSCRIPT}"
3748
                rm "${dir}/${PBI_UNINS_MENUSCRIPT}"
3749
        fi
3750
}
3751

    
3752
# Create any XDG script for mime types
3753
mk_xdg_mime_script() {
3754
  	if [ ! -d "${PBI_CONFDIR}/${MOD_XDGMIME_DIR}" ] ; then return 0 ; fi
3755
	_mFound=0
3756

    
3757
        dir="${PBI_STAGEDIR}/${PBI_APPMIME_DIR}"
3758
        if [ ! -d "${dir}" ] ; then mkdir -p "${dir}" ; fi
3759
        echo "#!/bin/sh" >"${dir}/${PBI_INS_MIMESCRIPT}"
3760
        echo "#!/bin/sh" >"${dir}/${PBI_UNINS_MIMESCRIPT}"
3761

    
3762

    
3763
  	cd "${PBI_CONFDIR}/${MOD_XDGMIME_DIR}"
3764
  	for i in `ls *.xml 2>/dev/null`
3765
  	do
3766
		_mFound=1
3767
		cp "${i}" "${dir}/PBI-${i}"
3768
		ifi="$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/PBI-${i}"
3769

    
3770
		# Check for a .directory file associated with this .desktop
3771
		ifp=""
3772
		iconfile="`basename -s .xml ${i}`"
3773
		if [ -e "${iconfile}.png" ] ; then
3774
			cp "${iconfile}.png" "${dir}/${iconfile}.png"
3775
			ifp="$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${iconfile}.png"
3776
			mi=`cat "$i" | grep '<mime-type' | cut -d '"' -f 2 | sed 's|/|-|g'`
3777
			echo "xdg-icon-resource install --novendor --context mimetypes ${ifp} --size 64 $mi" \
3778
				 >> "${dir}/${PBI_INS_MIMESCRIPT}"
3779
			echo "xdg-icon-resource uninstall --context mimetypes ${ifp} --size 64" \
3780
				 >> "${dir}/${PBI_UNINS_MIMESCRIPT}"
3781
		fi
3782

    
3783
		echo "xdg-mime install --novendor ${ifi}" \
3784
			 >> "${dir}/${PBI_INS_MIMESCRIPT}"
3785
		echo "xdg-mime uninstall ${ifi}" \
3786
			 >> "${dir}/${PBI_UNINS_MIMESCRIPT}"
3787
  	done
3788

    
3789
	chmod 755 "${dir}/${PBI_INS_MIMESCRIPT}"
3790
	chmod 755 "${dir}/${PBI_UNINS_MIMESCRIPT}"
3791

    
3792
	# No mime entries
3793
	if [ "$_mFound" = "0" ] ; then
3794
		rm "${dir}/${PBI_INS_MIMESCRIPT}"
3795
		rm "${dir}/${PBI_UNINS_MIMESCRIPT}"
3796
	fi
3797
}
3798

    
3799

    
3800
# Create the install script for the PBI
3801
mk_install_script() {
3802
	echo "Creating install script..."
3803
	if [ ! -d "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}" ] ; then mkdir -p "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}" ; fi
3804
	insc="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/.pbi-install.sh"
3805
	echo "#!/bin/sh" > "$insc"
3806
	echo "PBI_WRAPPERBIN=\"${PBI_FAKEBIN_DIR}\"" >> "$insc"
3807
	echo "PBI_PROGDIRPATH=\"${PBI_PROGDIRPATH}\"" >> "$insc"
3808
	echo "SYS_LOCALBASE=\"${SYS_LOCALBASE}\"" >> "$insc"
3809
	echo "cd \"\$PBI_PROGDIRPATH\"" >> "$insc"
3810

    
3811
	# Xorg Font setup
3812
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
3813
		echo 'if [ -d "${PBI_PROGDIRPATH}/etc" ] ; then' >> "$insc"
3814
		echo '	rm "${PBI_PROGDIRPATH}/etc/fonts" >/dev/null 2>/dev/null' >> "$insc"
3815
		echo '	ln -fs "${SYS_LOCALBASE}/etc/fonts" "${PBI_PROGDIRPATH}/etc/fonts"' >> "$insc"
3816
		echo 'fi' >> "$insc"
3817
		echo 'if [ -d "${PBI_PROGDIRPATH}/lib/X11" ] ; then' >> "$insc"
3818
		echo '	rm "${PBI_PROGDIRPATH}/lib/X11/fonts" >/dev/null 2>/dev/null' >> "$insc"
3819
		echo '	ln -fs "${SYS_LOCALBASE}/lib/X11/fonts" "${PBI_PROGDIRPATH}/lib/X11/fonts"' >> "$insc"
3820
		echo '	rm "${PBI_PROGDIRPATH}/lib/X11/icons" >/dev/null 2>/dev/null' >> "$insc"
3821
		echo '	ln -fs "${SYS_LOCALBASE}/lib/X11/icons" "${PBI_PROGDIRPATH}/lib/X11/icons"' >> "$insc"
3822
		echo '	rm "${PBI_PROGDIRPATH}/share/icons" >/dev/null 2>/dev/null' >> "$insc"
3823
		echo '	ln -fs "${SYS_LOCALBASE}/share/icons" "${PBI_PROGDIRPATH}/share/icons"' >> "$insc"
3824
		echo 'fi' >> "$insc"
3825
	fi
3826

    
3827
	# Add the binary wrapper sym-links
3828
        if [ -e "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" ] ; then
3829
		echo 'if [ `id -u` = "0" ] ; then ' >>${insc}
3830
		echo "	$PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" >>${insc}
3831
		echo "fi" >>${insc}
3832
	fi
3833

    
3834
	# Look for any XDG scripts
3835
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMIME_DIR}/${PBI_INS_MIMESCRIPT}" ] ; then
3836
		echo "$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${PBI_INS_MIMESCRIPT}" >>${insc}
3837
	fi
3838
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMENU_DIR}/${PBI_INS_MENUSCRIPT}" ] ; then
3839
		echo "$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/${PBI_INS_MENUSCRIPT}" >>${insc}
3840
	fi
3841

    
3842
	chmod 755 "${insc}"
3843
	
3844
}
3845

    
3846
# Create the deinstall script for the PBI
3847
mk_deinstall_script() {
3848
	echo "Creating deinstall script..."
3849
	uisc="${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/.pbi-uninstall.sh"
3850

    
3851
	echo "#!/bin/sh" > "$uisc"
3852
	echo "PBI_PROGDIRPATH=\"${PBI_PROGDIRPATH}\"" >> "$uisc"
3853
	echo "SYS_LOCALBASE=\"${SYS_LOCALBASE}\"" >> "$uisc"
3854

    
3855
	# Remove the binary wrapper sym-links
3856
        if [ -e "${PBI_STAGEDIR}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" ] ; then
3857
		echo 'if [ `id -u` = "0" ] ; then ' >>${uisc}
3858
		echo "	$PBI_PROGDIRPATH/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" >>${uisc}
3859
		echo "fi" >>${uisc}
3860
	fi
3861

    
3862
	# Look for any XDG scripts
3863
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMIME_DIR}/${PBI_UNINS_MIMESCRIPT}" ] ; then
3864
		echo "$PBI_PROGDIRPATH/${PBI_APPMIME_DIR}/${PBI_UNINS_MIMESCRIPT}" >>${uisc}
3865
	fi
3866
        if [ -e "${PBI_STAGEDIR}/${PBI_APPMENU_DIR}/${PBI_UNINS_MENUSCRIPT}" ] ; then
3867
		echo "$PBI_PROGDIRPATH/${PBI_APPMENU_DIR}/${PBI_UNINS_MENUSCRIPT}" >>${uisc}
3868
	fi
3869
	chmod 755 "${uisc}"
3870
}
3871

    
3872
# Create a dir for manipulating header info
3873
mk_header_dir() {
3874
	PBI_HEADERDIR="${PBI_PROGDIRPATH}/.headerdir"
3875
	if [ -e "${PBI_HEADERDIR}" ] ; then rm -rf "${PBI_HEADERDIR}" ; fi
3876
	mkdir -p ${PBI_HEADERDIR}
3877
}
3878

    
3879
# Remove the tmp header-dir
3880
rm_header_dir() {
3881
	PBI_HEADERDIR="${PBI_PROGDIRPATH}/.headerdir"
3882
	if [ -e "${PBI_HEADERDIR}" ] ; then rm -rf "${PBI_HEADERDIR}" ; fi
3883
}
3884

    
3885
# Create a dir for staging the final archive
3886
mk_stage_dir() {
3887
	local _excOpts=""
3888

    
3889
	PBI_STAGEDIR="${PBI_PROGDIRPATH}/.stagedir"
3890
	echo "Creating Stage Dir: ${PBI_STAGEDIR}"
3891
	if [ -e "${PBI_STAGEDIR}" ] ; then 
3892
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
3893
		chflags -R noschg ${PBI_STAGEDIR} 2>/dev/null
3894
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
3895
	fi
3896
	mkdir -p ${PBI_STAGEDIR}
3897

    
3898
	# Build module list of excludes
3899
	if [ -n "$PBI_EXCLUDELIST" ] ; then
3900
		for excl in $PBI_EXCLUDELIST
3901
		do
3902
			if [ -z "$_excOpts" ] ; then
3903
				_excOpts = "--exclude ${excl}"
3904
			else
3905
				_excOpts = "$_excOpts --exclude ${excl}"
3906
			fi
3907
		done
3908
	fi
3909

    
3910
	# Now copy the stagedir
3911
	tar cvf - ${_excOpts} --exclude .stagedir \
3912
		--exclude .pkgdb --exclude .ld-elf.hints --exclude make.conf \
3913
		--exclude make.conf.bak --exclude .keepports \
3914
		-C "${PBI_PROGDIRPATH}" . 2>/dev/null \
3915
		| tar xvpf - -C ${PBI_STAGEDIR} 2>/dev/null
3916

    
3917
}
3918

    
3919
# Remove the stagedir
3920
rm_stage_dir() {
3921
	cd /
3922
	PBI_STAGEDIR="${PBI_PROGDIRPATH}/.stagedir"
3923
	if [ -e "${PBI_STAGEDIR}" ] ; then 
3924
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
3925
		chflags -R noschg ${PBI_STAGEDIR} 2>/dev/null
3926
		rm -rf "${PBI_STAGEDIR}" 2>/dev/null
3927
	fi
3928
}
3929

    
3930
# See if we need to clean the stagedir
3931
clean_stage_dir() {
3932
	if [ "${PBI_USESYSGL}" != "NO" ] ; then
3933
		rm ${PBI_STAGEDIR}/lib/libGl.* >/dev/null 2>/dev/null
3934
		rm ${PBI_STAGEDIR}/lib/libGL.* >/dev/null 2>/dev/null
3935
		rm ${PBI_STAGEDIR}/lib/libGLU.* >/dev/null 2>/dev/null
3936
	fi
3937
	if [ "${PBI_USESYSFONTS}" != "NO" ] ; then
3938
		rm -rf ${PBI_STAGEDIR}/etc/fonts >/dev/null 2>/dev/null
3939
		rm -rf ${PBI_STAGEDIR}/lib/X11/fonts >/dev/null 2>/dev/null
3940
		rm -rf ${PBI_STAGEDIR}/lib/X11/icons >/dev/null 2>/dev/null
3941
		rm -rf ${PBI_STAGEDIR}/share/icons >/dev/null 2>/dev/null
3942
	fi
3943
}
3944

    
3945
# Copy over any resource files into the PBI dir
3946
copy_resource_dir() {
3947
	if [ -d "${PBI_CONFDIR}/${PBI_RESOURCE_DIR}" ] ; then
3948
		echo "Copying ${PBI_CONFDIR}/${PBI_RESOURCE_DIR} -> ${PBI_STAGEDIR}"
3949
		tar cvf - -C ${PBI_CONFDIR}/${PBI_RESOURCE_DIR} --exclude .svn . 2>/dev/null \
3950
		| tar xvpf - -C ${PBI_STAGEDIR} 2>/dev/null
3951
	fi
3952
}
3953

    
3954
# Check if tar supports lzma compression
3955
test_tar_lzma() {
3956
	touch /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
3957
	tar cvJf /tmp/.pbilzma.tar.$$ /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
3958
	_exitcode=$?
3959
	rm /tmp/.pbilzma.$$ >/dev/null 2>/dev/null
3960
	rm /tmp/.pbilzma.tar.$$ >/dev/null 2>/dev/null
3961
	return $_exitcode
3962
}
3963

    
3964
# Start creating the application archive 
3965
mk_archive_file() {
3966
	PBI_CREATE_ARCHIVE="${PBI_CREATE_OUTDIR}/.PBI.$$.tbz"
3967
	if test_tar_lzma ; then _tcmp="J" ; else _tcmp="j" ; fi
3968
	echo "Creating compressed archive..."
3969
	tar cv${_tcmp}f "${PBI_CREATE_ARCHIVE}" -C ${PBI_STAGEDIR} . 2>/dev/null 
3970
}
3971

    
3972
# Start creating the header archive
3973
mk_header_file() {
3974
	PBI_HEADER_ARCHIVE="${PBI_CREATE_OUTDIR}/.PBI-header.$$.tbz"
3975
	tar cvjf ${PBI_HEADER_ARCHIVE} -C ${PBI_HEADERDIR} . >/dev/null 2>/dev/null
3976
}
3977

    
3978
# Start copying pbi details into header file
3979
save_pbi_details_to_header() {
3980
	local _osArch="`uname -m`"
3981
	if [ -n "${PBI_OSARCH}" ] ; then
3982
		_osArch="${PBI_OSARCH}"
3983
	fi
3984

    
3985
	local _osRel="`uname -r`"
3986
	if [ -n "${PBI_OSREL}" ] ; then
3987
		_osRel="${PBI_OSREL}"
3988
	fi
3989

    
3990
	if [ "${PBI_CREATEONLY}" = "YES" ] ; then
3991
		_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
3992
		echo "${PBI_APPDIR}/${_pbilow}-${_osArch}" > "${PBI_HEADERDIR}/pbi_defaultpath"
3993
	else	
3994
		echo "${PBI_PROGDIRPATH}" > "${PBI_HEADERDIR}/pbi_defaultpath"
3995
	fi
3996
	echo "${PBI_PROGNAME}" > "${PBI_HEADERDIR}/pbi_name"
3997
	echo "${PBI_PROGVERSION}" > "${PBI_HEADERDIR}/pbi_version"
3998
	echo "${PBI_PROGAUTHOR}" > "${PBI_HEADERDIR}/pbi_author"
3999
	echo "${PBI_PROGWEB}" > "${PBI_HEADERDIR}/pbi_web"
4000
	date "+%Y%m%d %H%M%S" > "${PBI_HEADERDIR}/pbi_mdate"
4001

    
4002
	if [ "${PBI_REQUIRESROOT}" = "YES" ] ; then
4003
		touch ${PBI_HEADERDIR}/pbi_requiresroot
4004
	fi
4005

    
4006
	# Do we have a license to accept?
4007
	if [ -e "${PBI_CONFDIR}/${PBI_LICENSEFILE}" ] ; then
4008
		cp "${PBI_CONFDIR}/${PBI_LICENSEFILE}" "${PBI_HEADERDIR}/${PBI_LICENSEFILE}"
4009
	fi
4010

    
4011
	# Custom install / remove scripts
4012
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREINS}" ] ; then
4013
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREINS}" \
4014
			"${PBI_HEADERDIR}/${MOD_PREINS}"
4015
	else
4016
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_PREINS}
4017
	fi
4018
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_POSTINS}" ] ; then
4019
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_POSTINS}" \
4020
			"${PBI_HEADERDIR}/${MOD_POSTINS}"
4021
	else
4022
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_POSTINS}
4023
	fi
4024
	if [ -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREREM}" ] ; then
4025
		cp "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/${MOD_PREREM}" \
4026
			"${PBI_HEADERDIR}/${MOD_PREREM}"
4027
	else
4028
		echo "#!/bin/sh" > ${PBI_HEADERDIR}/${MOD_PREREM}
4029
	fi
4030

    
4031
	# Copy over our icon
4032
	if [ -n "${PBI_PROGICON}" -a -e "${PBI_STAGEDIR}/${PBI_PROGICON}" ] ; then
4033
		# Get the file extension
4034
		_iconExt=`echo "$PBI_PROGICON" | awk -F . '{print $NF}'`
4035
		cp "${PBI_STAGEDIR}/${PBI_PROGICON}" "${PBI_HEADERDIR}/pbi_icon.${_iconExt}" >/dev/null 2>/dev/null
4036
	else
4037
		_iconExt=`echo "$PBI_DEFAULT_ICON_CHROOT" | awk -F . '{print $NF}'`
4038
		cp "${PBI_DEFAULT_ICON_CHROOT}" "${PBI_HEADERDIR}/pbi_icon.${_iconExt}" >/dev/null 2>/dev/null
4039
	fi
4040

    
4041
	# Check for any gui images
4042
	if [ -e "${PBI_STAGEDIR}/${PBI_GUITOPBANNER}" ] ; then
4043
		cp "${PBI_STAGEDIR}/${PBI_GUITOPBANNER}" "${PBI_HEADERDIR}/top-banner.png"
4044
	fi
4045
	if [ -e "${PBI_STAGEDIR}/${PBI_GUISIDEBANNER}" ] ; then
4046
		cp "${PBI_STAGEDIR}/${PBI_GUISIDEBANNER}" "${PBI_HEADERDIR}/side-banner.png"
4047
	fi
4048

    
4049
	# Save the uname details
4050
	echo "${_osArch}" > "${PBI_HEADERDIR}/pbi_arch"
4051
	echo "${_osRel}" > "${PBI_HEADERDIR}/pbi_fbsdver"
4052
	echo "${PROGVERSION}" > "${PBI_HEADERDIR}/pbi_createver"
4053

    
4054
	# Get the total number of files in the STAGEDIR
4055
	get_filetotal_dir "${PBI_STAGEDIR}"
4056
	echo "${FILETOTAL}" > "${PBI_HEADERDIR}/pbi_archivecount"
4057

    
4058
	# Save a checksum of archive file
4059
	sha256 -q "${PBI_CREATE_ARCHIVE}" > "${PBI_HEADERDIR}/pbi_archivesum"
4060

    
4061
	sign_pbi_files "$PBI_HEADERDIR"
4062
}
4063

    
4064
# Use openssl to sign parts of the pbi header structure and archive 
4065
sign_pbi_files() {
4066
	if [ -z "${PBI_SSLPRIVKEY}" ] ; then return 0 ; fi
4067
	_sf="${1}/pbi_archivesum ${1}/${MOD_PREINS} ${1}/${MOD_POSTINS} ${1}/${MOD_PREREM}"
4068
	for i in $_sf
4069
	do
4070
		openssl dgst -sha1 \
4071
  			-sign ${PBI_SSLPRIVKEY} \
4072
  			-out ${i}.sha1 \
4073
  			${i} >/dev/null 2>/dev/null
4074
	done
4075
}
4076

    
4077

    
4078
# All the pieces are ready, spit out the final PBI file
4079
mk_output_pbi() {
4080
	if [ -z "${PBI_OSARCH}" ] ; then
4081
		PBI_OSARCH="`uname -m`"
4082
	fi
4083

    
4084
        if [ -n "${PBI_PROGICON}" -a -e "${PBI_STAGEDIR}/${PBI_PROGICON}" ] ; then
4085
                icon="${PBI_STAGEDIR}/${PBI_PROGICON}"
4086
        else
4087
                icon="${PBI_DEFAULT_ICON_CHROOT}"
4088
        fi
4089
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
4090

    
4091
	outfile="${PBI_CREATE_OUTDIR}/${_pbilow}-${PBI_PROGVERSION}-${PBI_OSARCH}.pbi"
4092
	mark1="${PBI_CREATE_OUTDIR}/.pbimark1.$$"
4093
	mark2="${PBI_CREATE_OUTDIR}/.pbimark2.$$"
4094

    
4095
	echo "
4096
${PBI_SS_ICON}" >$mark1
4097
	echo "
4098
${PBI_SS_ARCHIVE}" >$mark2
4099

    
4100
	# DO IT, DO IT NOW!!!
4101
	cat ${PBI_HEADER_ARCHIVE} $mark1 ${icon} $mark2 ${PBI_CREATE_ARCHIVE} > ${outfile}	
4102
	sha256 -q ${outfile} > ${outfile}.sha256
4103

    
4104
	echo "Created PBI: ${outfile}"
4105

    
4106
	rm $mark1
4107
	rm $mark2
4108
	rm ${PBI_HEADER_ARCHIVE}
4109
	rm ${PBI_CREATE_ARCHIVE}
4110
}
4111

    
4112
get_filetotal_dir() {
4113
	FILETOTAL="`find ${1} | wc -l | tr -d ' '`"
4114
}
4115

    
4116
pbi_delete_init() {
4117
  	require_root_or_group
4118
	init_tmpdir
4119
	parse_delete_pbi_cmdline "$@"
4120
	do_pbi_delete
4121
}
4122

    
4123
# Delete this PBI
4124
do_pbi_delete() {
4125
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4126
	PBI_PROGDIRPATH="${PBI_ORIGPROGDIRPATH}"
4127

    
4128
	get_username_from_file "${PBI_DBAPPDIR}/${PBI_DELETENAME}/pbi_name"
4129
	if [ "$FILEUSER" != `whoami` -a `id -u` != "0" ] ; then
4130
		exit_err "Permission denied to modify PBI installed by: $FILEUSER"
4131
	fi
4132

    
4133
	# Set the dirty flag that we are removing this PBI
4134
	touch ${PBI_DBAPPDIR}/${PBI_DELETENAME}/.pbiDeleted
4135

    
4136
	check_preremove_script
4137
	run_remove_script
4138
 	remove_pbidir
4139
	unregister_pbi
4140
	
4141
	# Mark the hashdir as dirty
4142
	make_hashdir_dirty
4143
}
4144

    
4145
# Save the hash-list to run a cleanup afterwards
4146
pbirm_save_hashlist() {
4147
	if [ "${PBI_DISABLEHASHDIR}" = "YES" ] ; then return 0 ; fi
4148
	if [ -e "${PBI_PROGDIRPATH}/${PBI_HASHLIST}" ] ; then
4149
		PBI_TMPHASHLIST="${PBI_TMPDIR}/.pbi-hash.$$"
4150
		cp ${PBI_PROGDIRPATH}/${PBI_HASHLIST} ${PBI_TMPHASHLIST}
4151
	fi
4152
}
4153

    
4154
# Function which removes all empty dirs from the hash-dir
4155
pbi_clean_emptyhdirs() {
4156
        if [ ! -d "${PBI_HASHDIR}" ] ; then return 0 ; fi
4157
	cd ${PBI_HASHDIR}
4158
	found="0"
4159
	for i in `find . -empty -type d 2>/dev/null`
4160
	do
4161
		if [ "${i}" = "." ] ; then continue ; fi
4162
		if [ -d "${PBI_HASHDIR}/${i}" ] ; then
4163
			rmdir "${PBI_HASHDIR}/${i}"
4164
			found="1"
4165
		fi	
4166
	done
4167

    
4168
	# Run recursively
4169
	if [ "$found" = "1" ];then pbi_clean_emptyhdirs ; fi
4170
}
4171

    
4172
# Read through and clean the given hash-list
4173
pbi_clean_hashlist() {
4174
	if [ -z "${PBI_TMPHASHLIST}" ] ; then return 0 ; fi
4175
	while read hl
4176
	do
4177
		file="`echo $hl | sed 's/:::.*$//g'`"
4178
		hash="`echo $hl | sed 's/^.*::://g'`"
4179
		tfile="${file}:::${hash}"
4180
		if [ -f "${PBI_HASHDIR}/${tfile}" ] ; then
4181
			check_remove_hashfile "${tfile}"
4182
		fi
4183

    
4184
	done < ${PBI_TMPHASHLIST}
4185
	rm ${PBI_TMPHASHLIST}
4186
}
4187

    
4188
# Read through and clean the entire hashdir
4189
pbi_clean_hashdir() {
4190
        if [ ! -d "${PBI_HASHDIR}" ] ; then return 0 ; fi
4191
	echo "Cleaning shared-hash dir..."
4192
	cd ${PBI_HASHDIR}
4193
	tmphashlist="${PBI_TMPDIR}/.pbi-hashdir.$$"
4194
	find * -type f -links 1 > "${tmphashlist}" 2>/dev/null
4195
        while read hl
4196
        do
4197
		if [ ! -f "$hl" -o -h "$hl" ] ; then continue ; fi
4198
                if [ -f "${PBI_HASHDIR}/${hl}" ] ; then
4199
                        check_remove_hashfile "${hl}"
4200
                fi
4201

    
4202
        done < $tmphashlist
4203
        rm "$tmphashlist"
4204
	pbi_clean_emptyhdirs
4205
}
4206

    
4207
# Check if this hash-file is ready to be removed from the hash-dir
4208
check_remove_hashfile() {
4209
	tfile="${PBI_HASHDIR}/${1}"
4210
	get_hard_link_count "${tfile}"
4211
	if [ "$HLINKS" = "1" ] ; then
4212
		if [ "${PBI_VERBOSE}" = "YES" ] ; then 
4213
			echo "Removing unused hashfile: $tfile"
4214
		fi
4215
		rm -f "${tfile}"
4216
	fi
4217
}
4218

    
4219
# Run the removal script for this PBI
4220
run_remove_script() {
4221
	uisc="${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/.pbi-uninstall.sh"
4222
	if [ ! -e "$uisc" ] ; then return 0 ; fi
4223

    
4224
	# If not running as root, be sure to cleanup path links
4225
	if [ "`id -u`" != "0" ]; then
4226
	 	cat ${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT} | grep 'rm "$SYS_LOCALBASE/bin' | sed 's|$SYS_LOCALBASE|${HOME}|g' >${PBI_TMPDIR}/.binlnks
4227
         	while read lnk
4228
          	do
4229
               	 	/bin/sh -c "${lnk}"
4230
          	done <${PBI_TMPDIR}/.binlnks
4231
          	rm ${PBI_TMPDIR}/.binlnks
4232
        fi
4233
        export_script_vars
4234
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4235
       		sh "${uisc}"
4236
	else
4237
       		sh "${uisc}" >/dev/null 2>/dev/null
4238
	fi
4239
}
4240

    
4241
# Function to check the supplied $1 dir for any mounts before we
4242
# do a rm -rf
4243
umount_before_rm()
4244
{
4245
   	if [ -z "${1}" ] ; then return 0 ; fi
4246

    
4247
        local _ddir="$1"
4248
        echo "$_ddir" | rev | grep -q '^/'	
4249
	if [ $? -ne 0 ] ; then
4250
	   _ddir="${_ddir}/"
4251
	fi
4252
	
4253
	mount | grep -q "on ${_ddir}"
4254
	if [ $? -ne 0 ] ; then return 0; fi
4255

    
4256
        for i in `mount | grep "on ${_ddir}" | awk '{print $3}'`
4257
	do
4258
	   umount -f ${i} >/dev/null 2>/dev/null
4259
	   if [ $? -ne 0 ] ; then 
4260
		exit_err "Could not umount ${i} before rm -rf, bailing!"
4261
	   fi
4262
	done
4263
	return 0
4264
}
4265

    
4266
# Remove the pbi directory
4267
remove_pbidir() {
4268
	if [ -z "${PBI_PROGDIRPATH}" ] ; then return 0 ; fi
4269
	if [ ! -d "${PBI_PROGDIRPATH}" ] ; then return 0 ; fi
4270
	if [ "${PBI_PROGDIRPATH}" = "/" ] ; then return 0 ; fi
4271
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4272
		echo "Removing: ${PBI_PROGDIRPATH}"
4273
	fi
4274

    
4275
        # Make sure we are unmounted
4276
        umount_before_rm "${PBI_PROGDIRPATH}"
4277
	
4278
	rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4279

    
4280
	# Do we have leftovers?
4281
	if [ -d "${PBI_PROGDIRPATH}" ] ; then
4282
		chflags -R noschg "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4283
		chmod -R 777 "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4284
		rm -rf "${PBI_PROGDIRPATH}" >/dev/null 2>/dev/null
4285
	fi
4286
}
4287

    
4288
# Remove this PBI registration
4289
unregister_pbi() {
4290
	if [ -z "${PBI_DBAPPDIR}" ] ; then return 0 ; fi
4291
	if [ -z "${PBI_DELETENAME}" ] ; then return 0 ; fi
4292
	if [ ! -d "${PBI_DBAPPDIR}/${PBI_DELETENAME}" ] ; then return 0 ; fi
4293
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4294
		echo "Removing: ${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4295
	fi
4296
	rm -rf "${PBI_DBAPPDIR}/${PBI_DELETENAME}"
4297

    
4298
}
4299

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

    
4304
	if [ "$PBI_VERBOSE" = "YES" ] ; then
4305
		echo "Running pre-removal script: ${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}"
4306
	fi
4307
        export_script_vars
4308
       	sh "${PBI_DBAPPDIR}/${PBI_DELETENAME}/${MOD_PREREM}"
4309
}
4310

    
4311
add_app_path_links()
4312
{
4313
	# If root, run the regular path script
4314
	if [ `id -u` = "0" ] ; then
4315
		sh "${1}/${PBI_FAKEBIN_DIR}/${PBI_INS_PATHSCRIPT}" >/dev/null 2>/dev/null
4316
		return
4317
	fi
4318

    
4319
	# Running as user add to ~/bin
4320
	init_tmpdir
4321
	if [ ! -d "${HOME}/bin" ] ; then mkdir -p "${HOME}/bin"; fi
4322
	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
4323
	while read lnk
4324
	do
4325
		/bin/sh -c "${lnk}"
4326
		
4327
	done <${PBI_TMPDIR}/.binlnks
4328
	rm ${PBI_TMPDIR}/.binlnks
4329
	
4330
}
4331

    
4332
del_app_path_links()
4333
{
4334
	# If root, run the regular path script
4335
	if [ `id -u` = "0" ] ; then
4336
		sh "${1}/${PBI_FAKEBIN_DIR}/${PBI_UNINS_PATHSCRIPT}" >/dev/null 2>/dev/null
4337
		return
4338
	fi
4339

    
4340
	# Running as user remove from ~/bin
4341
	if [ ! -d "${HOME}/bin" ] ; then mkdir -p "${HOME}/bin"; fi
4342
	for lnk in `ls ${1}/${PBI_FAKEBIN_DIR}`
4343
	do
4344
		if [ "$lnk" = "$PBI_INS_PATHSCRIPT" -o "$lnk" = "$PBI_UNINS_PATHSCRIPT" ]
4345
		then
4346
			continue
4347
		fi
4348

    
4349
		if [ ! -e "${HOME}/bin/$lnk" ] ; then continue ; fi
4350
		if [ ! -h "${HOME}/bin/$lnk" ] ; then continue ; fi
4351
			
4352
		ls -al "${HOME}/bin/$lnk" | awk '{print $11}' | grep $1 >/dev/null 2>/dev/null
4353
		if [ "$?" = "0" ] ; then
4354
			rm ${HOME}/bin/$lnk
4355
		fi
4356
	done
4357
	
4358
}
4359

    
4360
pbi_icon_init() {
4361
	parse_icon_pbi_cmdline "$@"
4362
	
4363
	do_pbi_icon
4364
}
4365

    
4366
# Start the PBI icon process
4367
do_pbi_icon() {
4368
	# Get the dir for this PBI
4369
	_appDir=`cat ${PBI_DBAPPDIR}/${PBI_ICONTARGETAPP}/pbi_installedpath`
4370

    
4371
	if [ "${PBI_PATHADD}" = "YES" ] ; then
4372
		add_app_path_links "$_appDir"
4373
	fi
4374
	if [ "${PBI_PATHDEL}" = "YES" ] ; then
4375
		del_app_path_links "$_appDir"
4376
	fi
4377

    
4378
	if [ "${PBI_DESKADD}" = "YES" ] ; then
4379
		if [ ! -e "${_appDir}/.xdg-desktop/${PBI_INS_DESKSCRIPT}" ] ; then 
4380
			exit_err "No desktop icons for this PBI"
4381
		fi
4382
		sh "${_appDir}/.xdg-desktop/${PBI_INS_DESKSCRIPT}"
4383
	fi
4384
	if [ "${PBI_DESKDEL}" = "YES" ] ; then
4385
		if [ ! -e "${_appDir}/.xdg-desktop/${PBI_UNINS_DESKSCRIPT}" ] ; then 
4386
			exit_err "No desktop icons for this PBI"
4387
		fi
4388
		sh "${_appDir}/.xdg-desktop/${PBI_UNINS_DESKSCRIPT}"
4389
	fi
4390
	if [ "${PBI_MENUADD}" = "YES" ] ; then
4391
		require_root_or_group
4392
		if [ ! -e "${_appDir}/.xdg-menu/${PBI_INS_MENUSCRIPT}" ] ; then 
4393
			exit_err "No menu icons for this PBI"
4394
		fi
4395
		sh "${_appDir}/.xdg-menu/${PBI_INS_MENUSCRIPT}"
4396
	fi
4397
	if [ "${PBI_MENUDEL}" = "YES" ] ; then
4398
		require_root_or_group
4399
		if [ ! -e "${_appDir}/.xdg-menu/${PBI_UNINS_MENUSCRIPT}" ] ; then 
4400
			exit_err "No menu icons for this PBI"
4401
		fi
4402
		sh "${_appDir}/.xdg-menu/${PBI_UNINS_MENUSCRIPT}"
4403
	fi
4404
	if [ "${PBI_MIMEADD}" = "YES" ] ; then
4405
		require_root_or_group
4406
		if [ ! -e "${_appDir}/.xdg-mime/${PBI_INS_MIMESCRIPT}" ] ; then 
4407
			exit_err "No mime registration for this PBI"
4408
		fi
4409
		sh "${_appDir}/.xdg-mime/${PBI_INS_MIMESCRIPT}"
4410
	fi
4411
	if [ "${PBI_MIMEDEL}" = "YES" ] ; then
4412
		require_root_or_group
4413
		if [ ! -e "${_appDir}/.xdg-mime/${PBI_UNINS_MIMESCRIPT}" ] ; then 
4414
			exit_err "No mime registration for this PBI"
4415
		fi
4416
		sh "${_appDir}/.xdg-mime/${PBI_UNINS_MIMESCRIPT}"
4417
	fi
4418
}
4419

    
4420
pbid_init() {
4421
	require_root
4422

    
4423
	parse_pbid_cmdline "$@"
4424

    
4425
	do_pbid
4426
}
4427

    
4428
# Start the PBID daemon
4429
do_pbid() {
4430

    
4431
	# Allow user supplied logfile
4432
        if [ -z "${PBID_LOGFILE}" ] ; then
4433
	  _pbid_log="/var/log/pbid.log"
4434
	else
4435
          _pbid_log="${PBID_LOGFILE}"
4436
        fi
4437

    
4438
	# Set verbosity 
4439
	_redir="&1"
4440
	if [ "${PBI_VERBOSE}" != "YES" ] ; then _redir="/dev/null" ; fi
4441
	echo "Started pbid: `date`" > ${_pbid_log}
4442

    
4443
	while
4444
	i=1
4445
	do
4446
		# Do regular sleeps
4447
		qslp=0
4448

    
4449
		# Check if we have any out of date index files to update
4450
		for _dbIndex in `ls ${PBI_DBREPODIR}`
4451
		do
4452
			_iMd5=`echo ${_dbIndex} | cut -d '.' -f 2`
4453
			check_update_index "${_iMd5}"
4454

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

    
4462
		# Check if we have a dirty hash-dir to cleanup
4463
		check_clean_hashdir "$_pbid_log" "$_redir"
4464

    
4465
		# Check if we have any PBIs to auto-update
4466
		check_autoupdate_pbis "$_pbid_log" "$_redir"
4467

    
4468
		# Check if we need to merge files into the hashdir
4469
		if [ -n "`ls ${PBI_DBHASHQUEUEDIR}`" ] ; then
4470
			init_tmpdir
4471
			for _hpbi in `ls ${PBI_DBHASHQUEUEDIR}`
4472
			do
4473
				if [ ! -e "${PBI_DBAPPDIR}/${_hpbi}/pbi_installedpath" ] ; then
4474
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4475
					continue
4476
				fi
4477

    
4478
				_hpbipath=""
4479
				_hpbipath=`cat ${PBI_DBAPPDIR}/${_hpbi}/pbi_installedpath`
4480
				if [ ! -e "${_hpbipath}/${PBI_HASHLIST}" ] ; then
4481
					rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4482
					continue
4483
				fi
4484

    
4485
				# Get the username this PBI was installed as
4486
				get_username_from_file "${_hpbipath}"
4487

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

    
4491
				if [ "$FILEUSER" = "root" ];then
4492
					pbi_add_update_hashdir "${_hpbipath}" "${PBI_DBAPPDIR}/${_hpbi}/.pbiDeleted" >${_redir} 2>${_redir}
4493
				else
4494
					# Run hashdir command as a user
4495
					su $FILEUSER -c "pbi_update_hashdir \"${_hpbipath}\" \"${PBI_DBAPPDIR}/${_hpbi}/.pbiDeleted\"" >${_redir} 2>${_redir}
4496
				fi
4497
				echo "Finished adding ${_hpbipath} to hash-dir: `date`" >> ${_pbid_log}
4498
				
4499
				# Now remove the trigger file
4500
				rm ${PBI_DBHASHQUEUEDIR}/${_hpbi}
4501

    
4502
			done
4503
			rm_tmpdir
4504

    
4505
		fi
4506
		
4507
		# Check if we should rotate the logfile
4508
		_pbidLines=`wc -l ${_pbid_log} | awk '{ print $1 }'`
4509
		if [ $(is_num "$_pbidLines") ] ; then
4510
			if [ $_pbidLines -gt $PBI_LOG_LINES ] ; then
4511
				echo "Logfile turnover: `date`" >${_pbid_log}
4512
			fi
4513
		fi
4514
		
4515

    
4516
		# Done with our check, lets go back to sleep now
4517
		if [ $qslp -eq 1 ] ; then
4518
			sleep 60
4519
		else
4520
			sleep ${PBIDSLEEP}
4521
		fi
4522
	done
4523

    
4524
}
4525

    
4526
# Check if there are any PBIs which are flagged for auto-updates
4527
check_autoupdate_pbis() {
4528

    
4529
	for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
4530
	do
4531
		if [ ! -e "${PBI_DBAPPDIR}/${i}/autoupdate-enable" ] ; then
4532
			continue 
4533
		fi
4534

    
4535
		# Check if this app is already updating
4536
		if [ -e "${PBI_DBAPPDIR}/${i}/.updating" ] ; then
4537
			ps -p `cat ${PBI_DBAPPDIR}/${i}/.updating` >/dev/null 2>/dev/null
4538
			if [ "$?" != "0" ] ; then
4539
				rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
4540
			else
4541
				continue 
4542
			fi
4543
		fi
4544

    
4545
		# Found an auto-update enabled APP, see if it needs upping
4546
		PBI_UPDATEAPP="$i"
4547

    
4548
		# Load the details about this app
4549
		load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4550
		if [ -z "${PBI_REPO}" ]; then
4551
			pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4552
		fi
4553
		if [ -z "${PBI_REPO}" ]; then continue ; fi
4554
		local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
4555

    
4556
		# Does this need an update?
4557
		check_pbi_update "$PBI_UPDATEAPP" "nodisplay" \
4558
			"$PBI_PROGNAME" "current" \
4559
			"$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
4560
		if [ "$?" != "0" ] ; then
4561
			continue
4562
		fi
4563
		
4564
		# Get the username this PBI was installed as
4565
		get_username_from_file "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4566

    
4567
		# Its Update Time!
4568
		echo "Starting Auto-Update of ${PBI_UPDATEAPP} ($FILEUSER): `date`" >>${_pbid_log}
4569

    
4570
		su ${FILEUSER} -c "pbi_update ${PBI_UPDATEAPP}" >>${_pbid_log} 2>>${_pbid_log}
4571
		if [ "$?" = "0" ] ; then
4572
			echo "Success! Update of ${PBI_UPDATEAPP}: `date`" >>${_pbid_log}
4573
		else
4574
			echo "Failed! Update of ${PBI_UPDATEAPP}: `date`" >>${_pbid_log}
4575
		fi
4576

    
4577
		rm "${PBI_DBAPPDIR}/${i}/.updating" >/dev/null 2>/dev/null
4578
	done
4579
}
4580

    
4581
check_clean_hashdir() {
4582
	if [ ! -e "${PBI_DBDIRTYFILE}" ] ; then return ; fi
4583

    
4584
	# Get the date of the last hash-cleaning done
4585
	local _curDate="`cat ${PBI_DBDIRTYFILE}`"
4586
	if [ -e "${PBI_DBDIRTYFILE}.last" ] ; then
4587
		local _lastDate="`cat ${PBI_DBDIRTYFILE}.last`"
4588
	else
4589
		local _lastDate="0"
4590
	fi
4591

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

    
4595
	# Loop through and clean any hash-dirs as the appropriate user
4596
	for cHdir in `ls -d ${PBI_HASHDIR}*`
4597
	do
4598
		get_username_from_file "${cHdir}"
4599
		echo "Cleaning hash-dir ($FILEUSER): `date`" >> ${1}
4600
		su ${FILEUSER} -c "pbi_delete --clean-hdir" >>${2} 2>>${2}
4601
		echo "Finished cleaning hash-dir ($FILEUSER): `date`" >> ${1}
4602
		echo "$_curDate" > ${PBI_DBDIRTYFILE}.last 2>/dev/null
4603
	done
4604
}
4605

    
4606
pbi_info_init() {
4607
	parse_info_pbi_cmdline "$@"
4608
	
4609
	do_pbi_info
4610
}
4611

    
4612
# Display information on the PBI / PBIs
4613
do_pbi_info() {
4614

    
4615
	# If we are listing available PBIs via the index file
4616
	if [ "$PBI_INFOINDEX" = "YES" ] ; then
4617
		
4618
		# List the available PBIs from the index
4619
		do_index_listing
4620
		
4621
		exit_trap
4622
	fi
4623

    
4624
	if [ "$PBI_INFONAME" = "--ALL--" ] ; then
4625
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
4626
		do
4627
			if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
4628
				if [ "$PBI_VERBOSE" = "YES" ] ; then
4629
        				load_info_from_dir "${PBI_DBAPPDIR}/${i}"
4630
					get_username_from_file "${PBI_DBAPPDIR}/${i}"
4631
					PBI_INSTALLED_BY=$FILEUSER
4632
					pbi_display_info
4633
					pbi_display_gui "${PBI_DBAPPDIR}/${i}" ""
4634
					echo " "
4635
				else
4636
					echo "${i}"
4637
				fi
4638
			fi
4639
		done
4640
	else
4641
		# Start loading our variables
4642
        	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_INFONAME}"
4643
		get_username_from_file "${PBI_DBAPPDIR}/${PBI_INFONAME}"
4644
		PBI_INSTALLED_BY=$FILEUSER
4645
		pbi_display_info
4646
	fi
4647
}
4648

    
4649
# Read through the master index file and provide listing of available PBIs for installation
4650
do_index_listing()
4651
{
4652
	# Make sure we have a master index
4653
	ls ${PBI_DBINDEXDIR}/* >/dev/null 2>/dev/null
4654
	if [ "$?" != "0" ] ; then return ; fi
4655

    
4656
	for _rIndex in `ls ${PBI_DBINDEXDIR}/*index* | grep -v '.time'`
4657
	do
4658
		_rMd5=`basename ${_rIndex} | sed 's|-index||g'`
4659
		_rDesc=`cat ${PBI_DBREPODIR}/*.${_rMd5} | grep 'Desc: ' | sed 's|Desc: ||g'`
4660
		echo "Current and available PBIs. * = current"
4661
		echo "Repository: $_rDesc"
4662
		echo "----------------------------------------------------------------"
4663

    
4664
		sort "${_rIndex}" | while read _iLine
4665
		do
4666
			PBI_UPNAME="`echo $_iLine | cut -d ':' -f 1`"
4667
			PBI_UPARCH="`echo $_iLine | cut -d ':' -f 2`"
4668
	        	PBI_UPNVER="`echo $_iLine | cut -d ':' -f 3`"
4669
        		PBI_UPSTATUS="`echo $_iLine | cut -d ':' -f 9`"
4670
			pad_var "${PBI_UPNAME}" "30"
4671
			PBI_UPNAME="${PAD_VAR}"
4672
			pad_var "${PBI_UPNVER}" "15"
4673
			PBI_UPNVER="${PAD_VAR}"
4674
			pad_var "${PBI_UPARCH}" "6"
4675
			PBI_UPARCH="${PAD_VAR}"
4676
	
4677
			if [ "$PBI_UPSTATUS" = "current" ] ; then
4678
				echo "$PBI_UPNAME   $PBI_UPNVER	$PBI_UPARCH *"
4679
			fi
4680
			if [ "$PBI_UPSTATUS" = "active" ] ; then
4681
				echo "$PBI_UPNAME   $PBI_UPNVER	$PBI_UPARCH"
4682
			fi
4683
		done
4684
	done
4685

    
4686
}
4687

    
4688
# Function to pad a variable to X spaces
4689
pad_var() {
4690
	local _pVar="$1"
4691
	local _pNum="$2"
4692
	PAD_VAR="`echo \"$_pVar                                                                                    x\" | cut -c 1-$_pNum`"
4693
}
4694

    
4695
# Checks if we have a custom script to run prior to port make
4696
run_pbi_preportmake()
4697
{
4698
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
4699
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
4700
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-portmake.sh" ] ; then return 0 ; fi
4701

    
4702
	export_script_vars
4703

    
4704
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/pre-portmake.sh"
4705
	if [ "$?" != "0" ] ; then
4706
		exit_err "pre-portmake.sh failed!"
4707
	fi
4708
}
4709

    
4710
# Checks if we have a custom script to run prior to port make
4711
run_pbi_postportmake()
4712
{
4713
  	if [ ! -d "${PBI_CONFDIR}" ] ; then return 0 ; fi
4714
  	if [ ! -d "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}" ] ; then return 0 ; fi
4715
  	if [ ! -e "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/post-portmake.sh" ] ; then return 0 ; fi
4716

    
4717
	export_script_vars
4718

    
4719
	sh "${PBI_CONFDIR}/${PBI_CONF_SCRIPTSDIR}/post-portmake.sh"
4720
	if [ "$?" != "0" ] ; then
4721
		echo "Warning: post-portmake.sh returned non-0 status!"
4722
	fi
4723
}
4724

    
4725
# Begins the port make
4726
start_pbi_makeport()
4727
{
4728
	do_port_build "/usr/ports/${PBI_MAKEPORT}"
4729
}
4730

    
4731
# Prune any ports which aren't required for runtime
4732
start_pbi_prune_ports()
4733
{
4734
	if [ "${PBI_PRUNEBUILDPORTS}" = "NO" ] ; then return ; fi
4735

    
4736
	get_pkgname "${PORTSDIR}/${PBI_MAKEPORT}"
4737
	echo "${PKGNAME}" >/.keepports
4738

    
4739
	# Do the same for any OTHERPORTS
4740
	for port in ${PBI_MKPORTBEFORE}
4741
	do
4742
                if [ ! -d "${PORTSDIR}/${port}" ] ; then continue ; fi
4743
		get_pkgname "${PORTSDIR}/${port}"
4744
		echo "${PKGNAME}" >>/.keepports
4745
        done
4746

    
4747
	for port in ${PBI_MKPORTAFTER}
4748
	do
4749
                if [ ! -d "${PORTSDIR}/${port}" ] ; then continue ; fi
4750
		get_pkgname "${PORTSDIR}/${port}"
4751
		echo "${PKGNAME}" >>/.keepports
4752
        done
4753

    
4754
	# Now check what packages we have and prune those whom aren't needed
4755
	while
4756
	z="1"
4757
	do
4758
		FOUND=""
4759
		for j in `pkg_info -I -a | cut -d " " -f 1`
4760
		do
4761
			grep "${j}" "/.keepports" >/dev/null 2>/dev/null
4762
			if [ "$?" != "0" ] ; then 
4763
				pkg_info -R "${j}" | grep "Required" >/dev/null 2>/dev/null
4764
				if [ "$?" != "0" ] ; then 
4765
					echo "Removing non-required port: ${j}"
4766
					pkg_delete ${j} 
4767
					FOUND="1"
4768
					break 
4769
				fi
4770
			fi
4771
		done
4772

    
4773
		# All done pruning ports
4774
		if [ -z "$FOUND" ] ; then break ; fi
4775
	done
4776
}
4777

    
4778
# Get the full package-name for a target port
4779
get_pkgname() {
4780
        name="`make -C ${1} -V PKGNAME`"
4781
	PKGNAME="${name}"
4782
}
4783

    
4784
# Make any additional required ports 
4785
start_pbi_mkportbefore()
4786
{
4787
	if [ -z "${PBI_MKPORTBEFORE}" ] ; then return ; fi
4788
	
4789
	for port in ${PBI_MKPORTBEFORE}
4790
	do
4791
		if [ ! -d "/usr/ports/${port}" ] ; then
4792
			exit_err "/usr/ports/${port} does not exist!"
4793
		fi
4794
		do_port_build "/usr/ports/${port}"
4795
	done
4796

    
4797
}
4798

    
4799
# Make any additional required ports 
4800
start_pbi_mkportafter()
4801
{
4802
	if [ -z "${PBI_MKPORTAFTER}" ] ; then return ; fi
4803
	
4804
	for port in ${PBI_MKPORTAFTER}
4805
	do
4806
		if [ ! -d "/usr/ports/${port}" ] ; then
4807
			exit_err "/usr/ports/${port} does not exist!"
4808
		fi
4809
		do_port_build "/usr/ports/${port}"
4810
	done
4811

    
4812
}
4813

    
4814
# Start pbi_update_hashdir
4815
pbi_update_hashdir_init() {
4816
	pbi_add_update_hashdir "$1" "$2"
4817
}
4818

    
4819
# Start pbi_update processing
4820
pbi_update_init() {
4821

    
4822
  	parse_update_pbi_cmdline "$@"
4823

    
4824
	check_enable_disable_auto
4825

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

    
4829
	start_update_checks
4830
	if [ "$?" != "0" ] ; then rm_tmpdir ; exit 1 ; fi
4831

    
4832
	# Stop here if only doing update checks
4833
	if [ -n "${PBI_UPCHECK}" ]; then return 0 ; fi
4834

    
4835
  	require_root_or_group
4836

    
4837
	do_pbi_update
4838
}
4839

    
4840
# Check if we are enabling / disabling auto-updating
4841
check_enable_disable_auto()
4842
{
4843
	if [ -z "$PBI_UPENABLEAUTO" ] ; then return ; fi
4844
	if [ ! -d "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}" ] ; then return ; fi
4845

    
4846
	# Enable / disable auto-updating now
4847
	if [ "$PBI_UPENABLEAUTO" = "YES" ]; then
4848
		touch ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable
4849
	else
4850
		rm ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable >/dev/null 2>/dev/null
4851
	fi
4852
}
4853

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

    
4858
        # See which repo / key this PBI associates to, if any
4859
	check_valid_sigs "${1}"
4860
	if [ "$?" = "0" -a -n "$PBI_VALIDKEYSIG" ] ; then
4861
		_rMd5="`echo ${PBI_VALIDKEYSIG} | cut -d '.' -f 1`"
4862
		echo "$_rMd5" | sed "s|${PBI_DBKEYDIR}/||g" > ${1}/pbi_repo
4863
	fi
4864
}
4865

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

    
4870
	# Open up the tmpdir
4871
	init_tmpdir
4872

    
4873
	if [ "${PBI_UPCHECK}" = "YES" ] ; then
4874
		load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4875
		if [ -z "${PBI_REPO}" ]; then
4876
			pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
4877
		fi
4878
		if [ -z "${PBI_REPO}" ]; then
4879
			return 1
4880
		else
4881
			local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
4882
		fi
4883

    
4884
		check_pbi_update "$PBI_UPDATEAPP" "display" \
4885
	 	 "$PBI_PROGNAME" "current" \
4886
	 	 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
4887
		return $?
4888
	else
4889
		# Loop and check all PBIs for updates
4890
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
4891
                do
4892
			PBI_REPO=""
4893
                        if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
4894
				load_info_from_dir "${PBI_DBAPPDIR}/${i}"
4895
				if [ -z "${PBI_REPO}" ]; then
4896
					pbi_checksig_repomatch "${PBI_DBAPPDIR}/${i}"
4897
				fi
4898
				if [ -z "${PBI_REPO}" ]; then
4899
					continue
4900
				else
4901
					local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
4902
				fi
4903

    
4904
				check_pbi_update "$i" "display" \
4905
				 "$PBI_PROGNAME" "current" \
4906
				 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
4907
                        fi
4908
                done
4909
		return 0
4910
	fi
4911

    
4912
}
4913

    
4914
# Check if we need to pull down the updated INDEX file
4915
check_update_index() {
4916

    
4917
	init_tmpdir
4918
	
4919
	local _repoMd5="$1"
4920
	local _rURL=`cat ${PBI_DBREPODIR}/*${_repoMd5} | grep URL: | sed 's|URL: ||g'`
4921

    
4922
	_pbiIndex="${PBI_DBINDEXDIR}/${_repoMd5}-index"
4923
	_pbiMeta="${PBI_DBINDEXDIR}/${_repoMd5}-meta"
4924
	_pbiIndexTime="${_pbiIndex}.time"
4925
	_tmpPbiIndex="${PBI_TMPDIR}/.upcheck$$"
4926
	_tmpPbiMeta="${PBI_TMPDIR}/.upcheck$$"
4927
		
4928
	# Check if its been greater than $PBI_INDEXREFRESH hours since the last update
4929
	if [ -e "${_pbiIndexTime}" ] ; then
4930
		_curTime=`date +%s`
4931
		_oTime=`cat ${_pbiIndexTime}`
4932
		_trigTime=`expr ${PBI_INDEXREFRESH} \* 60 \* 60`
4933
		expr $_curTime - $_oTime >/dev/null 2>/dev/null
4934
		if [ "$?" = "0" ] ; then
4935
			_passed=`expr $_curTime - $_oTime`
4936
			if [ "$_passed" -lt "$_trigTime" ] ; then
4937
				return;
4938
			fi
4939
		fi
4940
		
4941
	fi
4942

    
4943
	if [ "${PBI_VERBOSE}" = "YES" ] ; then
4944
		echo "Updating index ${_pbiIndex}"
4945
		echo "Updating index ${_pbiIndex}: `date`" >> ${_pbid_log}
4946
	fi
4947

    
4948
	# Check that the last char isn't a '/'
4949
	_tmp=`echo ${_rURL} | wc -m | tr -s ' ' | tr -d ' '`
4950
	_tmp2=`expr $_tmp - 1`
4951
	_lastC=`echo ${_tmp} | cut -c ${_tmp2}-${_tmp}`
4952
	if [ "${_lastC}" = "/" ] ; then
4953
		_upURL="`echo ${_rURL} | sed 's|\(.*\).|\1|'`"
4954
	else
4955
		_upURL="${_rURL}"
4956
	fi
4957

    
4958
	fetch -o "${_tmpPbiIndex}.bz2" "${_upURL}/${PBI_INDEXUPFILE}.bz2" >/dev/null 2>/dev/null
4959
	if [ "$?" != "0" ] ; then
4960
		return
4961
	fi
4962

    
4963
	bzip2 -d "${_tmpPbiIndex}.bz2" >/dev/null 2>/dev/null
4964
	if [ "$?" != "0" ] ; then
4965
		return
4966
	fi
4967

    
4968
	# Move the uncompressed file
4969
	mv "${_tmpPbiIndex}" "${_pbiIndex}" >/dev/null 2>/dev/null
4970

    
4971
	# Wait a sec
4972
 	sleep 1
4973

    
4974
	# Now check for an optional meta file update
4975
	fetch -o "${_tmpPbiMeta}.bz2" "${_upURL}/${PBI_METAUPFILE}.bz2" >/dev/null 2>/dev/null
4976
	if [ "$?" = "0" ] ; then
4977
		bzip2 -d "${_tmpPbiMeta}.bz2" >/dev/null 2>/dev/null
4978
		if [ "$?" = "0" ] ; then
4979
			mv "${_tmpPbiMeta}" "${_pbiMeta}" >/dev/null 2>/dev/null
4980
		fi
4981
	fi
4982

    
4983
	# Update the icons for this repos meta file
4984
	update_repo_icons "${_repoMd5}" "${_pbiMeta}"
4985

    
4986
	echo "Finished updating index ${_pbiIndex}: `date`" >> ${_pbid_log}
4987
	if [ "${PBI_VERBOSE}" = "YES" ] ; then
4988
		echo "Finished updating index ${_pbiIndex}"
4989
	fi
4990

    
4991
	# Save the time that we are done
4992
	date +%s > ${_pbiIndexTime}
4993

    
4994
}
4995

    
4996
# Check if we need to update any repository icons
4997
update_repo_icons() {
4998
	_repoMd5="$1"
4999
	_repoMeta="$2"
5000

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

    
5003
	# Loop through, downloading icons we find
5004
	while read mLine
5005
	do
5006
		# Make sure this is an app / cat
5007
		echo "$mLine" | grep -e "^App=" -e "^Cat=" >/dev/null 2>/dev/null
5008
		if [ "$?" != "0" ] ; then continue ; fi
5009

    
5010
		# Get the icon URL
5011
		echo "$mLine" | grep "^App=" >/dev/null 2>/dev/null
5012
		if [ "$?" = "0" ] ; then
5013
			line=`echo $mLine | sed 's|^App=||g'`
5014
			aIcon=`echo $line | cut -d ';' -f 3`
5015
		else
5016
			line=`echo $mLine | sed 's|^Cat=||g'`
5017
			aIcon=`echo $line | cut -d ';' -f 2`
5018
		fi
5019
		iName=`echo $line | cut -d ';' -f 1`
5020
		ext=`echo $aIcon | sed 's/.*\.//'`
5021

    
5022
		# Now fetch the file
5023
		sFile="${PBI_DBICONDIR}/${_repoMd5}-${iName}.${ext}"
5024
		fetch -o "${sFile}" "${aIcon}" >/dev/null 2>/dev/null
5025
		if [ $? -ne 0 ]; then
5026
		  # Wait a moment before trying the next
5027
		  sleep 40 
5028
		fi
5029
		
5030
	done < ${_repoMeta}
5031
}
5032

    
5033
# Check a specific PBI for updates
5034
check_pbi_update() {
5035

    
5036
	# Init the tmpdir
5037
	init_tmpdir
5038

    
5039
	# Set the vars
5040
	_upbi="${1}"
5041
	_udisp="${2}"
5042
	_uprog="${3}"
5043
	_uver="${4}"
5044
	_ufbsdver="${5}"
5045
	_uarch="${6}"
5046
	_urepo="${7}"
5047
	_omdate="${8}"
5048

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

    
5051
	PBI_UPNVER=""
5052
	PBI_UPFILE=""
5053
	PBI_UPPATCHES=""
5054
	PBI_UPCSUM=""
5055
	PBI_UPMDATE=""
5056
	PBI_UPREPO=""
5057
	PBI_UPSIZE=""
5058

    
5059
	# If we are looking for the current app, set _uver accordingly
5060
	if [ "$_uver" = "current" ] ; then
5061
		_uver=":current"
5062
	else
5063
		_uver=":${_uver}:"
5064
	fi
5065

    
5066

    
5067
	for _repo in `ls ${PBI_DBINDEXDIR}`
5068
	do
5069

    
5070
		if [ "$_urepo" = "AUTO" ] ; then
5071
			_pbiIndex="${PBI_DBINDEXDIR}/${_repo}"
5072
			_rMd5="`echo ${_repo} | sed 's|-index||g'`"
5073
		else
5074
			_rMd5=`ls ${PBI_DBREPODIR}/${_urepo}.* | cut -d '.' -f 2`
5075
			_pbiIndex="${PBI_DBINDEXDIR}/${_rMd5}-index"
5076
		fi
5077

    
5078
		if [ ! -e "${_pbiIndex}" ] ; then continue ; fi
5079

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

    
5083
		PBI_UPNVER="`echo $_upLine | cut -d ':' -f 3`"
5084
		PBI_UPFILE="`echo $_upLine | cut -d ':' -f 6`"
5085
		PBI_UPPATCHES="`echo $_upLine | cut -d ':' -f 8`"
5086
		PBI_UPCSUM="`echo $_upLine | cut -d ':' -f 4`"
5087
		PBI_UPMDATE="`echo $_upLine | cut -d ':' -f 5`"
5088
		PBI_UPSIZE="`echo $_upLine | cut -d ':' -f 8`"
5089
		PBI_UPMIRROR="`cat ${PBI_DBMIRRORDIR}/${_rMd5} 2>/dev/null`"
5090
		PBI_UPREPO="${_rMd5}"
5091

    
5092
		if [ -n "${PBI_UPNVER}" ] ; then break; fi
5093
		if [ "${_urepo}" != "AUTO" ] ; then break; fi
5094

    
5095
	done
5096

    
5097
	# If no new version
5098
	if [ -z "$PBI_UPNVER" ] ; then return 1 ; fi
5099

    
5100
	# See if this update is newer than the installed date
5101
	if [ -n "$_omdate" ] ; then
5102
		nDay=`echo $PBI_UPMDATE | cut -d ' ' -f 1`
5103
		nHour=`echo $PBI_UPMDATE | cut -d ' ' -f 2`
5104
		oDay=`echo $_omdate | cut -d ' ' -f 1`
5105
		oHour=`echo $_omdate | cut -d ' ' -f 2`
5106

    
5107
		# Make sure we have all legit numbers
5108
		if [ $(is_num "$nDay") -a $(is_num "$nHour") \
5109
			-a $(is_num "$oDay") -a $(is_num "$oHour") ] ; then
5110
			if [ $oDay -gt $nDay ] ; then return 1 ; fi
5111
			if [ "$oDay" = "$nDay" -a $oHour -gt $nHour ] ; then return 1 ; fi
5112
		fi
5113
	fi
5114

    
5115
	if [ "$PBI_UPNVER" != "$PBI_PROGVERSION" ] ; then
5116
		if [ "$_udisp" = "display" ] ; then 
5117
			echo "${_upbi} - Available: ${PBI_UPNVER}"
5118
		fi
5119
		return 0
5120
	else
5121
		return 1
5122
	fi
5123
}
5124

    
5125
# Start PBI update process
5126
do_pbi_update() {
5127
	if [ -n "${PBI_UPCHECK}" ]; then return 0 ; fi
5128

    
5129
	if [ "$PBI_UPDATEAPP" = "ALL" ] ; then
5130
		# Loop and check all PBIs for updates
5131
		for i in `ls ${PBI_DBAPPDIR}/ 2>/dev/null`
5132
                do
5133
			if [ -e "${PBI_DBAPPDIR}/${i}/.updating" ] ; then
5134
				ps -p `cat ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating` >/dev/null 2>/dev/null
5135
				if [ "$?" = "0" ] ; then
5136
					continue
5137
				fi
5138
				rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5139
			fi
5140
                        if [ -e "${PBI_DBAPPDIR}/${i}/pbi_name" ] ; then
5141
				PBI_UPDATEAPP="${i}"
5142
				start_pbi_updateapp "all"
5143
                        fi
5144
		done
5145
	else
5146
		if [ -e "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" ] ; then
5147
			ps -p `cat ${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating` >/dev/null 2>/dev/null
5148
			if [ "$?" = "0" ] ; then
5149
				exit_err "This application is currently updating."
5150
			fi
5151
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5152
		fi
5153
		start_pbi_updateapp "single"
5154
	fi
5155
}
5156

    
5157
# Attempt to download a PBI from the update server for "pbi_add -r"
5158
pbi_add_fetch_remote() {
5159
	# Set the target program we want to download
5160
	_rtar="$PBI_FILENAME"
5161
	unset PBI_FILENAME
5162

    
5163
	# Check if the user overrode the arch / versions we want to install
5164
	_rArch=`uname -m`
5165
	if [ -n "$PBI_ADD_ALTARCH" ] ; then _rArch=$PBI_ADD_ALTARCH ; fi
5166

    
5167
	_rVer="current"
5168
	if [ -n "$PBI_ADD_ALTVER" ] ; then _rVer=$PBI_ADD_ALTVER ; fi
5169

    
5170

    
5171
	check_pbi_update "$_rtar" "nodisplay" \
5172
	 "$_rtar" "$_rVer" \
5173
	 "`uname -r`" "$_rArch" "${PBI_ADDREPO_ID}"
5174
	if [ "$?" != "0" ] ; then 
5175
		exit_err "Could not find \"$_rtar\" in any indexes" 
5176
	fi
5177

    
5178
	# We've gotten this far, now download the updated PBI
5179
	pbi_update_dl
5180
	if [ "$?" != "0" ] ; then
5181
		exit_err "Failed downloading PBI"
5182
	fi
5183

    
5184
	# Now overwrite the PBI_FILENAME and let us proceed to regular install
5185
	PBI_FILENAME="$PBI_UPDLFILE"
5186

    
5187
	# If we are only fetching, finish up now
5188
	if [ "$PBI_REMOTEFETCHONLY" = "YES" ] ; then
5189
		mv $PBI_FILENAME ./`basename ${PBI_UPFILE}`
5190
		echo "PBI saved to ./`basename ${PBI_UPFILE}`"
5191
		exit_trap
5192
	fi
5193

    
5194
}
5195

    
5196
# Update the targed PBI
5197
start_pbi_updateapp() {
5198
	_upact="${1}"
5199
	if [ "$2" = "pbid" ] ; then 
5200
		_pbidlog="$2"
5201
	else
5202
		_pbidlog=""
5203
	fi
5204

    
5205
	echo "$$" > "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5206

    
5207
	# Check for update to this app, and exit or return if not available
5208
	load_info_from_dir "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5209
	if [ -z "${PBI_REPO}" ]; then
5210
		pbi_checksig_repomatch "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}"
5211
	fi
5212
	if [ -z "${PBI_REPO}" ]; then
5213
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5214
		return
5215
	else
5216
		local _repoID=`ls ${PBI_DBREPODIR}/*.${PBI_REPO} | cut -d '.' -f 1 | sed "s|${PBI_DBREPODIR}/||g"`
5217
	fi
5218

    
5219
	check_pbi_update "$PBI_UPDATEAPP" "nodisplay" \
5220
	 "$PBI_PROGNAME" "current" \
5221
	 "$PBI_FBSDVER" "$PBI_APPARCH" "$_repoID" "$PBI_PROGMDATE"
5222
	if [ "$?" != "0" ] ; then 
5223
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5224
		if [ "$_upact" = "single" ] ; then
5225
			exit_err "$PBI_UPDATEAPP - no update available!"
5226
		else
5227
			return 1
5228
		fi
5229
	fi
5230
	
5231
	
5232
	echo "Starting update of ${PBI_UPDATEAPP} to ${PBI_UPNVER}..."
5233
	_pbilow="`echo ${PBI_PROGNAME} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
5234

    
5235
	# Check if there is a possible patch file for this update
5236
	# new filename to download
5237
	_pFile="${_pbilow}-${PBI_PROGVERSION}_to_${PBI_UPNVER}-${PBI_APPARCH}.pbp"
5238

    
5239
	# Try downloading the patch file
5240
	echo "Trying update via patchfile..."
5241
	pbi_update_dl "$_pFile" "OFF"
5242
	if [ "$?" = "0" ] ; then
5243
		# We had a good patch download, try applying it now
5244
		echo "Updating via patch file..."
5245
		pbi_patch "$PBI_UPDLFILE" #>/dev/null 2>/dev/null
5246
		if [ "$?" != "0" ] ; then
5247
			# Patching failed, we'll grab a fresh copy next
5248
			echo "Failed to patch with ${PBI_UPDLFILE}"
5249
			echo "Will try full file update"
5250
		else
5251
			echo "Patch successful!"
5252
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" >/dev/null 2>/dev/null
5253
			rm "${PBI_UPDLFILE}" >/dev/null 2>/dev/null
5254
			return 0
5255
		fi
5256
			
5257
	fi
5258

    
5259
	# No patch file, grab the full app
5260
	echo "Trying update via full-file..."
5261
	pbi_update_dl 
5262
	if [ "$?" != "0" ] ; then
5263
		if [ "$_upact" = "single" ] ; then
5264
			rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating"
5265
			exit_err "Failed downloading update!"
5266
		fi
5267
	fi
5268

    
5269
	echo " "
5270

    
5271
	# Save the auto-update status
5272
	if [ -e "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/autoupdate-enable" ] ; then
5273
		_autoUpEnable="YES"
5274
	else
5275
		_autoUpEnable="NO"
5276
	fi
5277
	
5278
	echo -e "Removing old version...\c"
5279
	pbi_delete "${PBI_UPDATEAPP}"
5280
	echo "Done"
5281

    
5282
	# Now install new PBI
5283
	echo -e "Installing new version...\c"
5284
	pbi_add --licagree -f "$PBI_UPDLFILE" >/dev/null 2>/dev/null
5285
	if [ "$?" != "0" ] ; then
5286
		echo "Failed to install PBI: ${PBI_UPDLFILE}"
5287
		rm "${PBI_UPDLFILE}"
5288
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" 2>/dev/null
5289
		return 1
5290
	else
5291
		if [ "$_autoUpEnable" = "YES" ] ; then
5292
		 	touch "${PBI_DBAPPDIR}/${_pbilow}-${PBI_UPNVER}-${PBI_APPARCH}/autoupdate-enable"
5293
		fi
5294
		echo "Done"
5295
		rm "${PBI_UPDLFILE}"
5296
		rm "${PBI_DBAPPDIR}/${PBI_UPDATEAPP}/.updating" 2>/dev/null
5297
		return 0
5298
	fi	
5299
}
5300

    
5301
# Start downloading the update
5302
pbi_update_dl() {
5303

    
5304
	_tPatch=$1
5305
	local _CKSUM="$2"
5306
	
5307
	# Set local download location
5308
	_dl_loc="${PBI_APPDIR}/.`basename $PBI_UPFILE`.$$"
5309

    
5310
	# Have a patch file to download instead, make that the active file to try
5311
	if [ -n "$_tPatch" ] ; then
5312
		_bDir=`dirname $PBI_UPFILE`
5313
		_uFile="${_bDir}/${_tPatch}"
5314
	else
5315
		_uFile="${PBI_UPFILE}"
5316
	fi
5317

    
5318
	_mirrorList=`echo $PBI_UPMIRROR | sed 's|\n| |g'`
5319

    
5320
	# Start download from repos mirror(s) in order
5321
	for _cMirror in $_mirrorList
5322
	do
5323
		_furl="`echo $_cMirror | sed 's/\/*$//'`${_uFile}"
5324
		echo "Downloading ${_furl}"
5325
		pbi_get_file "$_furl" "$_dl_loc"
5326
		if [ "$?" != "0" ]  ; then 
5327
			rm "${_dl_loc}" >/dev/null 2>/dev/null
5328
			echo "Download Failed: ${_furl}"
5329
			continue
5330
		fi
5331
		_upcsum=`sha256 -q "$_dl_loc"`
5332
		if [ "$_CKSUM" != "OFF" -a "$_upcsum" != "$PBI_UPCSUM" ] ; then
5333
			rm "${_dl_loc}" >/dev/null 2>/dev/null
5334
			echo "Download fails checksum: ${_furl}"
5335
			continue
5336
		fi
5337

    
5338
		# If we get this far, we have a good file!
5339
		PBI_UPDLFILE="$_dl_loc"
5340
		sync
5341
		return 0
5342
	done
5343

    
5344
	return 1
5345
}
5346

    
5347
# Function to download a file from remote using fetch
5348
pbi_get_file() {
5349
	_rf="${1}"
5350
	_lf="${2}"
5351

    
5352
	# Wait a sec
5353
	sleep 1
5354

    
5355
	init_tmpdir
5356
	if [ -e "${_lf}" ] ; then rm "$_lf" ; fi
5357

    
5358
	if [ "$PBI_FETCH_PARSING" != "YES" ] ; then
5359
		fetch -o "${_lf}" "${_rf}"
5360
		_err=$?
5361
	else
5362
		# Doing a front-end download, parse the output of fetch
5363
		_eFile="${PBI_TMPDIR}/.fetch-exit.$$"
5364
		fetch -s "${_rf}" > ${PBI_TMPDIR}/.fetch-size.$$ 2>/dev/null
5365
		_fSize=`cat ${PBI_TMPDIR}/.fetch-size.$$ 2>/dev/null`
5366
		_fSize="`expr ${_fSize} / 1024 2>/dev/null`"
5367
		rm "${PBI_TMPDIR}/.fetch-size.$$" 2>/dev/null
5368
		_time=0
5369

    
5370
		( fetch -o "${_lf}" "${_rf}" >/dev/null 2>/dev/null ; echo "$?" > ${_eFile} ) &
5371
		FETCH_PID=`ps -auwwwx | grep -v grep | grep "fetch -o ${_lf}" | awk '{print $2}'`
5372
		FETCH_TFILE="${_lf}"
5373
		while
5374
		z=1
5375
		do
5376
			if [ -e "${_lf}" ] ; then
5377
				_dSize=`du -k ${_lf} | tr -d '\t' | cut -d '/' -f 1`
5378
				if [ $(is_num "$_dSize") ] ; then
5379
					if [ ${_fSize} -lt ${_dSize} ] ; then _dSize="$_fSize" ; fi
5380
					_kbs=`expr ${_dSize} \/ $_time`
5381
					echo "SIZE: ${_fSize} DOWNLOADED: ${_dSize} SPEED: ${_kbs}KBs"
5382
				fi
5383
			fi
5384

    
5385
			# Make sure download isn't finished
5386
			ps -p $FETCH_PID >/dev/null 2>/dev/null
5387
			if [ "$?" != "0" ] ; then break ; fi
5388
			sleep 2
5389
			_time=`expr $_time + 2`
5390
		done
5391

    
5392
		_err="`cat ${_eFile}`"
5393
		if [ "$_err" = "0" ]; then echo "FETCHDONE" ; fi
5394
		unset FETCH_PID FETCH_TFILE
5395
	fi
5396

    
5397
	echo ""
5398
	return $_err
5399
}
5400

    
5401
is_num()
5402
{
5403
	expr $1 + 1 2>/dev/null
5404
	return $?
5405
}
5406

    
5407
# Function to check if the port is flagged to only build on specific arch
5408
# Returns 0 for OK, 1 for invalid arch
5409
check_port_compat_arch()
5410
{
5411
	local sPort=$1
5412
 	local cValues="`make -C $sPort -V ONLY_FOR_ARCHS`"
5413
	if [ -z "$cValues" ] ; then return 0 ; fi
5414

    
5415
	for cArch in $cValues
5416
	do
5417
		if [ "$cArch" = "`uname -m`" ] ; then
5418
			return 0
5419
		fi
5420
	done
5421
	
5422
	return 1
5423
}
5424

    
5425
# start processing autobuild
5426
pbi_autob_init() {
5427

    
5428
        require_root
5429

    
5430
        parse_autob_pbi_cmdline "$@"
5431

    
5432

    
5433
        do_pbi_autob
5434
}
5435

    
5436
# Start the auto-build traversal process
5437
do_pbi_autob() {
5438

    
5439
	# Prune any outdir files which we don't have modules for
5440
	do_pbi_autob_prune
5441

    
5442
	cd "${PBI_AB_CONFDIR}"
5443
	init_tmpdir
5444

    
5445
	# Get this runs timestamp
5446
	PBI_AB_TIMESTAMP=`date | md5`
5447

    
5448
	while
5449
	z=1
5450
	do
5451
  	  AB_FOUND="0"
5452
	  unset CUR_PRIORITY_PBI CUR_WORKING_PBI
5453
		
5454
	  for pbi in `find . -type f -name "${PBI_CONFFILE}" | grep -v '\.svn' | sort`
5455
	  do
5456
		# Figure out the target port for this build
5457
		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
5458
		. ${pbi}
5459

    
5460
		# If we have a PBI already and this one has no version we can continue
5461
	        if [ -z "${PBI_AB_PRIORITY}" -a -n "${CUR_WORKING_PBI}"  ] ; then continue ; fi
5462

    
5463
		_cd=$(dirname $pbi | sed 's|./||')
5464

    
5465
		# Make sure PBI_MAKEPORT is set
5466
		if [ -z "${PBI_MAKEPORT}" ] ; then
5467
			PBI_MAKEPORT=`echo $pbi | sed 's|./||'`
5468
			export PBI_MAKEPORT
5469
		fi	
5470

    
5471
		if [ ! -d "${PORTSDIR}/${PBI_MAKEPORT}" ] ; then 
5472
			echo "Skipping invalid port ${PORTSDIR}/${PBI_MAKEPORT}"
5473
			continue
5474
		fi
5475
		
5476
		# Check if this port can be built on this architecture
5477
		check_port_compat_arch "${PORTSDIR}/${PBI_MAKEPORT}"
5478
		if [ "$?" = "1" ] ; then
5479
			#echo "Incompatiable port arch: ${PORTSDIR}/${PBI_MAKEPORT}"
5480
			continue
5481
		fi
5482
		
5483
		# Check for missing port target
5484
		if [ -z "$PBI_MAKEPORT" ] ; then
5485
			echo "Warning: Missing PBI_MAKEPORT for ${pbi}"
5486
			continue
5487
		fi
5488

    
5489
		check_ab_needed "$PBI_MAKEPORT" "${PBI_BUILDKEY}" "$_cd" "$PBI_AB_TIMESTAMP"
5490
	 	if [ "$?" = "0" ] ; then	
5491
		   AB_FOUND="1"
5492

    
5493
		   # Check the priority of this PBI, see if it rises to the top
5494
		   if [ -z "${CUR_PRIORITY_PBI}" ] ; then 
5495
		     CUR_WORKING_PBI="${pbi}"
5496
		     if [ -z "$PBI_AB_PRIORITY" ] ; then 
5497
                       CUR_PRIORITY_PBI="0"
5498
	             else
5499
                       CUR_PRIORITY_PBI="$PBI_AB_PRIORITY"
5500
                     fi
5501
                     continue
5502
                   fi
5503

    
5504
		   # No priority set, keep the previous build
5505
		   if [ -z "${PBI_AB_PRIORITY}" ] ; then continue ; fi
5506

    
5507
		   if [ $CUR_PRIORITY_PBI -lt $PBI_AB_PRIORITY ] ; then
5508
		     CUR_WORKING_PBI="${pbi}"
5509
                     CUR_PRIORITY_PBI="$PBI_AB_PRIORITY"
5510
		     continue
5511
		   fi
5512

    
5513
		   continue
5514
		fi
5515

    
5516
	  done
5517

    
5518
	  # We have something to build lets do it!
5519
	  if [ "$AB_FOUND" = "1" ] ; then 
5520
	      pbi="$CUR_WORKING_PBI"
5521
	      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
5522
	      . ${pbi}
5523
	      get_pbi_progversion
5524

    
5525
	      _cd=$(dirname $pbi | sed 's|./||')
5526
	      if [ -z "${PBI_MAKEPORT}" ] ; then
5527
	 	PBI_MAKEPORT=$(dirname $pbi | sed 's|./||')
5528
	      fi	
5529

    
5530
	      echo "Starting build of: $pbi  - Priority: $CUR_PRIORITY_PBI"
5531

    
5532
	      # Start the build now
5533
	      start_ext_ab "$PBI_MAKEPORT" \
5534
		"${PBI_BUILDKEY}" "${PBI_PROGVERSION}" \
5535
		"${_cd}" "${PBI_AB_OUTDIR}" "${PBI_AB_TIMESTAMP}"
5536

    
5537
	      echo " "
5538

    
5539
	  else
5540
	    # If no builds left, we are done!
5541
            break
5542
          fi
5543
	done 
5544
	
5545
}
5546

    
5547
# Prune any outdir files which don't have matching modules
5548
do_pbi_autob_prune() {
5549
	if [ "${PBI_AB_PRUNE}" != "YES" ] ; then return 0 ; fi
5550

    
5551
    	# Prune outgoing dirs which don't have matching modules anymore
5552
	cd "${PBI_AB_OUTDIR}"
5553
	for i in `find . -type d | grep -v '\.svn'`
5554
	do
5555
		if [ "${i}" = "." -o "${i}" = ".." ] ; then continue ; fi
5556
		_pDir=`dirname ${i}`
5557
		if [ -d "${i}" -a -n "${i}" ] ; then
5558
    			if [ ! -e "${PBI_AB_CONFDIR}/${_pDir}" ] ; then
5559
      			# Not in our module tree anymore, remove it
5560
      			echo "Auto-Prune: ${PBI_AB_OUTDIR}/${_pDir}"
5561
      			rm -rf "${PBI_AB_OUTDIR}/${_pDir}"
5562
    			fi
5563
  		fi
5564
	done
5565
	cd
5566
}
5567

    
5568
# Start the pbi_makeport process
5569
start_ext_ab() {
5570
	_mp="${1}"
5571
	_bk="${2}"
5572
	_pv="${3}"
5573
	_cd="${4}"
5574
	_od="${5}/${_cd}"
5575
	local _abkey="$6"
5576
	_flags=""
5577
	_flags="-c ${_cd} -d ${PORTSDIR} -o ${_od} --delbuild"
5578
	if [ -n "${PBI_AB_SSLPRIVKEY}" ] ; then
5579
		_flags="${_flags} --sign ${PBI_AB_SSLPRIVKEY}"
5580
	fi
5581

    
5582
	# Check if we need to enable tmpfs
5583
 	if [ "$PBI_AB_TMPFS" = "YES" -a -z "$PBI_AB_NOTMPFS" ] ; then
5584
		_flags="${_flags} --tmpfs"
5585
	fi
5586

    
5587
	# Check if we need to enable pkgcaching
5588
 	if [ "$PBI_AB_PKGCACHE" = "YES" -a -z "$PBI_AB_NOPKGCACHE"  ] ; then
5589
		if [ ! -d "${_od}/pkgcache" ] ; then
5590
			mkdir -p ${_od}/pkgcache
5591
		fi
5592
		_flags="${_flags} --pkgdir ${_od}/pkgcache"
5593
	fi
5594
	get_pbi_progversion
5595

    
5596
	#echo "Starting build of ${_mp} - ${_pv}"
5597
	echo "pbi_makeport ${_flags} ${_mp}"
5598

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

    
5601
	# Save the autobuild hash key
5602
	echo "$_abkey" > ${_od}/.abkey
5603
	
5604
	# Save the build key for this PBI
5605
	if [ -n "$_bk" ] ; then
5606
		echo "$_bk" > "${_od}/pbi-buildkey"
5607
	else
5608
		echo "__NONE__" > "${_od}/pbi-buildkey"
5609
	fi
5610

    
5611
	# Clean old log files
5612
	if [ -e "${_od}/build.log" ] ; then
5613
		rm "${_od}/build.log"
5614
	fi
5615
	if [ -e "${_od}/build.log.bz2" ] ; then
5616
		rm "${_od}/build.log.bz2"
5617
	fi
5618
	if [ -e "${_od}/.failed-csum" ] ; then
5619
		rm ${_od}/.failed-csum
5620
	fi
5621

    
5622
	# Move old PBIs to archived folder
5623
        oldVersion=`cat ${_od}/pbi-version 2>/dev/null`
5624
	if [ "$oldVersion" != "$PBI_PROGVERSION" ]; then
5625
		echo "Archiving old PBIs..."
5626
		archive_old_pbis "${_od}" "$PBI_AB_ARCHIVENUM"
5627
	fi
5628

    
5629
	# Add some header info to log file
5630
	echo "Starting build: `date`" >${_od}/build.log
5631
	echo "Build Command:" >>${_od}/build.log
5632
	echo "pbi_makeport ${_flags} ${_mp}" >>${_od}/build.log
5633
	echo "------------------------------------------------------" >>${_od}/build.log
5634

    
5635
	# Start the build now
5636
	pbi_makeport ${_flags} ${_mp} >>${_od}/build.log 2>>${_od}/build.log
5637
	if [ "$?" = "0" ] ; then
5638

    
5639
		echo "$PBI_PROGVERSION" > "${_od}/pbi-version"
5640
		echo "OK" > "${_od}/pbi-result"
5641

    
5642
		# Save the mdate file
5643
		date "+%Y%m%d %H%M%S" >${_od}/pbi-mdate
5644

    
5645
		if [ -n "${PBI_AB_HELPS}" ] ; then
5646
			${PBI_AB_HELPS} "OK" "${_od}"
5647
		fi
5648

    
5649
		# Copy over a description file
5650
		if [ -e "${PORTSDIR}/${_mp}/pkg-descr" ] ; then
5651
			cp "${PORTSDIR}/${_mp}/pkg-descr" "${_od}/pbi-descr"
5652
		fi
5653
		if [ -e "${_cd}/pbi-descr" ] ; then
5654
			cp "${_cd}/pbi-descr" "${_od}/pbi-descr"
5655
		fi
5656

    
5657
		# Generate patch files to the new version of this PBI
5658
		if [ "$PBI_AB_GENPATCH" = "YES" -a -d "${_od}/archived" ] ; then
5659
			gen_pbi_patches "${_od}" "${_od}/archived" >>${_od}/build.log 2>>${_od}/build.log
5660
		fi
5661

    
5662
		rm "${_od}/build.log.bz2" >/dev/null 2>/dev/null
5663
		bzip2 "${_od}/build.log"
5664

    
5665
	else
5666
		# Save the md5sum of the ports directory
5667
		tar cvf - -C "${PORTSDIR}/${_mp}" . 2>/dev/null | md5 -q >${_od}/.failed-csum
5668

    
5669
		echo "Failed" > "${_od}/pbi-result"
5670
		if [ -n "${PBI_AB_HELPS}" ] ; then
5671
			${PBI_AB_HELPS} "FAILED" "${_od}"
5672
		fi
5673
	fi
5674
}
5675

    
5676
# Function which begins to generate patch files from archived PBIs to current
5677
gen_pbi_patches()
5678
{
5679
	_curPBIdir="$1"
5680
	_oldPBIdir="$2"
5681

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

    
5684
	# First remove any old patches
5685
	rm ${_curPBIdir}/*.pbp 2>/dev/null
5686

    
5687
	# Make sure to enable signing of the patch files
5688
	if [ -n "${PBI_AB_SSLPRIVKEY}" ] ; then
5689
        	local _mpflags="-o $_curPBIdir --sign ${PBI_AB_SSLPRIVKEY}"
5690
	else
5691
		local _mpflags="-o $_curPBIdir"
5692
	fi
5693

    
5694
	# Build a list of old PBIs we need to make patches from
5695
	for _oPBI in `ls ${_oldPBIdir}/*.pbi 2>/dev/null`
5696
	do
5697
		# Make sure we don't try to make a patch of identical files
5698
	  	if [ "`basename $_oPBI`" != "`basename $_curPBI`" ] ; then	
5699
			echo "Building pbp patch of ${_oPBI} -> ${_curPBI}"
5700
			pbi_makepatch $_mpflags "$_oPBI" "$_curPBI" 
5701
			if [ "$?" != "0" ] ; then
5702
				echo "pbi_makepatch: Failed creating patchfile for $_oPBI -> $_curPBI"
5703
			fi
5704
		 	
5705
		fi
5706
	done
5707
}
5708

    
5709
# Function which compares two PBIs, and creates a .pbp file from the differences 
5710
make_pbi_patchfile()
5711
{
5712
	_pbiNew="$1"
5713
	_pbiOld="$2"
5714
	_cDir="$3"
5715

    
5716
	init_tmpdir
5717

    
5718
        # Load all the information about this PBI / PBP
5719
	PBI_FILENAME="$1"
5720
        load_info_from_header
5721

    
5722
	_pbiNewDir="${PBI_APPDIR}/.newPBI-$$"
5723
	_pbiOldDir="${PBI_APPDIR}/.oldPBI-$$"
5724
	_pbiPatchDir="${PBI_APPDIR}/.patchPBI-$$"
5725
	_pbiPatchHeaderDir="${PBI_APPDIR}/.patchPBIHeaderDir-$$"
5726
	_pbiPatchArchiveFile="${PBI_APPDIR}/.patchPBIArchive-$$"
5727
	_pbiPatchHeaderFile="${PBI_APPDIR}/.patchPBIHeaderFile-$$"
5728

    
5729
	# Get the PBI Versions
5730
	get_ver_from_pbi_file "$_pbiNew"
5731
	_pbiNewVer="$VAL"
5732
	get_ver_from_pbi_file "$_pbiOld"
5733
	_pbiOldVer="$VAL"
5734

    
5735
	# Get the PBI directory names
5736
	get_prefix_from_pbi_file "$_pbiNew"
5737
	_pbiNewPrefix="`basename $VAL`"
5738
	get_prefix_from_pbi_file "$_pbiOld"
5739
	_pbiOldPrefix="`basename $VAL`"
5740

    
5741
	# Get the mdate of the old PBI
5742
	get_mdate_from_pbi_file "$_pbiOld"
5743
	_pbiOldMDate="$VAL"
5744

    
5745
	# Sanity check these prefixes
5746
	if [ "${_pbiNewPrefix}" != "${_pbiOldPrefix}" ] ; then
5747
		echo "Error: Prefix mismatch between $_pbiNew and $_pbiOld"
5748
		return
5749
	fi
5750

    
5751
	# Make our extraction directories
5752
	if [ -e "$_pbiNewDir" ] ; then rm -rf "$_pbiNewDir"; fi
5753
	if [ -e "$_pbiOldDir" ] ; then rm -rf "$_pbiOldDir"; fi
5754
	if [ -e "$_pbiPatchDir" ] ; then rm -rf "$_pbiPatchDir"; fi
5755
	mkdir -p "$_pbiNewDir"
5756
	mkdir -p "$_pbiOldDir"
5757
	mkdir -p "$_pbiPatchDir"
5758

    
5759
	local _opts="-e --licagree"
5760
	if [ "${PBI_SKIPSIGVERIFY}" = "YES" ] ; then
5761
		_opts="${_opts} --no-checksig"
5762
	fi
5763

    
5764
	# Extract the two PBIs
5765
	echo "Extracting PBI: $_pbiNew"
5766
	pbi_add ${_opts} -o "${_pbiNewDir}" "${_pbiNew}" >/dev/null 2>/dev/null
5767
	echo "Extracting PBI: $_pbiOld"
5768
	pbi_add ${_opts} -o "${_pbiOldDir}" "${_pbiOld}" >/dev/null 2>/dev/null
5769

    
5770
	if [ ! -d "${_pbiNewDir}/${_pbiNewPrefix}" -o ! -d "${_pbiOldDir}/${_pbiOldPrefix}" ] ; then 
5771
		exit_err "Failed Extracting PBIs for comparision!"
5772
	fi
5773

    
5774
	# Get a list of files which are removed in the new PBI vs the old
5775
	gen_rem_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
5776
	_rFileList="$VAL"
5777
	if [ -n "$_rFileList" ] ; then
5778
		echo "Saving removed file list..."
5779
		mv "${_rFileList}" ${_pbiPatchDir}/PBI-rmList
5780
	fi
5781

    
5782
	# Get archive of files/dirs which are new to the PBI
5783
	gen_newfile_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
5784
	_nFileList="$VAL"
5785
	if [ -n "$_nFileList" ] ; then
5786
		echo "Saving new files archive..."
5787
		tar cvf "$_pbiPatchDir/PBI-newFiles.tar" \
5788
			-C "$_pbiNewDir/$_pbiNewPrefix" -T "$_nFileList" >/dev/null 2>/dev/null
5789
		rm "$_nFileList"
5790
	fi
5791

    
5792
	# Get a listing of permissions
5793
	gen_chmod_list "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix"
5794
	_cFileList="$VAL"
5795
	if [ -n "$_cFileList" ] ; then
5796
		echo "Saving permissions list..."
5797
		mv "${_cFileList}" ${_pbiPatchDir}/PBI-permList
5798
	fi
5799

    
5800
	# Generate diffs of files which have changed between the two
5801
	gen_bsdiffs_dirs "$_pbiNewDir/$_pbiNewPrefix" "$_pbiOldDir/$_pbiOldPrefix" "$_pbiPatchDir"
5802

    
5803
	# Make the file archive
5804
	if test_tar_lzma ; then _tcmp="J" ; else _tcmp="j" ; fi
5805
	echo "Creating compressed archive..."
5806
	tar cv${_tcmp}f "${_pbiPatchArchiveFile}" -C ${_pbiPatchDir} . 2>/dev/null 
5807

    
5808
	# Make the header file
5809
	if [ -e "$_pbiPatchHeaderDir" ] ; then rm -rf "$_pbiPatchHeaderDir"; fi
5810
	mkdir -p "$_pbiPatchHeaderDir"
5811
	open_header_tmp "${PBI_TMPDIR}"
5812
  	cp ${PBI_HEADER_TMPDIR}/* "$_pbiPatchHeaderDir/"
5813

    
5814
	# Save the mdate of the old PBI
5815
	echo "$_pbiOldMDate" > $_pbiPatchHeaderDir/pbi_patchmdate
5816

    
5817
	# Remove any signatures
5818
  	rm $_pbiPatchHeaderDir/*.sha1 >/dev/null 2>/dev/null
5819

    
5820
	# Get the archive checksum
5821
	sha256 -q "${_pbiPatchArchiveFile}" > "${_pbiPatchHeaderDir}/pbi_archivesum"
5822
	
5823
	# Set the tag that this is a patch file
5824
	echo "${_pbiOldVer}:${_pbiNewVer}" > "${_pbiPatchHeaderDir}/pbi_patchfile"
5825
	
5826
	# Sign the files if necessary
5827
	sign_pbi_files "${_pbiPatchHeaderDir}"
5828

    
5829
	# Make the header tmpfile
5830
	tar cvjf "${_pbiPatchHeaderFile}" -C ${_pbiPatchHeaderDir} . 2>/dev/null 
5831
	if [ "$?" != "0" ] ; then
5832
		echo "Warning: TAR returned error creating header archive!"
5833
	fi
5834
	rm -rf ${_pbiPatchHeaderDir} 
5835
	
5836
	# Make the pbp file
5837
	get_progname_from_pbi_file "$_pbiNew"
5838
        _pbilow="`echo ${VAL} | tr '[:upper:]' '[:lower:]' | sed 's| ||g'`"
5839
        
5840
        outfile="${_cDir}/${_pbilow}-${_pbiOldVer}_to_${_pbiNewVer}-`uname -m`.pbp"
5841
        mark1="${_cDir}/.pbimark1.$$"
5842
        mark2="${_cDir}/.pbimark2.$$"
5843
        
5844
        echo "
5845
${PBI_SS_ICON}" >$mark1
5846
        echo "
5847
${PBI_SS_ARCHIVE}" >$mark2
5848
                
5849
        # DO IT, DO IT NOW!!!
5850
        cat ${_pbiPatchHeaderFile} $mark1 ${PBI_PATCH_ICON} $mark2 ${_pbiPatchArchiveFile} > ${outfile}
5851
        sha256 -q ${outfile} > ${outfile}.sha256
5852

    
5853
	# Cleanup the archive stuff
5854
        rm $mark1
5855
        rm $mark2
5856
        rm ${_pbiPatchHeaderFile}
5857
        rm ${_pbiPatchArchiveFile}
5858
	
5859
	# Cleanup the directories
5860
	rm_pbipatchfiles
5861

    
5862
	# Do some smell testing, make sure the patch file isn't larger than the PBI itself
5863
	# This happens with some java programs occasionally
5864
	if [ `du -k ${outfile} | awk '{print $1}'` -gt `du -k ${_pbiNew} | awk '{print $1}'` ]; then
5865
		rm ${outfile}
5866
		rm ${outfile}.sha256
5867
		exit_err "The patch is larger than the new PBI, aborting!"
5868
	else
5869
		# We have a patch!
5870
           	echo "Created PBP: ${outfile}"
5871
	fi
5872

    
5873

    
5874
}
5875

    
5876
# Function which compares two directories, and returns a list of chmod commands to get them in line
5877
gen_chmod_list() {
5878

    
5879
	_chList="${PBI_TMPDIR}/.pbi.chList.$$"
5880
	if [ -e "$_chList" ] ; then rm "$_chList" ; fi
5881

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

    
5884
	echo "Getting permissions of changed files..."
5885

    
5886
	while read line
5887
	do
5888
		# Make sure this file exists in the new / old dirs
5889
		if [ -z "$line" ] ; then continue ; fi
5890
		if [ ! -f "${1}/$line" ] ; then continue ; fi
5891
		if [ ! -e "${2}/$line" ] ; then continue ; fi
5892

    
5893
		# Filter out any special files, we don't need diffs of them
5894
		if [ -L "${1}/$line" ] ; then continue ; fi
5895
		if [ -p "${1}/$line" ] ; then continue ; fi
5896
		if [ -S "${1}/$line" ] ; then continue ; fi
5897
		if [ -d "${1}/$line" ] ; then continue ; fi
5898
		if [ -b "${1}/$line" ] ; then continue ; fi
5899
		if [ -c "${1}/$line" ] ; then continue ; fi
5900

    
5901
		_newPerm=`stat -f %Op "${1}/$line"  | cut -c 3-6`
5902
		_oldPerm=`stat -f %Op "${1}/$line"  | cut -c 3-6`
5903
		if [ "$_newPerm" != "$_oldPerm" ] ; then
5904
			# We have new permissions! Lets be sure to save them
5905
			echo "chmod $_newPerm $line" >> $_chList
5906
		fi
5907

    
5908
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
5909

    
5910
	# Remove the tmp list files
5911
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
5912

    
5913
	if [ -e "$_chList" ] ; then
5914
		VAL="$_chList"
5915
	else
5916
		VAL=""
5917
	fi
5918
}
5919

    
5920

    
5921

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

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

    
5927
	echo "Getting bsdiffs of changed files..."
5928

    
5929
	while read line
5930
	do
5931
		# Make sure this file exists in the new / old dirs
5932
		if [ -z "$line" ] ; then continue ; fi
5933
		if [ ! -f "${1}/$line" ] ; then continue ; fi
5934
		if [ ! -e "${2}/$line" ] ; then continue ; fi
5935

    
5936
		# Filter out any special files, we don't need diffs of them
5937
		if [ -L "${1}/$line" ] ; then continue ; fi
5938
		if [ -p "${1}/$line" ] ; then continue ; fi
5939
		if [ -S "${1}/$line" ] ; then continue ; fi
5940
		if [ -d "${1}/$line" ] ; then continue ; fi
5941
		if [ -b "${1}/$line" ] ; then continue ; fi
5942
		if [ -c "${1}/$line" ] ; then continue ; fi
5943

    
5944
		# Check sha256 of each file, see if we have differences
5945
		sha1="`sha256 -q ${1}/${line}`" 
5946
		sha2="`sha256 -q ${2}/${line}`"
5947
		if [ "$sha1" != "$sha2" ] ; then
5948
			# These files differ, get a binary patch made of them
5949
			_tDir="${3}/`dirname $line`"
5950
			_bName=`basename $line`
5951
			if [ ! -d "$_tDir" ] ; then mkdir -p "$_tDir" ; fi
5952
			
5953
			bsdiff "${2}/${line}" "${1}/${line}" "${_tDir}/${_bName}.bsdiff"
5954
			if [ "$?" != "0" ] ; then
5955
				exit_err "Failed creating bsdiff patch for $line"
5956
			fi
5957

    
5958
			# Save the sha256 of the file to be modified
5959
			sha256 -q "${2}/${line}" > "${_tDir}/${_bName}.sha256"
5960
		fi
5961

    
5962
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
5963

    
5964
	# Remove the tmp list files
5965
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
5966
}
5967

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

    
5971
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
5972
	find ${2} | sed "s|^${2}/||g" | sed "s|^${2}||g" >${PBI_TMPDIR}/.pbi.oDir.$$
5973

    
5974
	echo "Finding removed files..."
5975

    
5976
	_rmList="${PBI_TMPDIR}/.pbi.rmList.$$"
5977
	if [ -e "$_rmList" ] ; then rm "$_rmList" ; fi
5978

    
5979
	while read line
5980
	do
5981
		if [ -z "$line" ] ; then continue ; fi
5982
		grep "^$line" ${PBI_TMPDIR}/.pbi.nDir.$$ >/dev/null 2>/dev/null
5983
		if [ "$?" != "0" ] ; then
5984
			#echo "Removed File: $line"
5985
			echo "$line" >> ${_rmList}
5986
		fi
5987

    
5988
	done < ${PBI_TMPDIR}/.pbi.oDir.$$
5989

    
5990
	# Remove the tmp list files
5991
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
5992
	rm ${PBI_TMPDIR}/.pbi.oDir.$$
5993

    
5994
	if [ -e "$_rmList" ] ; then
5995
		VAL="$_rmList"
5996
	else
5997
		VAL=""
5998
	fi
5999
}
6000

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

    
6004
	find ${1} | sed "s|^${1}/||g" | sed "s|^${1}||g" >${PBI_TMPDIR}/.pbi.nDir.$$
6005
	echo "Finding new files..."
6006

    
6007
	_addList="${PBI_TMPDIR}/.pbi.addList.$$"
6008
	if [ -e "$_addList" ] ; then rm "$_addList" ; fi
6009

    
6010
	while read line
6011
	do
6012
		# Search for all new files + symlinks to include in tarball
6013
		if [ -z "$line" ] ; then continue ; fi
6014
		if [ ! -e "${2}/$line" -o -L "${1}/$line" ] ; then
6015
			#echo "New File: $line"
6016
			echo "./$line" >> ${_addList}
6017
		fi
6018

    
6019
	done < ${PBI_TMPDIR}/.pbi.nDir.$$
6020

    
6021
	# Remove the tmp list files
6022
	rm ${PBI_TMPDIR}/.pbi.nDir.$$
6023

    
6024
	if [ -e "$_addList" ] ; then
6025
		VAL="$_addList"
6026
	else
6027
		VAL=""
6028
	fi
6029
}
6030

    
6031
# Read the version from a PBI file
6032
get_ver_from_pbi_file() 
6033
{
6034
	VAL="`pbi_add -i $1 | grep Version: | cut -d ':' -f 2 | tr -d ' '`"
6035
	export VAL
6036
}
6037

    
6038
# Read the version from a PBI file
6039
get_progname_from_pbi_file() 
6040
{
6041
	VAL="`pbi_add -i $1 | grep Name: | cut -d ':' -f 2 | tr -d ' '`"
6042
	export VAL
6043
}
6044

    
6045
get_prefix_from_pbi_file()
6046
{
6047
	VAL="`pbi_add -i $1 | grep Prefix: | cut -d ':' -f 2 | tr -d ' '`"
6048
	export VAL
6049
}
6050

    
6051
get_mdate_from_pbi_file()
6052
{
6053
	VAL="`pbi_add -i $1 | grep Built: | cut -d ' ' -f 2-5 | tr -s ' '`"
6054
	export VAL
6055
}
6056

    
6057
# Move old PBIs to the archive
6058
archive_old_pbis()
6059
{
6060
	local _od="$1"
6061
	local _keepnum="$2"
6062

    
6063
	# Make sure the archived dir exists
6064
	if [ ! -d "${_od}/archived" ] ; then mkdir "${_od}/archived"; fi
6065

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

    
6070
	echo "Moving old PBIs from ${_od}/*.pbi -> ${_od}/archived/"
6071
	mv ${_od}/*.pbi ${_od}/archived/ 2>/dev/null
6072
	mv ${_od}/*.sha256 ${_od}/archived/ 2>/dev/null
6073

    
6074
	# Prune anything beyond the _keepnum
6075
        echo "Checking for more than $_keepnum PBIs in archive"
6076
	oCount="1"
6077
	for oFile in `ls -t ${_od}/archived/*.pbi 2>/dev/null`
6078
	do
6079
		if [ -z "$oFile" ] ; then continue ; fi
6080
		if [ "$oCount" -gt "$_keepnum" ] ; then
6081
			echo "Removing old PBI ${oFile} from archive"
6082
			rm ${oFile}*
6083
		fi
6084
		oCount=`expr $oCount + 1`	
6085
	done
6086
}
6087

    
6088
# Check if we need to do an auto-build of the target PBI
6089
check_ab_needed() {
6090
	_port="$1"
6091
	_bk="$2"
6092
	_cd="$3"
6093
	local _abkey="$4"
6094

    
6095
        unset PBI_PROGVERSION
6096
	get_pbi_progversion
6097

    
6098
	# Check PBI_BUILDKEY, see if we have a manual rebuild triggered
6099
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/pbi-buildkey" ] ; then
6100
		if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-buildkey`" != "$_bk" \
6101
			 -a -n "${_bk}" ]
6102
        	then echo "BUILDKEY bump, rebuild triggered." ; return 0 ; fi
6103
	fi
6104

    
6105
	# Make sure this PBI hasn't already failed during this run
6106
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/.abkey" ] ; then
6107
	  if [ "`cat ${PBI_AB_OUTDIR}/${_cd}/.abkey`" = "$_abkey" ] ; then
6108
	    return 1
6109
  	  fi
6110
	fi
6111

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

    
6114
	# Check if this is a failed port we should be skipping until its fixed
6115
	if [ -e "${PBI_AB_OUTDIR}/${_cd}/.failed-csum" ] ; then
6116
		_fcsum="`cat ${PBI_AB_OUTDIR}/${_cd}/.failed-csum`"
6117
		_ncsum="`tar cvf - -C "${PORTSDIR}/${_port}" . 2>/dev/null | md5 -q`"
6118
		if [ "$_fcsum" != "$_ncsum" ] ; then
6119
			return 1
6120
		fi
6121
 	fi	
6122

    
6123
	# See if we have an existing PBI
6124
	ls ${PBI_AB_OUTDIR}/${_cd}/*.pbi >/dev/null 2>/dev/null
6125
	if [ "${?}" != "0" ]; then 
6126
	  #echo "No existing PBI"
6127
          return 0 
6128
        fi
6129

    
6130
	# See if we have a saved version
6131
	if [ ! -e "${PBI_AB_OUTDIR}/${_cd}/pbi-version" ]; then 
6132
		#echo "No saved pbi-version"
6133
		return 0
6134
	fi
6135

    
6136
	# See if the version is different now
6137
	oldVersion=`cat ${PBI_AB_OUTDIR}/${_cd}/pbi-version`
6138
	if [ "$oldVersion" != "$PBI_PROGVERSION" ]; then 
6139
		echo "$_port version bump: $oldVersion -> $PBI_PROGVERSION"
6140
		return 0
6141
	fi
6142

    
6143
	return 1
6144
}
6145

    
6146
# start processing for make port / pbi compile
6147
pbi_make_init() {
6148

    
6149
  	require_root
6150

    
6151
  	parse_make_pbi_cmdline "$@"
6152
 
6153
  	do_pbi_make "$@"
6154
}
6155

    
6156
do_pbi_make() {
6157

    
6158
  	# Load the PBI settings
6159
	get_pbi_progversion
6160
	get_pbi_progname
6161
  	get_pbi_progdir
6162

    
6163
	# Check if this is being called from within chroot or outside
6164
	if [ "`basename $0`" = "pbi_makeport" ] ; then
6165
		# Extract the chroot 
6166
		chroot_extract
6167

    
6168
		# Now re-run pbi_makeport in chroot environment
6169
		chroot "${PBI_CHROOTDIR}" "/usr/local/sbin/pbi_makeport_chroot" "$@"
6170
		_err=$?
6171
		if [ "$_err" = "0" -a "${PBI_BUILDONLY}" != "YES" ] ; then
6172
			mv ${PBI_CHROOTDIR}/pbiout/*.pbi ${PBI_CREATE_OUTDIR}/ 
6173
			mv ${PBI_CHROOTDIR}/pbiout/*.sha256 ${PBI_CREATE_OUTDIR}/
6174
		fi
6175

    
6176
  		# Break here if we are only doing a build
6177
		if [ "${PBI_BUILDONLY}" = "YES" ] ; then exit_trap; fi
6178

    
6179
		# Lets cleanup the chroot environment
6180
		chroot_make_cleanup
6181
		rm_tmpdir
6182

    
6183
		exit $_err
6184
	fi
6185

    
6186
	if [ "`basename $0`" != "pbi_makeport_chroot" ] ; then return ; fi
6187
	
6188

    
6189
  	# Check if we have some specific make options to use
6190
  	load_pbi_conffile
6191

    
6192
  	# init tmpdir
6193
  	init_tmpdir
6194

    
6195
  	set_make_options
6196

    
6197
  	# See if we need to run a pre make script
6198
  	run_pbi_preportmake
6199

    
6200
  	# Start our build
6201
  	start_pbi_mkportbefore
6202
  	start_prebuild_script
6203
  	start_pbi_makeport
6204
  	start_postbuild_script
6205
  	start_pbi_mkportafter
6206

    
6207
  	# Prune any proto / build specific ports
6208
  	start_pbi_prune_ports
6209

    
6210
  	# See if we need to run a post make script
6211
  	run_pbi_postportmake
6212

    
6213
	# Check for any users / groups we need to save for install time
6214
	mk_pbi_users_file
6215
	mk_pbi_groups_file
6216

    
6217
	# Auto-generate a external_links directive from plist info
6218
	mk_auto_ext_linksfile
6219

    
6220
	# Check if we created a linux app, and need to copy files for it
6221
	auto_copy_linuxbase
6222

    
6223
  	# Break here if we are only doing a build
6224
	if [ "${PBI_BUILDONLY}" = "YES" ] ; then exit_trap; fi
6225

    
6226
	# Start creation of PBI
6227
	do_pbi_create
6228

    
6229
	# Got this far, lets exit with success
6230
	rm_buildfiles
6231
	rm_tmpdir
6232
	exit 0
6233
}
6234

    
6235
# Check if we need to save a list of GROUPS to create at install
6236
mk_pbi_groups_file()
6237
{
6238
	if [ -z "$PBI_BUILD_GROUPS" ] ; then return ; fi
6239

    
6240
	for group in $PBI_BUILD_GROUPS
6241
	do
6242
		# Check /usr/ports/GIDs for group entry
6243
		gidLine=`cat /usr/ports/GIDs | grep "^$group:"`
6244
		if [ -z "$gidLine" ] ; then
6245
			echo "Warning: No entry for \"$group\" in GIDs file..."
6246
			continue
6247
		fi
6248
		grep -q "^$group:" ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE} 2>/dev/null
6249
		if [ $? -ne 0 ] ; then
6250
			echo "Saving gid details for group: $group"
6251
			echo "$gidLine" >> ${PBI_PROGDIRPATH}/${PBI_INS_GROUPSFILE}
6252
		fi
6253
	done
6254
}
6255

    
6256
# Check if we need to save a list of users to create at install
6257
mk_pbi_users_file()
6258
{
6259
	if [ -z "$PBI_BUILD_USERS" ] ; then return ; fi
6260

    
6261
	for user in $PBI_BUILD_USERS
6262
	do
6263
		# Check /usr/ports/UIDs for user entry
6264
		uidLine=`cat /usr/ports/UIDs | grep "^$user:"`
6265
		if [ -z "$uidLine" ] ; then
6266
			echo "Warning: No entry for \"$user\" in UIDs file..."
6267
			continue
6268
		fi
6269
		grep -q "^$user:" ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE} 2>/dev/null
6270
		if [ $? -ne 0 ] ; then
6271
			echo "Saving uid details for user: $user"
6272
			echo "$uidLine" >> ${PBI_PROGDIRPATH}/${PBI_INS_USERSFILE}
6273
		fi
6274
	done
6275
}
6276

    
6277
# Source any pre-build script to allow a custom script to modify the port
6278
start_prebuild_script()
6279
{
6280
	if [ -e "/pre-build.sh" ] ; then
6281
		chmod 755 /pre-build.sh
6282
		# Source the script
6283
		. /pre-build.sh
6284
	fi
6285
}
6286

    
6287
# Source any post-build script to allow a custom script to modify the port
6288
start_postbuild_script()
6289
{
6290
	if [ -e "/post-build.sh" ] ; then
6291
		chmod 755 /post-build.sh
6292
		# Source the script
6293
		. /post-build.sh
6294
	fi
6295
}
6296

    
6297
# Check if we created any linux stuff, and copy it into the correct PREFIX
6298
auto_copy_linuxbase()
6299
{
6300
	echo "Checking for Linux libraries to copy..."
6301
	if [ -d "/compat/linux/usr/lib" ] ; then
6302
		mkdir ${PBI_PROGDIRPATH}/linuxlib
6303
		echo "Copying /compat/linux/lib -> ${PBI_PROGDIRPATH}/linuxlib"
6304
		tar cvf - -C /compat/linux/lib . 2>/dev/null | \
6305
		tar xvf - -C ${PBI_PROGDIRPATH}/linuxlib 2>/dev/null
6306
		echo "Copying /compat/linux/usr/lib -> ${PBI_PROGDIRPATH}/linuxlib"
6307
		tar cvf - -C /compat/linux/usr/lib . 2>/dev/null | \
6308
		tar xvf - -C ${PBI_PROGDIRPATH}/linuxlib 2>/dev/null
6309
	fi
6310
}
6311

    
6312
# Clean the chroot environment
6313
chroot_make_cleanup() {
6314
	[ -z "${PBI_CHROOTDIR}" ] && return
6315
	[ -d "${PBI_CHROOTDIR}" ] || return
6316
	[ "${PBI_CHROOTDIR}" = "/" ] && return
6317
	
6318
	# Unmount /dev if mounted
6319
	echo "Cleaning $PBI_CHROOTDIR"
6320
	umount -f ${PBI_CHROOTDIR}/dev >/dev/null 2>/dev/null
6321
	umount -f ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
6322
	umount -f ${PBI_CHROOTDIR}/usr/ports >/dev/null 2>/dev/null
6323
	umount -f ${PBI_CHROOTDIR}/tmpfs >/dev/null 2>/dev/null
6324
	umount -f ${PBI_CHROOTDIR}/pkgs >/dev/null 2>/dev/null
6325
	umount -f ${PBI_CHROOTDIR}/.ccache >/dev/null 2>/dev/null
6326

    
6327
	if [ "${PBI_KEEPBUILDFILES}" = "YES" ] ; then return ; fi
6328
	rm -rf "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
6329
	chflags -R noschg ${PBI_CHROOTDIR} >/dev/null 2>/dev/null
6330
	rm -rf "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
6331
}
6332

    
6333
# Function which extracts the clean chroot environment for the PBI
6334
chroot_extract() {
6335

    
6336
	# If no chroot file exists, make it first
6337
	[ -e "${PBI_CHROOTFILE}" ] || mk_chroot_file
6338

    
6339
	# Set the chroot path
6340
	PBI_CHROOTDIR="${PBI_PROGDIRPATH}.chroot"
6341
	export PBI_CHROOTDIR
6342
	
6343
	# See if there is old chroot to clean first
6344
	chroot_make_cleanup
6345

    
6346
	mkdir -p "${PBI_CHROOTDIR}"
6347
	echo "Extracting chroot environment..."
6348
	tar xvf ${PBI_CHROOTFILE} -C "${PBI_CHROOTDIR}" >/dev/null 2>/dev/null
6349
	[ $? -ne 0 ] && exit_err "Failed extracting chroot environment!"
6350

    
6351
	# Copy resolv.conf
6352
	cp /etc/resolv.conf ${PBI_CHROOTDIR}/etc/resolv.conf
6353

    
6354
	# Copy our binary wrapper
6355
	mkdir ${PBI_CHROOTDIR}${PBI_APPDIR}
6356
	cp ${PBI_WRAPPERFILE} ${PBI_CHROOTDIR}${PBI_WRAPPERFILE}
6357

    
6358
	# If we have a custom PBI_MAKECONF include it
6359
	[ -e "${PBI_MAKECONF}" ] && cp ${PBI_MAKECONF} ${PBI_CHROOTDIR}/etc/make.conf
6360

    
6361
	#echo "Copying ${PORTSDIR} -> ${PBI_CHROOTDIR}/usr/ports"
6362
	#tar cvf - -C "${PORTSDIR}" --exclude ./distfiles . 2>/dev/null | tar xvf - -C "${PBI_CHROOTDIR}/usr/ports" 2>/dev/null
6363
	[ -d "${PORTSDIR}/distfiles" ] || mkdir -p ${PORTSDIR}/distfiles
6364
	mkdir -p ${PBI_CHROOTDIR}/usr/ports
6365
	mount_nullfs ${PORTSDIR} ${PBI_CHROOTDIR}/usr/ports
6366

    
6367
	# Using tmpfs?
6368
	if [ "$MKTMPFS" = "YES" ] ; then 
6369
		mkdir ${PBI_CHROOTDIR}/tmpfs
6370
		mount -t tmpfs tmpfs ${PBI_CHROOTDIR}/tmpfs
6371
	fi
6372

    
6373
	# Are we doing pkg caching?
6374
	if [ "$PBI_PKGCACHE" = "YES" ] ; then
6375
		mkdir ${PBI_CHROOTDIR}/pkgs
6376
		mount_nullfs ${PBI_PKGCACHEDIR} ${PBI_CHROOTDIR}/pkgs
6377
	fi
6378
	
6379
	# Now copy over the pbi_* scripts
6380
	mkdir ${PBI_CHROOTDIR}/usr/local/sbin
6381
	cp ${PROGBASE}/sbin/pbi_* ${PBI_CHROOTDIR}/usr/local/sbin
6382
	cp ${PBI_CHROOTDIR}/usr/local/sbin/pbi_makeport ${PBI_CHROOTDIR}/usr/local/sbin/pbi_makeport_chroot
6383
	chmod 755 ${PBI_CHROOTDIR}/usr/local/sbin/pbi_*
6384

    
6385
	# Copy the default icons
6386
	cp ${PBI_DEFAULT_ICON} ${PBI_CHROOTDIR}${PBI_DEFAULT_ICON_CHROOT}
6387

    
6388
	# Make sure the outgoing dir is created
6389
	mkdir -p ${PBI_CHROOTDIR}/pbiout
6390

    
6391
	# Copy over the PBI DB
6392
	mkdir -p ${PBI_CHROOTDIR}/var/db
6393
	cp -r ${PBI_DBDIR} ${PBI_CHROOTDIR}${PBI_DBDIR}
6394
	
6395
	# Copy over the confdir as well
6396
	if [ -n "${PBI_CONFDIR}" ] ; then
6397
		mkdir -p "${PBI_CHROOTDIR}/pbimodule"
6398
		echo "Copying ${PBI_CONFDIR} -> ${PBI_CHROOTDIR}/pbimodule"
6399
	 	tar cvf - -C "${PBI_CONFDIR}" . 2>/dev/null | tar xvf - -C "${PBI_CHROOTDIR}/pbimodule" 2>/dev/null
6400
	fi
6401

    
6402
	# Copy over the ssl priv key if used
6403
	if [ -n "$PBI_SSLPRIVKEY" ] ; then
6404
	 	cp "${PBI_SSLPRIVKEY}" "${PBI_CHROOTDIR}/privkey.pem"
6405
		chmod 600 "${PBI_CHROOTDIR}/privkey.pem"
6406
	fi
6407

    
6408
	# Check if we have a pre-make script to run
6409
	if [ -n "${PBI_PREMAKE_SCRIPT}" ] ; then
6410
		if [ -e "${PBI_PREMAKE_SCRIPT}" ] ; then
6411
			cp ${PBI_PREMAKE_SCRIPT} ${PBI_CHROOTDIR}/pre-build.sh
6412
		fi
6413
	fi
6414
	# Check if we have a post-make script to run
6415
	if [ -n "${PBI_POSTMAKE_SCRIPT}" ] ; then
6416
		if [ -e "${PBI_POSTMAKE_SCRIPT}" ] ; then
6417
			cp ${PBI_POSTMAKE_SCRIPT} ${PBI_CHROOTDIR}/post-build.sh
6418
		fi
6419
	fi
6420

    
6421
	# Start devfs in the chroot
6422
	if [ ! -d "${PBI_CHROOTDIR}/dev" ] ; then
6423
		mkdir ${PBI_CHROOTDIR}/dev
6424
	fi
6425
	mount -t devfs devfs ${PBI_CHROOTDIR}/dev
6426

    
6427
	# Mount linprocfs
6428
	mkdir -p ${PBI_CHROOTDIR}/compat/linux/proc >/dev/null 2>/dev/null
6429
	mount -t linprocfs linprocfs ${PBI_CHROOTDIR}/compat/linux/proc
6430

    
6431
	# Make sure the outgoing dir exists
6432
	mkdir -p ${PBI_CHROOTDIR}${PBI_CREATE_OUTDIR} >/dev/null 2>/dev/null
6433

    
6434
	# Check for ccache being enabled on the host and nullfs mount it to the chroot
6435
	if [ -n "${CCACHE_DIR}" -a -d "${CCACHE_DIR}" ] ; then
6436
		mkdir ${PBI_CHROOTDIR}/.ccache
6437
		mount_nullfs ${CCACHE_DIR} ${PBI_CHROOTDIR}/.ccache	
6438
	fi
6439

    
6440
}
6441

    
6442
# No chroot environment tar file exists yet, lets build or extract
6443
mk_chroot_file() {
6444

    
6445
	# Check if on PC-BSD and we can instead fetch fbsd-release.txz
6446
	if [ -e "$PCBSD_ETCCONF" -a -z "$FORCE_FBSD_ONLY" ]; then
6447

    
6448
	  cd "$PBI_APPDIR"
6449

    
6450
	  # Set the mirror URL
6451
  	  MIRRORURL="`sed -n 's/PCBSD_MIRROR: //p' ${PCBSD_ETCCONF}`"
6452

    
6453
  	  # Get the system version we are checking for updates to
6454
  	  SYSVER="`pbreg get /PC-BSD/Version`" ; export SYSVER
6455

    
6456
  	  # Set the system arch type
6457
  	  ARCH=`uname -m`
6458
	  if [ -n "${PBI_OSARCH}" ] ; then
6459
	  	ARCH="${PBI_OSARCH}"
6460
	  fi
6461

    
6462
  	  # To fetch the jail environment
6463
 	  echo "Fetching FreeBSD chroot environment... This may take a while..."
6464
  	  fetch -o rel.txz ${MIRRORURL}/${SYSVER}/${ARCH}/netinstall/fbsd-release.txz
6465
    	  fetch -o rel.md5 ${MIRRORURL}/${SYSVER}/${ARCH}/netinstall/fbsd-release.txz.md5
6466

    
6467
    	  [ `md5 -q rel.txz` != `cat rel.md5` ] && exit_err "Error in download data, checksum mismatch.. Please try again later."
6468

    
6469
	  mv rel.txz ${PBI_CHROOTFILE}
6470
	  rm rel.md5
6471
	  return
6472
 	fi
6473

    
6474
        local _srcdir="/usr/src"
6475
        if [ -z "${PBI_BUILDSRC}" ] ; then
6476
                PBI_BUILDSRC="${_srcdir}"
6477
        fi
6478

    
6479
        local _targetDir="${PBI_APPDIR}/.worldTarget.$$"
6480
        if [ -z "${PBI_BUILDTARGET}" ] ; then
6481
                PBI_BUILDTARGET="${_targetDir}"
6482
        fi
6483

    
6484
        # Delete source code/build if not /usr/src and PBI_DELETE_BUILD is true
6485
        if [ -z "${PBI_DELETE_BUILD}" ] ; then
6486
                PBI_DELETE_BUILD=1
6487
        fi
6488
 
6489
	# Use existing sources
6490
        if [ -e "${PBI_BUILDSRC}/COPYRIGHT" -a -z "${PBI_OSREL}" ] ; then
6491
		PBI_BUILDLOG="${PBI_APPDIR}/.buildWorldLog"
6492
		: > ${PBI_BUILDLOG}
6493
		mkdir -p "${PBI_BUILDTARGET}"
6494
	
6495
	else
6496
		# Make sure SVN is installed
6497
		which svn >/dev/null 2>/dev/null
6498
		[ "$?" -ne 0 ] && exit_err "Subversion is required to rebuild the chroot environment!"
6499

    
6500
                local _osRel=`uname -r`
6501
                if [ -n "${PBI_OSREL}" ]; then
6502
                        _osRel="${PBI_OSREL}"
6503
                fi
6504

    
6505
		echo "Building the PBI chroot environment... This may take a while..."
6506
		PBI_BUILDLOG="${PBI_APPDIR}/.buildWorldLog"
6507
		echo "" > ${PBI_BUILDLOG}
6508
		mkdir -p "${PBI_BUILDSRC}"
6509
		mkdir -p "${PBI_BUILDTARGET}"
6510
	
6511
		# Figure out which version of FreeBSD to checkout
6512
		case $_osRel in
6513
			*RELEASE)
6514
				local _osMajor=${_osRel%%.*}
6515
				local svnUrl="svn://svn.freebsd.org/base/releng/${_osMajor}.0"
6516
				echo "Using $svnUrl for sources"
6517
				;;
6518
			*CURRENT)
6519
				local svnUrl="svn://svn.freebsd.org/base/head"
6520
				echo "Using $svnUrl for sources"
6521
				;;
6522
			*STABLE)
6523
				local _osMajor=${_osRel%%.*}
6524
				local svnUrl="svn://svn.freebsd.org/base/stable/${_osMajor}"
6525
				"Using $svnUrl for sources"
6526
				;;
6527
			*)
6528
				local svnUrl="svn://svn.freebsd.org/base/head"
6529
				echo "Using $svnUrl for sources"
6530
				echo "Assuming a BETA|RC or rarely used FreeBSD version. Using CURRENT!"
6531
				;;
6532
		esac
6533

    
6534
		echo "Checking out FreeBSD sources from $svnUrl"
6535
                if [ -e "${PBI_BUILDSRC}/COPYRIGHT" ] ; then
6536
                        svn update ${PBI_BUILDSRC} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
6537
                else
6538
                        svn co ${svnUrl} ${PBI_BUILDSRC} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
6539
                fi
6540

    
6541
                if [ "$?" != "0" ] ; then
6542
                        if [ "${PBI_DELETE_BUILD}" = "1" ] ; then
6543
                                rm -rf "${PBI_BUILDSRC}"
6544
                                rm -rf "${PBI_BUILDTARGET}"
6545
                        fi
6546
			exit_err "Subversion checkout failed! Logfile saved: ${PBI_BUILDLOG}"
6547
		fi
6548
	fi # End of subversion checkout
6549

    
6550
	echo "Running buildworld / installworld"
6551
	touch ${PBI_BUILDSRC}/Makefile
6552
	cd ${PBI_BUILDSRC}
6553
        make ${PBI_BUILDFLAGS} buildworld >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
6554
        if [ "$?" != "0" ] ; then
6555
                cd
6556
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
6557
                        rm -rf "${PBI_BUILDSRC}"
6558
                        rm -rf "${PBI_BUILDTARGET}"
6559
                fi
6560
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
6561
        fi
6562
        make ${PBI_BUILDFLAGS} installworld DESTDIR=${PBI_BUILDTARGET} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
6563
        if [ "$?" != "0" ] ; then
6564
                cd
6565
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
6566
                        rm -rf "${PBI_BUILDSRC}"
6567
                        rm -rf "${PBI_BUILDTARGET}"
6568
                fi
6569
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
6570
        fi
6571
        make ${PBI_BUILDFLAGS} distribution DESTDIR=${PBI_BUILDTARGET} >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
6572
        if [ "$?" != "0" ] ; then
6573
                cd
6574
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
6575
                        rm -rf "${PBI_BUILDSRC}"
6576
                        rm -rf "${PBI_BUILDTARGET}"
6577
                fi
6578
                exit_err "Buildworld failed! Logfile saved: ${PBI_BUILDLOG}"
6579
        fi
6580

    
6581
	# Copy the source since some ports need kern sources
6582
	echo "Copying FreeBSD sources to chroot environment"
6583
	mkdir -p ${PBI_BUILDTARGET}/usr/src >/dev/null 2>/dev/null
6584
	tar cvf - -C "${PBI_BUILDSRC}" --exclude "\.svn/" . 2>/dev/null | tar xvf - -C "${PBI_BUILDTARGET}/usr/src" 2>/dev/null
6585

    
6586
	echo "Creating chroot environment tarball"
6587
	tar cvjf ${PBI_CHROOTFILE} -C ${PBI_BUILDTARGET} . >>${PBI_BUILDLOG} 2>>${PBI_BUILDLOG}
6588
	if [ $? -ne 0 ] ; then
6589
		cd
6590
                if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
6591
                        rm -rf "${PBI_BUILDSRC}"
6592
                        rm -rf "${PBI_BUILDTARGET}"
6593
                fi
6594
		rm -rf "${PBI_CHROOTFILE}"
6595
		exit_err "Making chroot environment tarball failed! Logfile saved: ${PBI_BUILDLOG}"
6596
	fi
6597

    
6598
	# Cleanup after ourselves
6599
	chflags -R noschg "${PBI_BUILDTARGET}" >/dev/null 2>/dev/null
6600
        if [ "${PBI_BUILDSRC}" != "/usr/src" -a "${PBI_DELETE_BUILD}" != "0" ] ; then
6601
                rm -rf "${PBI_BUILDSRC}"
6602
        fi
6603
        if [ "${PBI_DELETE_BUILD}" = "1" ] ; then
6604
                rm -rf "${PBI_BUILDTARGET}" >/dev/null 2>/dev/null
6605
        fi
6606
	rm ${PBI_BUILDLOG}
6607
}
6608

    
6609
# Read the target ports plist, and generate a external_links config based upon it
6610
mk_auto_ext_linksfile() {
6611
	# Get ports name
6612
	get_pkgname "${PORTSDIR}/${PBI_MAKEPORT}"
6613
	_pname="${PKGNAME}"
6614

    
6615
 	pkg_info -L ${_pname} | sed "s|^${PBI_PROGDIRPATH}/||g" \
6616
		| grep -v "^Information for" \
6617
		| grep -v "^Files:" \
6618
		| tr -s '\t' ' ' \
6619
		| tr -d ' ' \
6620
		 > "${PBI_TMPDIR}/.pkg_flist.$$"
6621

    
6622
	_ef="${PBI_PROGDIRPATH}/${MOD_AUTOEXTLINKFILE}"
6623

    
6624
	[ -e "$_ef" ] && rm "$_ef"
6625

    
6626
	while read f
6627
	do
6628
		bin="NO"
6629
		[ -z "${f}" ] && continue
6630
		[ -e "${PBI_PROGDIRPATH}/${f}" ] || continue
6631

    
6632
		# See if this is executable and set it as binary
6633
		dirname ${f} | grep -e "bin" -e "sbin" >/dev/null 2>/dev/null
6634
		if [ -x "${PBI_PROGDIRPATH}/${f}" -a $? -eq 0 ] ; then
6635
			echo "${f}	${f}	binary,nocrash" >> "$_ef"
6636
		else
6637
			echo "${f}	${f}	replace" >> "$_ef"
6638
		fi
6639
	done < ${PBI_TMPDIR}/.pkg_flist.$$
6640
	rm "${PBI_TMPDIR}/.pkg_flist.$$"
6641

    
6642
	# Skip the dbus stuff for now causes weird issues with various apps
6643
	return 0
6644

    
6645
	# Now figure out any dbus services we need to make links / wrappers for
6646
 	for _dsd in $DBUS_SEARCH_DIRS
6647
	do
6648
		# Check if we have a valid dbus directory
6649
		[ -d "${PBI_PROGDIRPATH}/${_dsd}" ] || continue
6650

    
6651
		# Make a list of files to include
6652
		find ${PBI_PROGDIRPATH}/${_dsd} -type f | sed "s|${PBI_PROGDIRPATH}/${_dsd}/||g" > ${PBI_TMPDIR}/.dbus.$$
6653
		
6654
		# Add these files to the external links file
6655
		while read _dbfile
6656
		do
6657
			# Get the file extension, only .xml and .service are valid
6658
			case "${_dsd}/${_dbfile}" in
6659
				*.xml) dbext=".xml" ;;
6660
				*.service)
6661
					dbext=".service"
6662

    
6663
					# We have a service file, find the target binary and make sure its added as a wrapper only
6664
					_dbbin="`grep 'Exec' ${PBI_PROGDIRPATH}/${_dsd}/${_dbfile} | cut -d '=' -f 2 | cut -d ' ' -f 1`"
6665
					_dbbin=`echo "$_dbbin" | sed "s|${PBI_PROGDIRPATH}/||g"`
6666
					[ -n "$_dbbin" ] && echo "${_dbbin}		${_dbbin}	binwrapper" >> "$_ef"
6667

    
6668
					# Massage the service file to point to the fakebin wrapper
6669
					rmBaseDir="`dirname ${_dbbin}`"
6670
					sed -i '' "s|${PBI_PROGDIRPATH}/${rmBaseDir}/|${PBI_PROGDIRPATH}/${PBI_FAKEBIN_DIR}/|g" "${PBI_PROGDIRPATH}/${_dsd}/${_dbfile}"
6671
					;;
6672
				*) continue ;;
6673
			esac
6674

    
6675
			echo "${_dsd}/${_dbfile}	${_dsd}/${_dbfile}.${_pname}.${dbext}	replace" >> "$_ef"
6676
		done < ${PBI_TMPDIR}/.dbus.$$
6677
		rm ${PBI_TMPDIR}/.dbus.$$
6678

    
6679
	done	
6680

    
6681
}
6682

    
6683
# Init the crash handler routine
6684
pbi_crash_init() {
6685
	which "pbi-crashhandler-gui" >/dev/null 2>/dev/null
6686
	if [ "$?" = "0" -a -n "${DISPLAY}" ] ; then
6687
		#pbi-crashhandler-gui "$@"
6688
	fi
6689
}
6690

    
6691
# Get the hard-link counter for the specified file
6692
get_hard_link_count() {
6693
	HLINKS=`stat -f %l "${1}"`
6694
}
6695

    
6696
# Cleanup after caught exit
6697
exit_trap() {
6698
	# If a download is running, kill it
6699
	if [ -n  "${FETCH_PID}" ] ; then 
6700
	   echo "Killing ${FETCH_PID}"
6701
	   kill -9 ${FETCH_PID}
6702
	   sleep 1
6703
	   rm ${FETCH_TFILE}
6704
	fi
6705
        chroot_make_cleanup
6706
	rm_tmpdir
6707
	exit 0
6708
}
6709

    
6710
# Read in the global pbi.conf
6711
load_pbi_etcconf() {
6712

    
6713
	# FTP_PASSIVE_MODE needs to be enabled by default
6714
	FTP_PASSIVE_MODE=YES
6715
	export FTP_PASSIVE_MODE
6716

    
6717
	PBI_PUBKEYS="`ls ${PBI_DBKEYDIR}/*.ssl 2>/dev/null`"
6718

    
6719
	[ -e "${PBI_ETCCONF}" ] || return 0
6720

    
6721
	# See if we have a custom index refresh rate
6722
	_ckPBIIR="`sed -n 's/^PBI_INDEXREFRESH: //gp' ${PBI_ETCCONF}`"
6723
	if [ -n "${_ckPBIIR}" -a $(is_num "$_ckPBIIR") ] ; then 
6724
		PBI_INDEXREFRESH="${_ckPBIIR}"
6725
	fi
6726

    
6727
	# See if we have a custom pbid refresh time
6728
	_ckPBID="`cat ${PBI_ETCCONF} | grep '^PBID_REFRESH: ' | sed 's|PBID_REFRESH: ||g'`"
6729
	if [ -n "${_ckPBID}" -a $(is_num "$_ckPBID") ] ; then 
6730
		PBIDSLEEP="${_ckPBID}"
6731
	fi
6732

    
6733
        # Load Proxy Variables
6734
	if [ -z "$PBI_PROXYURL" -a -e "${PBI_ETCCONF}" ] ; then
6735
		PBI_PROXYURL="`sed -n 's/PBI_PROXYURL: //p' ${PBI_ETCCONF}`"
6736
		PBI_PROXYPORT="`sed -n 's/PBI_PROXYPORT: //p' ${PBI_ETCCONF}`"
6737
		PBI_PROXYTYPE="`sed -n 's/PBI_PROXYTYPE: //p' ${PBI_ETCCONF}`"
6738
		PBI_PROXYUSER="`sed -n 's/PBI_PROXYUSER: //p' ${PBI_ETCCONF}`"
6739
		PBI_PROXYPASS="`sed -n 's/PBI_PROXYPASS: //p' ${PBI_ETCCONF}`"
6740
	fi
6741

    
6742
	# If empty proxy config, check if configured for master pcbsd.conf file
6743
	if [ -z "$PBI_PROXYURL" -a -e "${PCBSD_ETCCONF}" ] ; then
6744
		PBI_PROXYURL="`sed -n 's/PCBSD_PROXYURL: //p' ${PCBSD_ETCCONF}`"
6745
		PBI_PROXYPORT="`sed -n 's/PCBSD_PROXYPORT: //p' ${PCBSD_ETCCONF}`"
6746
		PBI_PROXYTYPE="`sed -n 's/PCBSD_PROXYTYPE: //p' ${PCBSD_ETCCONF}`"
6747
		PBI_PROXYUSER="`sed -n 's/PCBSD_PROXYUSER: //p' ${PCBSD_ETCCONF}`"
6748
		PBI_PROXYPASS="`sed -n 's/PCBSD_PROXYPASS: //p' ${PCBSD_ETCCONF}`"
6749
	fi
6750

    
6751

    
6752
        # Create the PROXY variables based upon proxy information supplied
6753
	if [ -n "$PBI_PROXYURL" ] ; then
6754
		if [ -n "$PBI_PROXYPORT" ] ; then
6755
			HTTP_PROXY="${PBI_PROXYURL}:${PBI_PROXYPORT}"
6756
			FTP_PROXY="${PBI_PROXYURL}:${PBI_PROXYPORT}"
6757
			export HTTP_PROXY FTP_PROXY
6758
		else
6759
			HTTP_PROXY="${PBI_PROXYURL}"
6760
			FTP_PROXY="${PBI_PROXYURL}"
6761
			export HTTP_PROXY FTP_PROXY
6762
		fi
6763
		if [ -n "$PBI_PROXYUSER" ] ; then
6764
			if [ -n "$PBI_PROXYPASS" ] ; then
6765
				HTTP_PROXY_AUTH="basic:*:${PBI_PROXYUSER}:${PBI_PROXYPASS}"
6766
				export HTTP_PROXY_AUTH
6767
			fi
6768
		fi
6769
	fi
6770
}
6771

    
6772
# If the loaded file is a PBI PatchFile
6773
is_pbi_patch() {
6774
	if [ -z "$PBI_PATCHVERSION" ] ; then
6775
		return 1
6776
	else
6777
		return 0
6778
	fi
6779
}
6780

    
6781

    
6782
# Build the specified port
6783
do_port_build()
6784
{
6785
  local _lPort="$1"
6786
  echo "Checking port: $_lPort"
6787

    
6788
  # Make sure this port isn't already loaded
6789
  local pkgName=`make -V PKGNAME -C $_lPort`
6790
  if [ -e "/var/db/pkg/${pkgName}" ] ; then return ; fi
6791

    
6792
  # Save any users / groups we need to create later
6793
  local pUsers="`make -V USERS -C $_lPort`"
6794
  local pGroups="`make -V GROUPS -C $_lPort`"
6795
  if [ -n "$pUsers" ] ; then
6796
     PBI_BUILD_USERS="$PBI_BUILD_USERS $pUsers"
6797
  fi
6798
  if [ -n "$pGroups" ] ; then
6799
     PBI_BUILD_GROUPS="$PBI_BUILD_GROUPS $pGroups"
6800
  fi
6801

    
6802
  # Parse the deps 
6803
  local TMPFILE=`mktemp /tmp/deplist.XXXXXXXX`
6804
  make all-depends-list -C $_lPort >$TMPFILE
6805
  while read line
6806
  do
6807
    local _port="$line"
6808
    local _depPkgName=`make -V PKGNAME -C $_port`
6809
    # is this installed?
6810
    if [ -e "/var/db/pkg/${_depPkgName}" ] ; then continue ; fi
6811

    
6812
    # Not installed, do this one now until we drill down to the base
6813
    do_port_build "${_port}" >&1 2>&1
6814
  done < $TMPFILE
6815
  rm ${TMPFILE}
6816

    
6817
  # Not installed, see if we have a pkg to install instead
6818
  if [ -e "/pkgs/${pkgName}.txz" ] ; then
6819
     echo "Checking package: ${pkgName}"
6820
     REBUILDPKG="NO"
6821
     pkg_info -r /pkgs/${pkgName}.txz | grep "Dependency:" | cut -d ' ' -f 2 > /tmp/deps.$$
6822
     while read dLine
6823
     do
6824
	pkg_info $dLine >/dev/null 2>/dev/null
6825
        if [ $? -ne 0 ] ; then
6826
	   echo "Package dependencies updated! Rebuilding port..."
6827
           REBUILDPKG="YES"
6828
	   break
6829
        fi
6830
     done < /tmp/deps.$$
6831
     rm /tmp/deps.$$
6832

    
6833
     # Fix some pkgs bugging us with license questions
6834
     PACKAGE_BUILDING=yes
6835
     export PACKAGE_BUILDING
6836

    
6837
     if [ "$REBUILDPKG" = "NO" ] ; then
6838
       echo "Adding package: ${pkgName}"
6839
       pkg_add -f /pkgs/${pkgName}.txz
6840
       return
6841
     fi
6842
  fi
6843

    
6844
  # No package, lets do old-fashioned build
6845
  echo "Compiling port: ${_lPort}"
6846
  cd ${_lPort}
6847
  make rmconfig
6848
  make clean
6849
  make install
6850
  if [ "$?" != "0" ] ; then
6851
     echo "BUILDERROR1!!"
6852
     sleep 2
6853
     make install
6854
     if [ "$?" != "0" ] ; then
6855
	if [ "$MKDEBUG" = "YES" ] ; then
6856
  	  echo "Failed! Running /bin/sh for debugging, type 'exit' to finish."
6857
  	  /bin/sh
6858
	fi
6859
	make clean
6860
	exit_err "make install of ${PBI_MAKEPORT} failed!"
6861
     fi
6862
  fi
6863
  make clean
6864

    
6865
  # Are we caching packages?
6866
  if [ "${PBI_PKGCACHE}" = "YES" ] ; then
6867

    
6868
    # Prune outdated versions of cached pkg
6869
    local basePkgName
6870
    basePkgName="`echo ${pkgName} | rev | cut -d '-' -f 2- | rev`"
6871
    for rmPkg in `ls /pkgs/${basePkgName}* 2>/dev/null | sed 's|/pkgs/||g'`
6872
    do
6873
        testPkg="`echo ${rmPkg} | rev | cut -d '-' -f 2- | rev`"
6874
	if [ -n "$testPkg" -a "$testPkg" = "$basePkgName" ] ; then
6875
	   echo "Pruning old cache pkg: ${rmPkg}"
6876
	   rm /pkgs/${rmPkg}
6877
	fi
6878
    done
6879

    
6880
    # Create new pkg
6881
    pkg_create -J -b ${pkgName}
6882
    mv ${pkgName}.txz /pkgs/
6883
    sha256 -q /pkgs/${pkgName}.txz >/pkgs/${pkgName}.txz.sha256
6884

    
6885
  fi
6886
};
6887

    
6888

    
6889
# Main program operation
6890
##############################################################
6891
init_vars
6892
mk_required_dirs
6893
load_pbi_etcconf
6894

    
6895
trap exit_trap 1 2 3 9 15
6896

    
6897
# Figure out which mode we are running in
6898
case `basename ${0}` in
6899
   pbi_add) pbi_add_init "$@" ;;
6900
   pbi_addrepo) pbi_addrepo_init "$@" ;;
6901
   pbi_autobuild) pbi_autob_init "$@" ;;
6902
   pbi_browser) pbi_browser_init "$@" ;;
6903
   pbi_create) pbi_create_init "$@" ;;
6904
   pbi_deleterepo) pbi_deleterepo_init "$@" ;;
6905
   pbi_delete) pbi_delete_init "$@" ;;
6906
   pbi_icon) pbi_icon_init "$@" ;;
6907
   pbi_indextool) pbi_it_init "$@" ;;
6908
   pbi_info) pbi_info_init "$@" ;;
6909
   pbi_listrepo) pbi_listrepo_init "$@" ;;
6910
   pbi_makeport) pbi_make_init "$@" ;;
6911
   pbi_makeport_chroot) pbi_make_init "$@" ;;
6912
   pbi_makepatch) pbi_makepatch_init "$@" ;;
6913
   pbi_makerepo) pbi_makerepo_init "$@" ;;
6914
   pbi_metatool) pbi_mt_init "$@" ;;
6915
   pbi_patch) pbi_patch_init "$@" ;;
6916
   pbi_update) pbi_update_init "$@" ;;
6917
   pbi_update_hashdir) pbi_update_hashdir_init "$@" ;;
6918
   pbi-crashhandler) pbi_crash_init "$@" ;;
6919
   pbid) pbid_init "$@" ;;
6920
   *) echo "Error: Called with invalid basename!" ; exit_trap ;;
6921
esac
6922

    
6923
rm_tmpdir
6924
exit 0
(11-11/34)