aboutsummaryrefslogtreecommitdiff
path: root/scripts/pkg
blob: ab88db78a538565efa666ef79346037e34df1695 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
#!/bin/bash

# pkg - Formilux package builder - version 0.3.2 - 2003-06-09
#
# Copyright (C) 2001-2003 Benoit Dolez & Willy Tarreau
#       mailto: benoit@ant-computing.com,willy@ant-computing.com
#
# This program is licenced under GPLv2 ( http://www.gnu.org/licenses/gpl.txt )

## WARNING ##
# This version is not compatible with pkg scripts written for pre-0.2.0 versions


# Usage:
#   pkg <action> [ pkg [ pkg2 ] ]
#
#   pkg newpkg [ new_pkg [ old_pkg ] ]
#     ex: pkg newpkg openssl-0.9.6g-flx0.1 openssl-0.9.6d-flx0.1
#         pkg newpkg apache apache-1.3
#         pkg newpkg bash
#         pkg newpkg gcc gcc-3*flx*.1
#
#   pkg setpkg [ new_pkg ]
#     ex: pkg setpkg openssl-0.9.6g-flx0.1
#
#   pkg { info | cat | edit } [ pkg ] 
#     ex: pkg info
#         pkg info bash
#         pkg edit modutils-2.4
#         pkg cat gzip-1.3
#
#   pkg { compile,build,prepack,strip,pack,unpack,delpack,release,clean }*
#
#   pkg { patch | unpatch } [ patch_name ]
#
#   pkg { any_command } [ any_args ]
#

# don't return stupid names, and we also want dotfiles and use extended globbing
shopt -s nullglob
shopt -s dotglob
shopt -s extglob

# disable pathnames expansion
set -o noglob

# change the default mask to avoid common security problems
umask og-w

# set some constants
KERNDIR=${KERNDIR:-/usr/src/linux}
FLXARCH=${FLXARCH:-$(uname -m)}
DEVROOT=${DEVROOT:-/var/flx-dev}
PKGROOT=${PKGROOT:-/var/flx-pkg}
# use -p1 by default to apply a patch
PATCH_LEVEL=${PATCH_LEVEL:-1}
# the suffix that we use to name different builds. It also matches build
# versions with this name followed by a number (BUILDVER)
BUILDSFX=${BUILDSFX:-flx}
BUILDVER=${BUILDVER:-0}

PKGSUFF="tgz"
CFGSUFF="cfg"
INSTNAME=".flxdisk"
LINKNAME=".flxpkg"

FILE_LIST=

######
###### here are some functions for manipulating package names
######

# returns the radix from a package name. Eg: 'pkg-1.2.3a-flx0.12' returns 'pkg'
function get_pkg_radix {
    echo ${1%%[-_][0-9]*}
}

# returns the version from a package name. Eg: 'pkg-1.2.3a-flx0.12' returns '1.2.3a'
function get_pkg_ver {
    local ver=${1#${1%%[_-][0-9]*}[._-]} 
    ver=${ver%-${BUILDSFX}*}
    [ "$ver" = "$1" ] || echo $ver
}

# returns the build number from a package name when appropriate, or empty when
# there's nothing. Eg: 'pkg-1.2.3a-flx0.12-pkg' returns 'flx0.12'
function get_build_num {
    local build=${1##${1%%-${BUILDSFX}*([0-9]).+([0-9])*}}	# -flx0.12-pkg
    build=${build%%${build##-${BUILDSFX}*([0-9]).+([0-9])}}	# -flx0.12
    build=${build#-}					# flx0.12
    [ "$build" != "$1" ] && echo $build
}

# returns the build number following a known build. Eg: 'flx0.12' returns 'flx0.13'
function get_next_build {
    local prefix=${1%%.*}
    local suffix=${1##*.}
    echo $prefix.$[$suffix + 1]
}

# This function accepts a list of versionned names, and returns them sorted by
# version number. The names must NOT contain any '|' or '~' character, or they
# will be discarded. Names that don't have any version are also discarded.
function sortnames {
    local IFS FIELD NUMERIC_VERSION ALPHA_VERSION VERSION
    local base version rest filename i t file flist
    local -a list

    # a numeric versions consists in a series of numbers delimited by dots, and
    # optionnally ending with one or several dots, so that strange namings are
    # correctly processed. An alphanumeric version consists in everything that
    # cannot match a numeric version, optionnaly ending with one or more dots.
    IFS=$'\n'
    FIELD='\([^|]*\)'
    NUMERIC_VERSION='\([0-9]\+\(\.[0-9]\+[.]*\)*\)'
    ALPHA_VERSION='\([^0-9~|.]\+[.]*\)'
    VERSION="\($NUMERIC_VERSION\|$ALPHA_VERSION\)"

    # make the list appear in the form 'package|version|rest|full_name'
    list=($(echo "$*" | grep -v "|~" | sed -e "s/$VERSION/\1|/" \
		    -e "s/^$FIELD|$VERSION/\1|\2|/" \
		    -e "s/^$FIELD|$FIELD|$FIELD$/\1|\2|\3~\1\2\3/" \
		    -e "s/^[^|]*|[^|]*$//"))

    # there's a risk that it doesn't complete for all the list, and that some
    # elements keep a "rest". But what can we do about it ?

    # we loop on the list if there's at least one element
    # this will build alternating series of numeric-only and non-numeric
    # substrings, packed by six.
    while [ "${list[0]}" ] ; do
	# now we add sub-version delimiters ','
	list=( $(for file in ${list[*]} ; do
           IFS="|~" ; set -- $file
	    base=$1 ; version=$2 ; rest=$3 ; filename=$4
	    if [ -z "$rest" ] ; then
		IFS="." ; set -- $version
		# we append a dot to the version for sed below.
		echo "$base,$1,$2,$3,$4,$5,$6|.~$filename"
		continue
	    fi
	    IFS="." ; set -- $version
	    echo "$base,$1,$2,$3,$4,$5,$6|$rest~$filename"
	done | sed -e "s/^$FIELD|\($VERSION\|\.\)/\1|\2|/"))
	IFS=$'\n'
	# and we stop once everyone has "|\.|~" (no rest)
	if echo "${list[*]}" | grep -vq "|\.|~" ; then : ; else break ; fi
    done

    # now construct a field separator list for 'sort'. Since it's full of bugs,
    # the only way for it to work is -k1,1 -k2,2n -k3,3n ...
    # To match most cases, we'll assume that most of our packages will be
    # numbered NNNNNNAAAAAANNN... (6 numbers, 6 alpha, repeating).
    IFS=',' ; i=1 ; flist=
    for t in ${list[0]%%|*} ; do
	if [ $i -eq 1 -o $[(($i-2)/6)&1] -eq 1 ]; then
	    flist="$flist${flist:+ }-k$i,$i"
	else
	    flist="$flist${flist:+ }-k$i,$i"n
	fi
	i=$[$i+1];
    done

    IFS=$'\n'$'\t'' '
    # Do not use '-u' since sort is stupid enough to remove nearly identical
    # lines !
    #echo "${list[*]}" | sort -t , -u $flist | cut -f2 -d~
    echo "${list[*]}" | sort -t , $flist | cut -f2 -d~
}

######
###### here are "exported" functions, which can be used and redefined by build.cfg
######

# builds everything from a clean start
function do_build {
    local ACTION
    # ACTION will be inherited by other functions
    for ACTION in clean compile prepack strip pack ; do
	declare -f pre_$ACTION > /dev/null && { ( pre_$ACTION $* ) || return $?; }
	declare -f do_$ACTION > /dev/null && { ( do_$ACTION $* ) || return $?; }
	declare -f post_$ACTION > /dev/null && { ( post_$ACTION $* ) || return $?; }
    done
}

# this function returns one exact package name from a list of potentially
# interesting ones, classed from higher preference to lower. They are all
# passed as strings, constituting packages names, or some of the following
# special names :
#   %P => use current directory as the source for the name
#   %L => use the package pointed to by the ${LINKNAME} link
#   %D => use the default package
# If several packages match a given pattern, the user is asked to select the
# desired one.
# The result is returned in REPLY.
function get_name {
    local pattern pkg_name
    local radix ver build
    local -a rel_list dev_list sort_list
    local i

    REPLY=
    for pattern in $*; do
	if [ "$pattern" = "%P" ]; then
	    pattern=$(basename $(pwd))
	elif [ "$pattern" = "%L" ]; then
	    if [ -L ${LINKNAME} -a -d ${LINKNAME}/. ]; then
		# the link is always an EXACT name, so we return it as-is.
		pattern=$(readlink ${LINKNAME})
		REPLY=$(basename $pattern)
		return
	    else
		continue
	    fi
	elif [ "$pattern" = "%D" ]; then
	    pattern=default
	fi
	radix=$(get_pkg_radix $pattern)
	ver=$(get_pkg_ver $pattern)
	build=$(get_build_num $pattern)
	pkg_name=${radix:-*}-${ver:-*}-${build:-*}

	REPLY=
	# we loop until pkg_name is empty, which allows recursive choices.
	while [ "$pkg_name" ]; do
	    # now we'll try to build a list of potentially matching packages for
	    # each pattern. We'll reduce the original name until either we have
	    # a non-empty list or the package name is void.
	    rel_list=( ); dev_list=( )
	    while [ "$pkg_name" -a -z "$rel_list" -a -z "$dev_list" ]; do
		rel_list=( $(find $PKGROOT/ -maxdepth 1 -type d -name ${pkg_name} -printf "%f\n" 2>/dev/null) )
		if [ "$release_only" != "1" ]; then
		    dev_list=( $(find $DEVROOT/ -maxdepth 1 -type d -name ${pkg_name} -printf "%f\n" 2>/dev/null) )
		fi
		
		if [ -z "${rel_list[*]}" -a -z "${dev_list[*]}" ]; then
		    radix=$(get_pkg_radix $pkg_name)
		    ver=$(get_pkg_ver $pkg_name)
		    build=$(get_build_num $pkg_name)
		    
		    if [ "$ver" -a "$ver" != "*" -a "$radix" != "$pkg_name" ]; then
			if [ "$build" -a "$build" != "*" ]; then
			    pkg_name=${radix}-${ver}-*
			elif [ "${ver%.*}" != "$ver" ]; then
			    # let's reduce the version precision
			    pkg_name=${radix}-${ver%.*}-*
			else
			    pkg_name=${radix}-*
			fi
		    else
			break
		    fi
		else
		    break
		fi
	    done
	    
	    # we're prepared to break the big loop, unless someone sets pkg_name again.
	    pkg_name=
	    sort_list=( $(sortnames ${dev_list[*]} ${rel_list[*]}) )
	    
	    # if we matched nothing, we jump to the next pattern, and if we matched
	    # exactly one result, we return it immediately.
	    if [ ${#sort_list[*]} -eq 0 ]; then
		continue
	    elif [ ${#sort_list[*]} -eq 1 ]; then
		REPLY=${sort_list[0]}
		return
	    fi

	    # now, we'll present the possible names to the user.
	    i=0
	    printf " %5d : - None of the following packages -\n" 0
	    while [ $i -lt ${#sort_list[*]} ]; do
		# we'll display an 'R' in front of released names, or a 'D' for dev.
		if [ "${rel_list[*]/${sort_list[$i]}/}" != "${rel_list[*]}" ]; then
		    printf " %5d : [R] %s\n" $[$i+1] ${sort_list[$i]}
		else
		    printf " %5d : [D] %s\n" $[$i+1] ${sort_list[$i]}
		fi
		i=$[$i+1]
	    done
	    echo

	    while : ; do
		echo -n "Choice [${sort_list[${#sort_list[*]}-1]}]: "; read i
		if [ -z "$i" ]; then
		    # empty string, we use the last choice which is the preferred one.
		    i=${#sort_list[*]}
		    REPLY=${sort_list[$[$i-1]]}
		    return
		elif [ "${i//[0-9]/}" ]; then
		    # not a plain integer, we'll allow to recursively re-select
		    #pattern=${pattern}*${i}
		    pattern=${i}
		    radix=$(get_pkg_radix $pattern)
		    ver=$(get_pkg_ver $pattern)
		    build=$(get_build_num $pattern)
		    pkg_name=${radix:-*}-${ver:-*}-${build:-*}
		    break;
		elif [ $i -le 0 ]; then
		    # if the user explicitly replied "0", then he wants other choices.
		    break;
		elif [ $i -le ${#sort_list[*]} ]; then
		    REPLY=${sort_list[$[$i-1]]}
		    return
		fi
	    done
	    # we get here only either if someone tries to refine the package name or
	    # if he refuses these ones.
	done
    done
}

# choose a package and make ${LINKNAME} point to it
function do_setpkg {
    rm -f ${LINKNAME}
    ln -s $PKGDIR ${LINKNAME}
}


# look for existing packages, and propose a new version for the current one
function do_newpkg {
    local -a rel_list dev_list sort_list
    local pkg_name new_name
    local radix ver build

    set -o noglob
    if [ -e ${LINKNAME} ]; then
	if [ -L ${LINKNAME} ]; then
	    if [ -d ${LINKNAME}/. ]; then
		echo "Error! the link '${LINKNAME}' already exists. Please remove it by manually."
		exit 1
	    else
		rm -f ${LINKNAME}
	    fi
	else
	    echo "Error! '${LINKNAME}' already exists and is not a link. Please remove it by manually."
	    exit 1
	fi
    fi

    if [ $# -gt 0 ]; then
	# the user has specified an explicit version string
	new_name=$1
	if [ $# -gt 1 ]; then
	    pkg_name=$2
	fi
    else
	# the user has not specified any version string, we'll use the directory
	# name.
	new_name=$(basename $(pwd))
    fi

    rel_list=( ); dev_list=( )

    # now we'll have to guess the new package name.
    # The build rev part (flx*.*) will be ignored.
    # We'll look for existing packages with the exact
    # name+version, and if found, use this + the first unused build number.
    # If not found, a new package is created with the exact name and flx0.1

    radix=$(get_pkg_radix $new_name)
    ver=$(get_pkg_ver $new_name)
    build=$(get_build_num $new_name)
    new_name=${radix:-*}-${ver:-*}

    rel_list=( $(find $PKGROOT/ -maxdepth 1 -type d -name ${new_name}\* -printf "%f\n" 2>/dev/null) )
    dev_list=( $(find $DEVROOT/ -maxdepth 1 -type d -name ${new_name}\* -printf "%f\n" 2>/dev/null) )
    sort_list=(${rel_list[*]} ${dev_list[*]})

    if [ "${sort_list[*]}" ]; then
	sort_list=($(IFS=$'\n'; echo "${sort_list[*]%-${BUILDSFX}*([0-9]).+([0-9])*}" | sort -u) )
	sort_list=( $(sortnames ${sort_list[*]}) )
	if [ "${radix/*\\**/}" -a "${ver/*\\**/}" ] && \
	    ! (IFS=$'\n';echo "${sort_list[*]}"|grep -q "^$new_name\$"); then
	    # if the package was properly named, and not already listed, let's
	    # propose it on last position.
	    sort_list=( ${sort_list[*]} $new_name )
	fi
	# echo "package_list : ${sort_list[*]}"

	# now, we'll present the possible names to the user
	if [ ${#sort_list[*]} -gt 1 ]; then
	    local i=0
	    echo; echo ">>> Please select the name of the package to create :";echo
	    while [ $i -lt ${#sort_list[*]} ]; do
		# we'll display an 'R' in front of released names, or a 'D' for dev.
		if [ "${rel_list[*]/${sort_list[$i]}/}" != "${rel_list[*]}" ]; then
		    printf " %5d : [R] %s\n" $[$i+1] ${sort_list[$i]}
		else
		    printf " %5d : [D] %s\n" $[$i+1] ${sort_list[$i]}
		fi
		i=$[$i+1]
	    done

	    echo
	    while : ; do
		echo -n "Choice [${sort_list[${#sort_list[*]}-1]}]: "; read i
		if [ -z "$i" ]; then
		    new_name=${sort_list[${#sort_list[*]}-1]}
		    break
		elif [ "${i//[0-9]/}" ]; then
		    # not a plain integer, we'll take it for the new name
		    new_name=$i
		    break;
		elif [ $i -ge 1 -a $i -le ${#sort_list[*]} ]; then
		    new_name=${sort_list[$[$i-1]]}
		    break;
		fi
	    done
	else
	    new_name=${sort_list[0]}
	fi
	# we'll search for all packages starting with the same name and version
	# in both release and dev dirs. Then we'll be able to deduce the latest
	# build number used.
#	sort_list=( $(find $PKGROOT/ $DEVROOT/ -maxdepth 1 -type d -name ${new_name}-${BUILDSFX}*.\* -printf "%f\n" 2>/dev/null|sort -u) )
	sort_list=( $(find $PKGROOT/ $DEVROOT/ -maxdepth 1 -type d -name ${new_name}-${BUILDSFX}${BUILDVER}.\* -printf "%f\n" 2>/dev/null|sort -u) )
	if [ ${#sort_list[*]} -eq 0 ]; then
	    # this can happen with new BUILDSFX/BUILDVER
	    new_name=${new_name}-${BUILDSFX}${BUILDVER}.1
	else
	    sort_list=( $(sortnames ${sort_list[*]} ))
	    new_name=${new_name}-$(get_next_build $(get_build_num ${sort_list[${#sort_list[*]}-1]}))
	fi
    else
	if [ -z "${radix/*\\**/}" -o -z "${ver/*\\**/}" ]; then
	    echo "Error: no existing package matches $new_name, and wildcards"
	    echo "or incomplete names cannot be part of a real name."
	    exit 1
	fi
	# we keep new_name since it's syntactically correct
	new_name=${new_name}-${BUILDSFX}${BUILDVER}.1
    fi

    #echo "new_name: $new_name"

    # if pkg_name is unspecified, we'll use the current directory name to guess
    # the source package, else we'll use the explicit name
    echo; echo ">>> Please select the package to use as a reference :"; echo

    get_name $pkg_name $new_name %P %D

    if [ -z "$REPLY" ]; then
	echo "No reference package found (even default). Please specify one."
	exit 1
    fi

    echo "Using '$REPLY'."

    if [ -e "$PKGROOT/$REPLY/build.cfg" ]; then
	pkg_name=$PKGROOT/$REPLY
    else
	pkg_name=$DEVROOT/$REPLY
    fi

    # new_name is always relative to DEVROOT
    #echo "new_name: $new_name ; old_name: $(basename $pkg_name)"

    # we should verify that new_name/released doesn't exist before extracting
    # anything into it, or even that new_name doesn't exist at all.
    new_name=$DEVROOT/$new_name
    if [ -e $new_name ]; then
	echo "Error! new directory $new_name already exists. Refusing to overwrite."
	exit 1
    fi

    rm -f ${LINKNAME} && mkdir -p $new_name && ln -s $new_name ${LINKNAME} && \
	tar -C $pkg_name  --exclude='compiled/*' --exclude='released.*' -cplf - . | tar -C $new_name -xf - || \
	    (rmdir $new_name ; rm -f ${LINKNAME})
    echo "A new package '$(basename $new_name)' has been created as '$new_name', based on '$(basename $pkg_name)'."
    echo "The link '${LINKNAME}' now points to it."
    echo
    if [ $(find $new_name/patches -type f |wc -l) -gt 0 ]; then
	echo "*** Warning: there are patches to be applied, use >>>pkg info<<< ***"
	echo
    fi
    set +o noglob
    return 0
}


function do_edit {
    echo "Editing $CFGFILE..."
    vi $CFGFILE
}

function do_cat {
    cat $CFGFILE
}

function pre_info {
    echo "Information for package '$EXACTPKG' :"

    echo "   Package version : $PKGVER (\$PKGVER)"
    echo "   Distrib version : $DISTVER (\$DISTVER)"
    echo -n "   Config. file : "
    if [ -e $CFGFILE ]; then
	echo "$CFGFILE"
    else
	echo "none found."
    fi
    echo "   Package file : $PKGDIR/compiled/$EXACTPKG-$FLXARCH.$PKGSUFF"
    echo -n "   Package size : "
    if [ -e $PKGDIR/compiled/$EXACTPKG-$FLXARCH.$PKGSUFF ]; then
	echo "$(du -b $PKGDIR/compiled/$EXACTPKG-$FLXARCH.$PKGSUFF |cut -f1) bytes."
    else
	echo "does not exist yet."
    fi
    [ "$PATCH_LIST" ] && echo "   Patches list : $PATCH_LIST"
    return 0
}

# does only compile, not changing the current config
function do_compile_only {
    $FLXMAKE
    return $?
}

# new simplified name for 'config_only', which is deprecated, not changing current scripts.
function do_config {
    if declare -f do_config_only >/dev/null 2>&1; then
	do_config_only
	return $?
    else
	return 0
    fi
}

# configures and compiles
function do_compile {
    do_config && do_compile_only
}

# preparatory work for prepack()
function pre_prepack {
    if [ "$UID" != "0" -a "$force" != "1" ]; then
	echo "You must specify '--force' to install as non-root"
	exit 1
    fi
    # WARNING! here, we don't use $ROOTDIR because we don't want to risk
    # erasing a wrong directory as root !
    [ -d $(pwd)/${INSTNAME} ] && rm -rf $(pwd)/${INSTNAME}
    return 0
}

# some cleanup of an eventual opt directory after prepack()
function post_prepack {
    local dir
    if [ -d $ROOTDIR/opt ] ; then (
	cd $ROOTDIR/opt
	for dir in bin sbin lib ; do
	    mkdir $dir
	    find */$dir  -type f -perm +111 -exec ln -s ../{} $dir \; -printf "ln -s ../%p $ROOTDIR/opt/$dir\n"
	done
    ) fi
    return 0
}

# deletes the current prepack directory.
function do_delpack {
    # WARNING! here, we don't use $ROOTDIR because we don't want to risk
    # erasing a wrong directory as root !
    [ -d $(pwd)/${INSTNAME} ] && rm -rf $(pwd)/${INSTNAME}
    return 0
}

# does a full clean
function do_clean {
    make distclean || make mrproper || make clean
    ( do_delpack )
    return 0
}

# applies all the patches to the current sources
# files which match *.rej and *~ will be deleted
function do_patch {
    local i
    find . -name '*.rej' -o -name '*~' | xargs rm -f

    for i in $PATCH_LIST; do
	patch -Np$PATCH_LEVEL < $PKGDIR/patches/$i
    done

    if [ -z "$(find . -name '*.rej')" ]; then
	find . -name '*~' | xargs rm -f
    fi
    return 0
}

# reverts all the patches from the current sources
# files which match *.rej and *~ will be deleted
function do_unpatch {
    local i
    local UNPATCH_LIST=""

    find . -name '*.rej' -o -name '*~' | xargs rm -f

    for i in $PATCH_LIST; do
	UNPATCH_LIST="$i $UNPATCH_LIST"
    done

    for i in $UNPATCH_LIST; do
	patch -RNp$PATCH_LEVEL < $PKGDIR/patches/$i
    done

    if [ -z "$(find . -name '*.rej')" ]; then
	find . -name '*~' | xargs rm -f
    fi
    return 0
}

# extracts a binary package into $ROOTDIR, to reflect the state prior to pack().
function do_unpack {
    local FILE=$PKGDIR/compiled/$EXACTPKG-$FLXARCH.$PKGSUFF
    mkdir -p $ROOTDIR
    cd $ROOTDIR

    echo -n "Extracting $FILE into $ROOTDIR ... "
    tar zUxpf $FILE >/dev/null 2>&1
    echo "done."
    return 0
}

# strips symbols from executables before building the package.
# Abort if ROOTDIR doesn't exist (thus needing prepack() first).
function do_strip {
    if [ ! -d $ROOTDIR ] ; then
	echo "Error: directory $ROOTDIR doesn't exist. Make sure you dir 'prepack'."
	exit 1
    fi
    #find $ROOTDIR/. -type f | xargs file | grep ":.*executable.*not stripped" | cut -f1 -d: | xargs strip -x --strip-unneeded -R .note -R .comment > /dev/null 2>&1 
    # allow executable and shared (.so), but not relocatable (.o), both stripped or not stripped
    find $ROOTDIR/. -type f | xargs file | grep ":.*ELF.*\(executable\|\shared\).*stripped" | cut -f1 -d: | xargs strip -x --strip-unneeded -R .note -R .comment > /dev/null 2>&1 
    return 0
} 

# forces pack() to strip before starting, even if do_pack() is redefined by the user.
function pre_pack {
    ( do_strip )
    return 0
}

# this function finds perl dependencies for a given file.
# It's only called from do_pack_files() and do_pack()
function get_perl_depend {
    local filename=$1
    local dep DEP
    local DEP_FILE=$PKGDIR/compiled/$EXACTPKG-$FLXARCH.dep

    DEP=$(grep "^\(.*['{\"]\)*[ 	]*\(require\|use\) \+['\"]*[a-zA-Z][a-z:/A-Z0-9-_]*[; '\"]" $filename | \
                sed -e 's/.*\(require\|use\) \+["'\'']\?\([^'\''" };]\+\)["'\'']\?/§§\2§§/g' \
                    -e 's/§§\([^§]\+\)§§[^§]*/ \1/g' | \
                sed 's@::@/@g')
    if [ "x$DEP" != "x" ] ; then
	echo -n "$filename" >> $DEP_FILE
        for dep in $DEP ; do
	    if [ "x${dep/*.*}" != "x" ] ; then
		echo -n " $dep.pm" >> $DEP_FILE
	    else
		echo -n " $dep" >> $DEP_FILE
            fi
        done
        echo >> $DEP_FILE
    fi
}
 
# same as pack, except that it uses files in the current directory as the root
# entries, and that no strip, link nor compression is performed.
# Only entries listed in the file pointed to by variable FILE_LIST find their
# way to the archive.
# This function relies on get_perl_depend().
function do_pack_files {  
    local DEP_FILE FPNAME

    find . -not -type l | xargs touch -m

    # full path name of different files
    FPNAME=$PKGDIR/compiled/$EXACTPKG-$FLXARCH
    DEP_FILE=$FPNAME.dep

    # FIXME: absurde ? : rm puis cat !
    rm -rf $DEP_FILE
    if [ -e $DEP_FILE.diff ] ; then cat $DEP_FILE.diff $DEP_FILE ; fi

    echo -n "Creating $DEP_FILE ... "
    touch $DEP_FILE
    find . -type f -o -type l | while read ; do
	case $REPLY in
	    *.pm|*.pl|*.ph)
		get_perl_depend $REPLY
		;;
	    */man/man*/*.[0-9n])
		echo "$REPLY \$MAN" >> $DEP_FILE
		;;
	    */info/*.info|*/info/*.info-[0-9]*)
		echo "$REPLY \$INFO" >> $DEP_FILE
		;;
	    */sbin/*|*/bin/*|*/lib/*|*/libexec/*)
		flr="$(file $REPLY)"
		case "$flr" in
		    *\ shell\ *)
			echo "$REPLY $(head -1 $REPLY| sed -e 's/^#\! *\([^ ]\+\).*/\1/') \$SHELL">>$DEP_FILE
			;;
		    *perl\ commands*)
			echo "$REPLY $(head -1 $REPLY| sed -e 's/^#\! *\([^ ]\+\).*/\1/') ">>$DEP_FILE
			get_perl_depend $REPLY
			;;
		    *:\ symbolic\ link*)
			echo "$REPLY $(echo $flr | cut -f5 -d' ')" >> $DEP_FILE
			;;
		    *\ ELF\ 32-bit\ LSB*dynamically\ linked*)
			echo "$REPLY $(ldd $REPLY 2>/dev/null | grep -v 'statically linked' | awk '{print $1}' | tr '\012' ' ')" >> $DEP_FILE
			;;
		    *\ ELF\ 32-bit\ LSB*shared\ object*)
			echo "$REPLY $(ldd $REPLY 2>/dev/null | grep -v 'statically linked' | awk '{print $1}' | tr '\012' ' ')" >> $DEP_FILE
			;;
		esac
		;;
	esac
    done
    echo "done."

    echo -n "Creating $FPNAME.lst ... "
    # we try the special case of the '.' entry which is needed to set the root permissions.
    # this entry must be set as "." in FILE_LIST.
    if grep -q '^.[ 	]' $FILE_LIST; then
	set -- $(grep '^.[ 	]' $FILE_LIST)
	owner=${2%%:*}
	group=${2##*:}
	echo "d $3 $owner $group          0 -------------------------------- 0 ."
    fi > $FPNAME.lst
    (flx sign --no-depth --ignore-dot $(cut -f1 -d' ' $FILE_LIST|sed -e 's,/$,,') >> $FPNAME.lst) > /dev/null 2>&1
    echo "done."

    echo -n "Creating $FPNAME.$PKGSUFF ... "

    # we want everything, including directories.
    cut -f1 -d' ' $FILE_LIST|sed -e 's,/$,,' | tar -T - --no-recursion -cf - | gzip -9 >$FPNAME.$PKGSUFF 2>/dev/null
    echo "done."
    return 0
}


# packs the prepacked files into a new file located in $DEVROOT.
# any eventual old package is removed.
# this function relies on do_pack_files(), get_perl_depend(), 
function do_pack {
    local DEP_FILE FPNAME

    # use the file list when available
    if [ "$FILE_LIST" ]; then
	do_pack_files
	return $?
    fi

    # FIXME: is this normal ???
    if [ ! -d $ROOTDIR ] ; then export ROOTDIR=$(pwd) ; fi
    cd $ROOTDIR

##  ( find lib -type l -name "lib*.so*" | xargs rm -f ; \
##  find usr/lib -type l -name "lib*.so*" | xargs rm -f ; \
##  ldconfig -nr . ) > /dev/null 2>&1
    ldconfig -nr . lib usr/lib > /dev/null 2>&1
    find . ! -type l | xargs touch -m

    # full path name of different files
    FPNAME=$PKGDIR/compiled/$EXACTPKG-$FLXARCH
    DEP_FILE=$FPNAME.dep

    # FIXME: absurde ? : rm puis cat !
    rm -rf $DEP_FILE
    if [ -e $DEP_FILE.diff ] ; then cat $DEP_FILE.diff $DEP_FILE ; fi

    echo -n "Creating $DEP_FILE ... "
    touch $DEP_FILE
    find . -type f -o -type l | while read ; do
	case $REPLY in
	    *.pm|*.pl|*.ph)
		get_perl_depend $REPLY
		;;
	    */man/man*/*.[0-9n])
		if [ "${REPLY/*gz}" ] ; then
		    if [ -L $REPLY ] ; then
			LINK=$(readlink $REPLY)
			rm $REPLY
			ln -s $LINK.gz $REPLY.gz
		    else
			gzip -f -9 $REPLY
			chmod 644 $REPLY.gz
		    fi
		fi
		echo "$REPLY \$MAN" >> $DEP_FILE
		;;
	    */info/*.info|*/info/*.info-[0-9]*)
		if [ "${REPLY/*gz}" ] ; then
		    gzip -f -9 $REPLY
		    chmod 644 $REPLY.gz
		fi
		echo "$REPLY \$INFO" >> $DEP_FILE
		;;
	    */sbin/*|*/bin/*|*/lib/*|*/libexec/*)
		flr="$(file $REPLY)"
		case "$flr" in
		    *\ shell\ *)
			echo "$REPLY $(head -1 $REPLY| sed -e 's/^#\! *\([^ ]\+\).*/\1/') \$SHELL">>$DEP_FILE
			;;
		    *perl\ commands*)
			echo "$REPLY $(head -1 $REPLY| sed -e 's/^#\! *\([^ ]\+\).*/\1/') ">>$DEP_FILE
			get_perl_depend $REPLY
			;;
		    *:\ symbolic\ link*)
			echo "$REPLY $(echo $flr | cut -f5 -d' ')" >> $DEP_FILE
			;;
		    *\ ELF\ 32-bit\ LSB*dynamically\ linked*)
			echo "$REPLY $(ldd $REPLY 2>/dev/null | grep -v 'statically linked' | awk '{print $1}' | tr '\012' ' ')" >> $DEP_FILE
			;;
		    *\ ELF\ 32-bit\ LSB*shared\ object*)
			echo "$REPLY $(ldd $REPLY 2>/dev/null | grep -v 'statically linked' | awk '{print $1}' | tr '\012' ' ')" >> $DEP_FILE
			;;
		esac
		;;
	esac
    done
    echo "done."

    echo -n "Creating $FPNAME.lst ... "
    (find . ! -type d -o -empty | cut -c3-| xargs flx sign --ignore-dot --no-depth > $FPNAME.lst) > /dev/null 2>&1
    echo "done."

    echo -n "Creating $FPNAME.$PKGSUFF ... "
    # we want everything, and directories only if they're empty. All this without './'
    # we shouldn't get an empty line since . should contain at least what we want to tar !
    find . ! -type d -o -empty | cut -c3- | tar -T - -cf - | gzip -9 >$FPNAME.$PKGSUFF 2>/dev/null
    echo "done."
    return 0
}

function usage {
    echo "Usage:"
    echo "  pkg [-options]* <action> [ pkg [ pkg2 ] ]"
    echo
    echo "  pkg newpkg [ new_pkg [ old_pkg ] ]"
    echo "    ex: pkg newpkg openssl-0.9.6g-${BUILDSFX}${BUILDVER}.1 openssl-0.9.6d-${BUILDSFX}${BUILDVER}.1"
    echo "        pkg newpkg apache apache-1.3"
    echo "        pkg newpkg bash"
    echo "        pkg newpkg gcc gcc-3*${BUILDSFX}*.1"
    echo
    echo "  pkg setpkg [ new_pkg ]"
    echo "    ex: pkg setpkg openssl-0.9.6g-${BUILDSFX}${BUILDVER}.1"
    echo
    echo "  pkg { info | cat | edit } [ pkg ]"
    echo "    ex: pkg info"
    echo "        pkg info bash"
    echo "        pkg edit modutils-2.4"
    echo "        pkg cat gzip-1.3"
    echo
    echo "  pkg { compile | config | compile_only | build | prepack }*"
    echo "  pkg { strip | pack | unpack | delpack | release | clean }*"
    echo
    echo "  pkg { patch | unpatch } [ patch_name ]"
    echo
    echo "  pkg { any_command } [ any_args ]"
    echo
    echo "User variables are :"
    echo "PKGROOT : directory containing released packages <$PKGROOT>"
    echo "DEVROOT : directory containing unreleased packages <$DEVROOT>"
    echo "ROOTDIR : base directory for package installation (not source), <$ROOTDIR>"
    echo "FLXARCH : architecture to use for the package, <$FLXARCH>"
    echo "KERNDIR : kernel sources location, if needed, <$KERNDIR>"
# Those two are not user-settable anymore
#    echo "CFGFILE : force to use of a .pkg, <$CFGFILE>"
#    echo "DISTVER : build version (${BUILDSFX}${BUILDVER}.1)"
    exit 1
}

# displays usage
function do_help {
    usage
    return 0
}

function do_release {
    echo "#####################################################"
    echo "# Release command not implemented yet ! Aborting... #"
    echo "#####################################################"
    exit 1
    return 0
}

######
###### here are some functions used only from main
######

function known_cmd {
    declare -f pre_$ACTION > /dev/null && { ( pre_$ACTION $* ) || return $?; }
    declare -f do_$ACTION > /dev/null && { ( do_$ACTION $* ) || return $?; }
    declare -f post_$ACTION > /dev/null && { ( post_$ACTION $* ) || return $?; }
}


######
###### here is the main entry point
######

# scan the command line

release_only=0
force=0
PRINTUSAGE=0
ARGLIST=( )
ACTION=
CHAINCMD=1

[ $# -eq 0 ] && PRINTUSAGE=1

while [ $# -gt 0 ] ; do
    case "$1" in 
	--force )
	    force=1
	    ;;
	--help|-h)
	    PRINTUSAGE=1
	    ;;
	--rel|-r*)
	    release_only=1
	    ;;
	--)
	    shift
	    ARGLIST=(${ARGLIST[*]} $*)
	    break
	    ;;
	-* )
	    PRINTUSAGE=1
	    ;;
	*)
	    ARGLIST=(${ARGLIST[*]} "$1")
	    ;;
    esac
    shift
done


#echo "arglist=${ARGLIST[*]}"

[ $PRINTUSAGE -gt 0 ] && usage
[ ${#ARGLIST[*]} -lt 1 ] && usage

# Some actions can be chained, others not. we'll get the longest
# possible chain, and stop once we encounter a non-chainable action

while [ $CHAINCMD -gt 0 ]; do
    set -o noglob
    ACTION=${ARGLIST[0]}

    #    unset ARGLIST[0]  ### doesn't work in scripts with this shitty bash !!!
    ARGLIST[0]= ; ARGLIST=( ${ARGLIST[*]} )  # gets expanded with shitty bash !

    case "$ACTION" in
	newpkg)
	    CHAINCMD=0
	    KNOWNCMD=1
	    # newpkg is the only command which doesn't start by a package lookup.
	    ;;
	setpkg)
	    CHAINCMD=0
	    KNOWNCMD=1
	    get_name $1 %P default
	    ;;
	info|edit|cat)
	    CHAINCMD=0
	    KNOWNCMD=1
	    get_name ${ARGLIST[0]} %L %P %D
	    ;;
	patch|unpatch)
	    CHAINCMD=0
	    KNOWNCMD=1
	    REPLY=$(basename $(readlink ${LINKNAME}) 2>/dev/null)
	    # get_name %L
	    ;;
	compile_only|config|config_only|compile|build|prepack|strip|pack|unpack|delpack|release|clean)
	    KNOWNCMD=1
	    REPLY=$(basename $(readlink ${LINKNAME}) 2>/dev/null)
	    # get_name %L
	    ;;
	*)
	    CHAINCMD=0
	    KNOWNCMD=0
	    REPLY=$(basename $(readlink ${LINKNAME}) 2>/dev/null)
	    # get_name %L
	    ;;
    esac

    set +o noglob
    if [ "$ACTION" != "newpkg" ]; then
	if [ -z "$REPLY" ]; then
	    echo "Error: package name not found."
	    exit 1
	fi
	EXACTPKG=$REPLY

	if [ -e "$PKGROOT/$EXACTPKG/build.cfg" ]; then
	    PKGDIR=$PKGROOT/$EXACTPKG
	else
	    PKGDIR=$DEVROOT/$EXACTPKG
	fi
	CFGFILE=$PKGDIR/build.cfg
	PKGRADIX=$(get_pkg_radix $EXACTPKG)
	PKGVER=$(get_pkg_ver $EXACTPKG)
	DISTVER=$(get_build_num $EXACTPKG)
	ROOTDIR=${ROOTDIR:-$(pwd)/${INSTNAME}}

	# for compatibility with old functions. Not used anywhere outside this script.
	packver=$EXACTPKG
	pack=$PKGRADIX

	. $CFGFILE
    fi

    case "$FLXARCH" in
	i686) arch=i686 cpu=i686 basearch=i386 ;;
	i486) arch=i486 cpu=i486 basearch=i386 ;;
	i386) arch=i386 cpu=i386 basearch=i386 ;;
	*)    arch=i586 cpu=i686 basearch=i386 ;;
    esac

    if [ -z "$FLXMAKE" ]; then
	FLXMAKE=make
    fi

    export DISTVER PKGRADIX PKGVER FLXMAKE PATCH_LIST FILE_LIST

#    echo "ACTION=$ACTION, KNOWNCMD=$KNOWNCMD, CHAINCMD=$CHAINCMD"
#    echo "ARGLIST=${ARGLIST[*]}"

    if [ $KNOWNCMD -gt 0 ]; then
	known_cmd ${ARGLIST[*]} || exit 1
    else
	if declare -f do_$ACTION >/dev/null; then
	    ( do_$ACTION ${ARGLIST[*]} ) || exit 1
	fi
    fi

    # now, we'll loop only if we were in a chainable action
done






































exit 99

###############################################################################################################
###############################################################################################################
###############################################################################################################
###############################################################################################################


DEAD CODE BELOW !!!




































function usage {
    echo "Usage: pkg <action> [new_pkg [old_pkg]]"
    echo " action is one of :"
    echo "   help    : display this help."
    echo "   info    : get information on current package."
    echo "   newpkg  : build a more recent .pkg script from an old one."
    echo "   cat     : display last .pkg file."
    echo "   edit    : edit last .pkg file."
    echo "   patch   : apply a list of patches to the directory prior to compile."
    echo "   unpatch : revert a list of patches to the directory."
    echo "   compile : do_compile=do_config_only+do_compile_only in .pkg script ($CFGROOT/$CFGDIR)"
    echo "   prepack : execute do_prepack in .pkg script ($CFGROOT/$CFGDIR)"
    echo "   strip   : strip binaries in temporary directory"
    echo "   pack    : strip binaries, then package into $PKGROOT"
    echo "   delpack : remove temporary directory"
    echo "   clean   : execute 'make clean' and remove temporary directory."
    echo "   build   : execute clean compile prepack pack."
    echo "   unpack  : extract package into temporary directory"
    echo "Variables are :"
    echo "CFGROOT : directory for .pkg and patches, <$CFGROOT>"
    echo "CFGFILE : force to use of a .pkg, <$CFGFILE>"
    echo "PKGROOT : directory for .lst, .tgz and .dep, <$PKGROOT>"
    echo "ROOTDIR : base directory for package (not source), <$ROOTDIR>"
    echo "FLXARCH : architecture for package name, <$FLXARCH>"
    echo "KERNDIR : base directory for package (not source), <$KERNDIR>"
    echo "DISTVER : build version (flx.1)"
    exit 1
}









for ACTION in ${ARGLIST[*]}; do

# now we will try to identify two packages names :
#   - the EXACT one, deduced from command line, then version symlink, then the
#     directory name ; this one doesn't have to exist to be correct.
#   - the NEAREST one, deduced from the same criterions, with and without
#     versions, and based on EXISTING files only.
# The NEAREST one will be used as a source, while the EXACT one will be used as
# a target. When the EXACT one exists, the NEAREST one must obviously be the
# same.

# EXACTPKG can be specified as an environment variable if needed
[ $NEAREST_IS_SRC -eq 0 ] && [ -z "$EXACTPKG" -a ${#ARGLIST[*]} -gt 0 ] && EXACTPKG=$(basename ${ARGLIST[0]})
[ -z "$EXACTPKG" -a -L .flxver ] && EXACTPKG=$(readlink .flxver)
[ -z "$EXACTPKG" ] && EXACTPKG=$(basename $(pwd))

if [ -z "$(get_pkg_ver $EXACTPKG)" ]; then
    TEMP=$(sortnames $CFGROOT/$EXACTPKG-[0-9]* | tail -1)
    TEMP=${TEMP:-$(sortnames $CFGROOT/$EXACTPKG.* | tail -1)}
    TEMP=${TEMP:-$(sortnames $CFGROOT/$EXACTPKG-* | tail -1)}
    TEMP=${TEMP:-$(sortnames $CFGROOT/$EXACTPKG* | tail -1)}
#    if [ -z "$TEMP" ]; then
#	echo "Cannot find a suitable package for the current directory. Please specify"
#	echo "a correct name on the command line."
#	usage
#	exit 1
#    fi
    [ "$TEMP" ] && EXACTPKG=$(basename $TEMP)
    [ -z "$(get_pkg_ver $EXACTPKG)" ] && EXACTPKG=$EXACTPKG-0
fi

if [ -z "$(get_build_num $EXACTPKG)" ]; then
    RADIX=$(get_pkg_radix $EXACTPKG)
    TEMP=$(sortnames $CFGROOT/$EXACTPKG-* $CFGROOT/$EXACTPKG $CFGROOT/$RADIX | tail -1)

    VER=$(get_pkg_ver $TEMP)
    BUILD=$(get_build_num $TEMP)
    EXACTPKG=${RADIX}-${VER:-0}-${BUILD:-flx.1}
fi

NEWPKGRADIX=$(get_pkg_radix $EXACTPKG)
NEWPKGVER=$(get_pkg_ver $EXACTPKG)
NEWDISTVER=$(get_build_num $EXACTPKG)
NEWDISTVER=${NEWDISTVER:-flx.1}
EXACTPKG=$NEWPKGRADIX-$NEWPKGVER-$NEWDISTVER

trylist=( )
[ -d "$CFGROOT/$EXACTPKG" -o -f "$CFGROOT/$EXACTPKG.$PKGSUFF" ] && trylist=( ${trylist[*]} $EXACTPKG)
[ ${#ARGLIST[*]} -gt 0 ] && trylist=( ${trylist[*]} $(basename ${ARGLIST[0]}))
[ -L .flxver ] && trylist=( ${trylist[*]} $(readlink .flxver))
trylist=( ${trylist[*]} $NEWPKGRADIX-$NEWPKGVER )
trylist=( ${trylist[*]} $NEWPKGRADIX )
trylist=( ${trylist[*]} $(basename $(pwd)))
trylist=( ${trylist[*]} "default")

echo trylist=${trylist[*]}

for NEARESTPKG in ${trylist[*]}; do
    if [ -z "$(get_pkg_ver $NEARESTPKG)" ]; then
	TEMP=$(sortnames $CFGROOT/$NEARESTPKG-[0-9]* | tail -1)
	TEMP=${TEMP:-$(sortnames $CFGROOT/$NEARESTPKG.* | tail -1)}
	TEMP=${TEMP:-$(sortnames $CFGROOT/$NEARESTPKG-* | tail -1)}
	#TEMP=${TEMP:-$(sortnames $CFGROOT/$NEARESTPKG | tail -1)}
	[ "$TEMP" ] && NEARESTPKG=$(basename $TEMP) || continue
    fi

    RADIX=$(get_pkg_radix $NEARESTPKG)
    VER=$(get_pkg_ver $NEARESTPKG)
    BUILD=$(get_build_num $NEARESTPKG)
    NEARESTPKG=${RADIX}${VER:+-$VER}${BUILD:+-$BUILD}

    #### [ "$(get_build_num $NEARESTPKG)" ] &&

    [ -d "$CFGROOT/$NEARESTPKG" -o -f "$CFGROOT/$NEARESTPKG.$PKGSUFF" ] && break
echo NEARESTPKG=$NEARESTPKG

    ###TEMP=$(sortnames $CFGROOT/$NEARESTPKG-* | tail -1)
    ###[ "$(get_build_num $TEMP)" ] && NEARESTPKG=$(basename $TEMP) && break
done

RADIX=$(get_pkg_radix $NEARESTPKG)
VER=$(get_pkg_ver $NEARESTPKG)
BUILD=$(get_build_num $NEARESTPKG)
NEARESTPKG=${RADIX}${VER:+-$VER}${BUILD:+-$BUILD}

echo "EXACTPKG=$EXACTPKG"
echo "NEARESTPKG=$NEARESTPKG"

# to be removed ## look if there was an argument, in which case we would treat it as a package
# to be removed ## name (either source or destination, depending on the action). These variables
# to be removed ## are set :
# to be removed ##   - ARGPKGFULL  : full package name with version
# to be removed ##   - ARGPKGRADIX : package radix name (without version)
# to be removed ##   - ARGPKGVER   : package version without -flx*
# to be removed ##   - ARGDISTVER  : package build version (flx*)
# to be removed #
# to be removed #if [ ${#ARGLIST[*]} -gt 0 ]; then
# to be removed #    ARGPKGFULL=$(basename ${ARGLIST[0]})
# to be removed #    ARGPKGRADIX=$(get_pkg_radix $ARGPKGFULL)
# to be removed #    ARGPKGVER=$(get_pkg_ver $ARGPKGFULL)
# to be removed #    if echo $ARGPKGFULL | grep -q -- "-flx\." ; then
# to be removed #	 ARGDISTVER=$(get_build_num $ARGPKGFULL)
# to be removed #    fi
# to be removed #    ARGBASECFG=${ARGBASECFG:-$(sortnames $CFGROOT/$ARGPKGFULL* |tail -1)}
# to be removed #    ARGBASECFG=${ARGBASECFG:-$(sortnames $CFGROOT/$ARGPKGRADIX-$ARGPKGVER-* |tail -1)}
# to be removed #    ARGBASECFG=${ARGBASECFG:-$(sortnames $CFGROOT/$ARGPKGRADIX-$ARGPKGVER* |tail -1)}
# to be removed #    ARGBASECFG=${ARGBASECFG:-$(sortnames $CFGROOT/$ARGPKGRADIX-* |tail -1)}
# to be removed #fi
# to be removed #
# to be removed ## look for package name from the '.flxver' link in current dir, then dir name
# to be removed #
# to be removed #if [ -L .flxver ]; then
# to be removed #    PKGFULL=$(readlink .flxver)
# to be removed #else
# to be removed #    PKGFULL=$(basename $(pwd))
# to be removed #fi
# to be removed #
# to be removed #PKGRADIX=$(get_pkg_radix $PKGFULL)
# to be removed #PKGVER=$(get_pkg_ver $PKGFULL)
# to be removed #
# to be removed #if [ -z "$DISTVER" ] && echo $PKGFULL | grep -q -- "-flx\." ; then
# to be removed #    DISTVER=$(get_build_num $PKGFULL)
# to be removed #fi
# to be removed #
# to be removed #BASECFG=${BASECFG:-$(sortnames $CFGROOT/$PKGFULL* |tail -1)}
# to be removed #BASECFG=${BASECFG:-$(sortnames $CFGROOT/$PKGRADIX-$PKGVER-* |tail -1)}
# to be removed #BASECFG=${BASECFG:-$(sortnames $CFGROOT/$PKGRADIX-$PKGVER* |tail -1)}
# to be removed #BASECFG=${BASECFG:-$(sortnames $CFGROOT/$PKGRADIX-* |tail -1)}
# to be removed #
# to be removed #
# to be removed #
# to be removed ## now process the destination parameters
# to be removed #
# to be removed #if [ -L .flxver ]; then
# to be removed #    NEWPKGFULL=$(readlink .flxver)
# to be removed #else
# to be removed #    NEWPKGFULL=$(basename $(pwd))
# to be removed #fi
# to be removed #
# to be removed #NEWPKGRADIX=$(get_pkg_radix $NEWPKGFULL)
# to be removed #NEWPKGVER=$(get_pkg_ver $NEWPKGFULL)
# to be removed #NEWPKGVER=${NEWPKGVER:-$PKGVER}
# to be removed #
# to be removed #if [ -z "$NEWDISTVER" ] && echo $NEWPKGFULL | grep -q -- "-flx\." ; then
# to be removed #    NEWDISTVER=$(get_build_num $NEWPKGFULL)
# to be removed #fi
# to be removed #NEWDISTVER=${NEWDISTVER:-$DISTVER}
# to be removed #
# to be removed ## recompute the new package version
# to be removed #NEWBASECFG=${NEWBASECFG:-$NEWPKGRADIX-$NEWPKGVER-$NEWDISTVER}
# to be removed #


# now this is rather simple : for nearly all actions, NEWPKGFULL is used as the
# directory name for the new package. If it cannot be found, all actions except
# info and newpkg will fail. So we have to do a newpkg before using a new dir.

if [ ! -d "$CFGROOT/$NEARESTPKG" -a ! -f "$CFGROOT/$NEARESTPKG.$PKGSUFF" ]; then
    echo "Config directory <$NEARESTPKG> (NEARESTPKG) does not exist, use 'newpkg' first."
    exit 1
fi

# source configuration
ROOTDIR=${ROOTDIR:-$(pwd)/${INSTNAME}}


CURPKG=$NEARESTPKG
PKGRADIX=$(get_pkg_radix $NEARESTPKG)
PKGVER=$(get_pkg_ver $NEARESTPKG)
if echo $NEARESTPKG | grep -q -- "-flx\." ; then
    DISTVER=$(get_build_num $NEARESTPKG)
    NEARESTPKG=$PKGRADIX-$PKGVER-$DISTVER
else
    DISTVER=
    NEARESTPKG=$PKGRADIX-$PKGVER
fi

CFGDIR=$CFGROOT/$CURPKG
CFGFILE=$CFGDIR/$PKGRADIX.$CFGSUFF

echo "CFGFILE=$CFGFILE, PKGVER=$PKGVER, CFGDIR=$CFGDIR"

exit 0



if [ -n "$CFGFILE" ]; then
    CFGDIR=$NEWCFGROOT/$NEWBASECFG
    . $CFGFILE
else
	    #CFGFILE=`find $CFGROOT/ -name "$pack[-_]*-${DISTVER:-*}-$FLXARCH.$CFGSUFF"|sed -e "s/\.$CFGSUFF\$//"|sort|tail -1`
	    #CFGFILE=${CFGFILE:-`find $CFGROOT/ -name "$pack[-_]*-${DISTVER:-*}-*.$CFGSUFF"|sed -e "s/\.$CFGSUFF\$//"|sort|tail -1`}
	    #CFGFILE=${CFGFILE:-`find $CFGROOT/ -name "$pack[-_]*.$CFGSUFF"|sed -e "s/\.$CFGSUFF\$//"|sort|tail -1`}
	    #CFGFILE=${CFGFILE:-`find $CFGROOT/ -name "$pack.$CFGSUFF"|sed -e "s/\.$CFGSUFF\$//"|sort|tail -1`}
	    CFGFILE=`find $CFGROOT/ -maxdepth 1 -type d -name "$pack[-_]*-${DISTVER:-*}-pkg"|sed -e "s/-pkg\$//"|sort|tail -1`
	    CFGFILE=${CFGFILE:-`find $CFGROOT/ -maxdepth 1 -type d -name "$pack[-_]*-pkg"|sed -e "s/-pkg\$//"|sort|tail -1`}
	    CFGFILE=${CFGFILE:-`find $CFGROOT/ -maxdepth 1 -type f -name "$pack[-_]*-${DISTVER:-*}-pkg.$PKGSUFF"|sed -e "s/-pkg\.$PKGSUFF\$//"|sort|tail -1`}
	    CFGFILE=${CFGFILE:-`find $CFGROOT/ -maxdepth 1 -type f -name "$pack[-_]*-pkg.$PKGSUFF"|sed -e "s/-pkg\.$PKGSUFF\$//"|sort|tail -1`}

	    # to be completed

	    if [ -z "$CFGFILE" ]; then
		echo "CFGFILE not found. Cannot continue." >&2
		exit 1
	    fi

	    if [ -d $CFGFILE ]; then
		CFGROOT=`dirname $CFGFILE`
		CFGDIR=`basename $CFGFILE`-pkg
		CFGFILE=$CFGROOT/$CFGDIR/$pack.$CFGSUFF
	    else
		CFGROOT=`dirname $CFGFILE`
		CFGDIR=`basename $CFGFILE`-pkg
		CFGFILE=$CFGROOT/$CFGDIR/$pack.$CFGSUFF
		if [ ! -e $CFGROOT/$CFGDIR ]; then
		    echo "Opening package $CFGROOT/$CFGDIR.$PKGSUFF into $CFGROOT/$CFGDIR..."
		    mkdir -p $CFGROOT/$CFGDIR && tar -C $CFGROOT/$CFGDIR -Uxpf $CFGROOT/$CFGDIR.$PKGSUFF
		    if [ $? != 0 ]; then
			echo "There was an error during this operation. You may have to manually clean $CFGROOT/$CFGDIR. Cannot continue !"
			exit 1
		    else
			echo "Done !"
		    fi
		fi
	    fi

	    if [ -e "$CFGFILE" ]; then
		. $CFGFILE
	    else
		echo "CFGFILE ($CFGFILE) not found. Cannot continue." >&2
		exit 1
	    fi
	fi

	if [ -z "$DISTVER" ]; then
	    if echo $CFGFILE | grep -q -- "-flx\." ; then
		DISTVER=`echo $CFGFILE|sed 's/\(.*-\)\(flx.[0-9]\+\)\(.*\)/\2/'`
	    else
		DISTVER='flx.1'
	    fi
	fi

	echo $packver | grep -q -- "-flx\."
	if [ $? != 0 ] ; then
	    packver=$packver-$DISTVER
	fi

	echo $packver | grep -q -- "-$FLXARCH\$" 
	if [ $? != 0 ] ; then packver=$packver-$FLXARCH ; fi

	prefix=${packver%%[._-][0-9]*} 
	suffix=${packver#$prefix[._-]} 
	PKGVER=${suffix%-flx*}
	PKGRADIX=$prefix
	#echo "packver=$packver suffix=$suffix PKGVER=$PKGVER"
	if [ -z "$DISTVER" ]; then
	    DISTVER=${suffix#$PKGVER-}
	    if [ "$DISTVER" = "$PKGVER" ]; then
		DISTVER="flx.1"
	    else
		DISTVER=${DISTVER%-*}
	    fi
	fi

	case "$FLXARCH" in
	    i686) arch=i686 cpu=i686 basearch=i386 ;;
	    i486) arch=i486 cpu=i486 basearch=i386 ;;
	    i386) arch=i386 cpu=i386 basearch=i386 ;;
	    *)    arch=i586 cpu=i686 basearch=i386 ;;
	esac

	if [ -z "$FLXMAKE" ]; then
	    FLXMAKE=make
	fi

    
	if [ -z "$PATCH_LIST" ]; then
	    PATCH_LIST=${CFGFILE%%.$CFGSUFF}.diff
	    if [ ! -e "$PATCH_LIST" ]; then
		unset PATCH_LIST
	    fi
	fi

	export DISTVER PKGRADIX PKGVER FLXMAKE PATCH_LIST FILE_LIST
 
	declare -f pre_$ACTION > /dev/null && ( pre_$ACTION )
	[ $? != 0 ] && exit $?
	declare -f do_$ACTION > /dev/null && ( do_$ACTION )
	[ $? != 0 ] && exit $?
	declare -f post_$ACTION > /dev/null && ( post_$ACTION )
	[ $? != 0 ] && exit $?
    fi
fi