This file is indexed.

/usr/bin/bipgenconfig is in bip 0.8.9-1.2build1.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

   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
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
#!/usr/bin/env perl
#
# This file is part of the bip project
# Copyright (C) 2004 2007 Arnaud Cornet and Loïc Gomez
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# See the file "COPYING" for the exact licensing terms.
#

use strict;
use IO::File;
use Data::Dumper;

my $bipdir = $ENV{'HOME'} . '/.bip';
my $CFILE = $bipdir . '/bip.conf.autogen';
my $sfile = $bipdir . '/bipgenconfig.store';
my $certout = $bipdir . '/bip.pem.autogen';
my $SERIALIZE_DBG = 1;
my %cf;
my $DEBUG = 0;
my $global_done = 0;
my $cert_done = 0;
my $mode = 'normal';
# maximum level of nested blocks { { { } } }
my $maxlevel = 5;
my $bipmkpw;
my $tmpcrt = "/tmp/bip-cert.cnf";

my %optcompat = (
	"bl_msg_only" => "backlog_msg_only",
	"blreset_on_talk" => "backlog_reset_on_talk",
	"always_backlog" => "backlog_always",
);

my %optdesc = (
	'global' => {
		'ip' => { 'type' => 's', 'adv' => 1, 'default' => '0.0.0.0',
			'optional' => 1,
			'desc' => 'What IP address/hostname do you want bip to listen on ?' },
		'port' => { 'type' => 'i', 'adv' => 1, 'default' => '7778',
			'optional' => 1,
			'desc' => 'What port do you want bip to listen on ?' },
		'client_side_ssl' => { 'type' => 'b', 'adv' => 1, 'default' => 'true',
			'optional' => 1,
			'desc' => 'Do you want to enable client side SSL ?' },
		'client_side_ssl_pem' => { 'type' => 's', 'adv' => 1, 'optional' => 1,
			'default' => '',
			'desc' => 'Where is the bip.pem file (cert/key pair) ?' },
		'pid_file' => { 'type' => 's', 'adv' => 1, 'optional' => 1,
			'default' => $bipdir . '/bip.pid',
			'desc' => 'Where do you want the pidfile to be stored ?' },
		'log' => { 'type' => 'b', 'adv' => 0, 'default' => 'true',
			'optional' => 1,
			'desc' => 'Do you want to enable channel logging ?' },
		'log_system' => { 'type' => 'b', 'adv' => 0, 'default' => 'true',
			'optional' => 1,
			'desc' => 'Do you want to enable system logging ?' },
		'log_sync_interval' => { 'type' => 'i', 'adv' => 1,
			'optional' => 1,
			'default' => '5', 'depends' => 'log', 'depval' => 'true',
			'desc' => 'At which interval do you want bip to force logs to be written {seconds} ?' },
		'log_level' => { 'type' => 'i', 'adv' => 1, 'default' => '3',
			'optional' => 1,
			'depends' => 'log', 'depval' => 'true',
			'desc' => 'Define bip\'s system logs verbosity level {less 0 - 7 tremendous}:' },
		'log_root' => { 'type' => 's', 'adv' => 0,
			'optional' => 1,
			'default' => $bipdir . '/logs',
			'depends' => 'log', 'depval' => 'true',
			'desc' => 'In which directory do you want logs to be stored ?' },
		'log_format' => { 'type' => 's', 'adv' => 1, 'default' => '%n/%Y-%m/%c.%d.log', 
			'optional' => 1,
			'depends' => 'log', 'depval' => 'true',
			'desc' => 'Define the channel/private log format {see strftime, limited}:' },
	},

	'network' => {
		'name' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'Network\'s name' },
		'ssl' => { 'type' => 'b', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'desc' => 'Enable SSL for this network ?' },
		'server' => { 'type' => 'e' },
	},

	'user' => {
		'name' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'User\'s internal name ?' },
		'admin' => { 'type' => 'b', 'adv' => 0, 'default' => 'false',
			'optional' => 1,
			'desc' => 'Is user an admin ?' },
		'password' => { 'type' => 'p', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'Set a password for his bip account:' },
		'bip_use_notice' => { 'type' => 'b', 'adv' => 0, 'default' => 'false',
			'optional' => 1,
			'desc' => 'Do you prefer bip to use notices instead of privmsgs ?' },
		'ssl_check_mode' => { 'type' => 's', 'adv' => 1,
			'optional' => 1, 'default' => 'none',
			'desc' => 'Type of SSL servers certificate\'s checks' },
		'ssl_check_store' => { 'type' => 's', 'adv' => 1,
			'optional' => 1, 'default' => '',
			'desc' => 'Path to SSL servers\'s data storage' },
		'default_nick' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'User\'s default IRC nickname' },
		'default_user' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'User\'s default IRC username' },
		'default_realname' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'User\'s default IRC realname' },
		'backlog' => { 'type' => 'b', 'adv' => 0, 'default' => 'true',
			'optional' => 1,
			'depends' => 'log', 'depval' => 'true',
			'desc' => 'Do you want to activate backlog {play back logs} system ?' },
		'backlog_lines' => { 'type' => 'i', 'adv' => 0, 'default' => '10',
			'optional' => 1,
			'depends' => 'backlog', 'depval' => 'true',
			'desc' => 'How much line do you want bip to play back upon client connect' .
				" {0 => replay everything since backlog's last reset} ?" },
		'backlog_no_timestamp' => { 'type' => 'b', 'adv' => 0,
			'optional' => 1,
			'default' => 'false', 'depends' => 'backlog', 'depval' => 'true',
			'desc' => 'Disable timestamp in backlog ?' },
		'backlog_msg_only' => { 'type' => 'b', 'adv' => 0,
			'optional' => 1,
			'default' => 'false', 'depends' => 'backlog', 'depval' => 'true',
			'desc' => 'Only playback users messages {chan/priv}, no nick/join/... ?' },
		'backlog_always' => { 'type' => 'b', 'adv' => 0,
			'optional' => 1,
			'default' => 'false', 'depends' => 'backlog', 'depval' => 'true',
			'desc' => 'Always backlog {false means backlog pointers are reset after each backlog} ?' },
		'backlog_reset_on_talk' => { 'type' => 'b', 'adv' => 0,
			'optional' => 1,
			'default' => 'false', 'depends' => 'backlog', 'depval' => 'true',
			'desc' => 'Reset backlog each time an attached client "talks" ?' },
		'connection' => { 'type' => 'e' },

	},

	'connection' => {
		'name' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'Connection name (used by bip only)' },
		'network' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0, 'postdepends' => 'networks.$value',
			'desc' => 'Network to connect to' },
		'defid'	=> { 'type' => 'b', 'adv' => 0, 'default' => 'true',
			'optional' => 1, 'nosave' => 1,
			'desc' => 'Use default identity ?' },
		'nick' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'depends' => 'defid', 'depval' => 'false',
			'desc' => 'IRC nickname on this connection ?' },
		'user' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'depends' => 'defid', 'depval' => 'false',
			'desc' => 'IRC username on this connection ?' },
		'realname' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'depends' => 'defid', 'depval' => 'false',
			'desc' => 'IRC realname on this connection ?' },
		'password' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'desc' => 'IRC server\'s password ?' },
		'vhost' => { 'type' => 's', 'adv' => 1, 'default' => '',
			'optional' => 1,
			'desc' => 'Connect to IRC server from this specific IP address:' },
		'source_port' => { 'type' => 'i', 'adv' => 1, 'default' => '',
			'optional' => 1,
			'desc' => 'Connect to IRC server from this specific port:' },
		'follow_nick' => { 'type' => 'b', 'adv' => 0, 'default' => 'true',
			'optional' => 1,
			'desc' => 'Follow nicknames changes from clients to use upon reconnection (if false, bip\'ll use config nickname)' },
		'ignore_first_nick' => { 'type' => 'b', 'adv' => 0, 'default' => 'true',
			'optional' => 1,
			'desc' => 'Ignore nickname change sent by a client (first one only, upon client attach)' },
		'away_nick' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'desc' => 'Set nickname to this value when there\'s no more client attached:' },
		'no_client_away_msg' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'desc' => 'Set this away message when there\'s no more client attached:' },
		'on_connect_send' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'desc' => 'Send this raw message upon connection to IRC server' },
		'ssl_check_mode' => { 'type' => 's', 'adv' => 1,
			'optional' => 1, 'default' => '',
			'desc' => 'Type of SSL servers certificate\'s checks' },
		'channel' => { 'type' => 'e' },
	},

	'channel' => {
		'name' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'Channel name' },
		'key' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 1,
			'desc' => 'Channel key (optional)' },
	},

	'server' => {
		'host' => { 'type' => 's', 'adv' => 0, 'default' => '',
			'optional' => 0,
			'desc' => 'IRC server\'s IP address/hostname' },
		'port' => { 'type' => 'i', 'adv' => 0, 'default' => '6667',
			'optional' => 0,
			'desc' => 'IRC server\'s port' },
	}
);
my %optorder = (
	'global' => [
		'ip' ,
		'port' ,
		'client_side_ssl' ,
		'client_side_ssl_pem' ,
		'pid_file' ,
		undef,
		'log' ,
		'log_system' ,
		'log_sync_interval' ,
		'log_level' ,
		'log_root' ,
		'log_format' ,
	],

	'network' => [
		'name' ,
		'ssl' ,
		'server' ,
	],

	'user' => [
		'name' ,
		'password' ,
		'ssl_check_mode' ,
		'ssl_check_store' ,
		undef,
		'default_nick' ,
		'default_user' ,
		'default_realname' ,
		undef,
		'backlog' ,
		'backlog_lines' ,
		'backlog_no_timestamp' ,
		'backlog_msg_only' ,
		'backlog_always' ,
		'backlog_reset_on_talk' ,
		'connection' ,
	],

	'connection' => [
		'name' ,
		'network' ,
		'defid',
		'nick' ,
		'user' ,
		'realname' ,
		'password' ,
		undef,
		'vhost' ,
		'source_port' ,
		'follow_nick' ,
		'ignore_first_nick' ,
		'away_nick' ,
		'no_client_away_msg' ,
		'on_connect_send' ,
		'ssl_check_mode' ,
		'channel' ,
	],

	'channel' => [
		'name' ,
		'key' ,
	],

	'server' => [
		'host' ,
		'port' ,
	]
);

my $clear_string = `clear`;

sub myexit {
	warn("Error: $1");
	warn("Saving configuration...");
	save_config();
	warn("Don't worry, your configuration has been saved ;)");
	exit(1);
}

sub askOpt {
	my ($e, $curval, $mayempty) = @_;
	my ($o, $sel);

	$sel = (($curval ne undef) ? $curval : $e->{'default'});
	return $sel if ($mode eq 'normal' && $e->{'adv'} eq 1);

	while (1) {
		my $opt = (defined $e->{'optional'} && $e->{'optional'} eq 1 ?
				1 : 0);
		if ($e->{'type'} eq 'b') {
			$o = askbool($e->{'desc'}, $sel, 1);
		} elsif ($e->{'type'} eq 'p') {
			$o = askPass($e->{'desc'});
		} else {
			$o = askval($e->{'desc'}, $sel, ($mayempty && ($opt ne 1 ||
					$e->{'type'} eq 'i' ? 1 : undef)), 1);
		}
		if ($o eq undef && $opt eq 0) {
			print("This value is mandatory, please enter a value\n");
			next;
		}
		if ($e->{'type'} eq 'i' && $o !~ /^\d*$/) {
			print("We want a number here, please enter one\n");
			next;
		}
		last;
	}
	return $o;
}

sub align {
	my ($text, $num) = @_;
	my ($out, $pos, $orig);

	$orig = $text;
	while ($text ne '' || $text ne undef) {
		$num = 60 if (!$num);
		$pos = rindex($text, " ", 60);
		$out .= "\n" if ($out);
		$out .= substr($text, 0, $pos);
		$text = substr($text, $pos+1);
	}
	$out .= " ";

	return $out;
}

sub askbool {
	my ($text, $default, $star) = @_;
	 
	$text = "* $text" if $star;
	if ($default eq "true") {
		print align("$text [Y/n] ");
	} else {
		$default = "false";
		print align("$text [y/N] ");
	}

	
	while (my $l = <STDIN>) {
		chomp($l);
		if ($default eq "true" && $l =~ /^n$/i) {
			return "false";
		} elsif ($default eq "false" && $l =~ /^y$/i) {
			return "true";
		} elsif (!$default && $l eq '') {
			return undef;
		} else {
			return $default;
		}
	}
}

sub askPass {
	my ($text) = @_;
	
	which_bipmkpw();
	print("$text ? ");
	my $pass = `$bipmkpw`;
	chomp($pass);
	$pass =~ s/^Password:\s*\n?//si;
	chomp($pass);
	return $pass;
}

sub which_bipmkpw {
	my ($which);

	return if ($bipmkpw ne '' && -x "$bipmkpw");

	if (-x "/usr/bin/bipmkpw") {
		$bipmkpw = '/usr/bin/bipmkpw';
		return;
	}

	$which = `which bipmkpw`;
	if ($which ne '' && -x "$which") {
		$bipmkpw = $which;
		return;
	}

	while (!$bipmkpw || ! -x "$bipmkpw") {
		if ($bipmkpw ne '' && (! -f $bipmkpw || ! -x $bipmkpw)) {
			print("No exec permission: $bipmkpw\n");
		}
		$bipmkpw = askval("Please enter the path to bipmkpw:",
				undef, 1);
	}
	return;
}

sub askval {
	my ($text, $default, $skipblank, $star) = @_;
	
	$text .= " ";
	$text .= "[$default] " if ($default ne undef);
	$text = "* $text" if $star;
	print(align("$text"));
	while (my $l = <STDIN>) {
		chomp($l);
#		if ($default eq undef && !$skipblank && $l eq '') {
#			my $q = askbool("You've entered a blank value, do you want this field to be unset (if not, it'll be set to the empty string) ?", "true");
#			return undef if ($q eq 'true');
#		}
		return ($l ne '' ? $l : $default);
	}
}

sub checkDepends {
	my ($n, $v) = @_;
	return if (!exists($v->{'depends'}));

	my $d = $v->{'depends'};
	if (!exists($cf{'global'}->{$d})) {
		return "You cannot define `$n' since `$d' isn't defined";
	}
	if (exists($v->{'depval'}) &&
			$cf{'global'}->{$d} ne $v->{'depval'}) {
		return "You cannot define `$n' since `$d' isn't set to " .
				$v->{'depval'};
	}
}

sub loadConfig {
	my ($f) = @_;
	my ($fh, $data, $hr);

	$fh = new IO::File;
	$data = '';
	$fh->open($f) || return "Unable to open $f";
	while (<$fh>) {
		chomp();
		$data .= $_;
	}
	$fh->close;
	$hr = unserialize($data) || return "Invalid format in $f";
	%cf = %{$hr};
	$cf{'networks'} = [ values %{$cf{'networks'}} ];
	$cf{'users'} = [ values %{$cf{'users'}} ];

	sanitizeCompat(\%cf);
	foreach (@{$cf{'networks'}}) {
		$_->{'server'} = [ values %{$_->{'server'}} ];
	}
	foreach my $tcu (@{$cf{'users'}}) {
		$tcu->{'connection'} = [ values %{$tcu->{'connection'}} ];
		foreach my $tcc (@{$tcu->{'connection'}}) {
			$tcc->{'channel'} = [ values %{$tcc->{'channel'}} ];
		}
	}
	return "Config loaded from $f";
}

sub sanitizeCompat {
	my ($d) = @_;

	foreach (keys %$d) {
		if (ref($d->{$_}) eq 'ARRAY') {
			foreach my $d2 (@{$d->{$_}}) {
				sanitizeCompat($d2);
			}
		}
		$d->{$optcompat{$_}} = $d->{$_} if (defined $optcompat{$_});
	}
}

sub resetConfig {
	my $r = askbool("Do you want to reset current loaded configuration options, networks, users... ?", 'false');
	$r eq 'false' && return "Reset config aborted";

	%cf = ();
	-e "$sfile" || return "Configuration cleared";
	my $r = askbool("Do you want to delete saved configuration file $sfile too ?", 'false');
	if ($r eq 'true') {
		unlink($sfile) || return "Unable to remove file $sfile, current config has been cleared";
		return "Configuration cleared, saved-configuration file removed";
	}
	return "Configuration cleared";
}

sub setOptions {
	foreach my $n (@{$optorder{'global'}}) {
		if ($n eq undef) {
			print("\n");
			next;
		}
		my $e = $optdesc{'global'}->{$n};
		my $r = checkDepends($n, $e);
		if ($r) {
			print("$r\n") if ($DEBUG);
			$cf{'global'}->{$n} = undef;
			next;
		}
		$cf{'global'}->{$n} = askOpt($e, $cf{'global'}->{$n});
	}
	$global_done = 1;
	pause();
	return "Options have been set";
}

sub printOptions {
	my $cnt = 1;
	foreach my $n (@{$optorder{'global'}}) {
		next if (!$n);
		my $e = $optdesc{'global'}->{$n};
		next if ($e->{'type'} eq 'e' || $e->{'nosave'} eq 1);
		next if ($mode eq 'normal' && $e->{'adv'} eq 1);

		my $r = checkDepends($n, $e);
		if ($r) {
			printf('%02d.(%s - unset, missing dependency)'."\n", $cnt, $n);
		} elsif (exists($cf{'global'}->{$n})) {
			printf('%02d. %s = %s'."\n", $cnt, $n, $cf{'global'}->{$n}); 
		} else {
			printf('%02d. %s - unset'."\n", $cnt, $n);
		}
		$cnt++;
	}
	pause();
	return;
}

sub makeCert {
	my ($fh, $c, $o, $ou, $cn);
	$fh = new IO::File;
	$c = askval("SSL cert country :", undef, 1);
	$o = askval("SSL cert organisation :", "Sexy boys");
	$ou = askval("SSL cert organisational unit :", "Bip");
	$cn = askval("SSL cert common name :", "Bip");

	$fh->open("> $tmpcrt");
	return "Unable to write to $tmpcrt\n" if (!$fh);
	print $fh "HOME                    = .

[ req ]
distinguished_name      = dn
x509_extensions         = v3_bip
default_md              = sha1
prompt                  = no

[ dn ]
C=$c
O=$o
OU=$ou
CN=$cn

[ v3_bip ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always";

#	if (-e $certout) {
#		my @t = localtime(time);
#		my $ts = sprintf("%04d-%02d-%02d.%02d:%02d:%02d", 1900+$t[5], 1+$t[4], $t[3], $t[2], $t[1], $t[0]);
#		rename($certout, "$certout.$ts");
#		print "Existing $certout found, renamed to $certout.$ts\n";
#	}

	`openssl req -new -newkey rsa:4096 -x509 -days 365 -nodes -config "$tmpcrt" -out "$certout" -keyout "$certout"`;
	# TODO check command status
	`openssl x509 -subject -dates -fingerprint -noout -in "$certout"`;
	# TODO check command status
	$cert_done = 1;
	print "Certificate/key pair has been generated in $certout\n";
	unlink("$tmpcrt");
	pause();
	return "Certificate/key pair has been generated in $certout";
}

sub writeConfig {
	my ($f) = @_;
	my ($fh, $ts, @t);

	$ts = localtime(time);
	$fh = new IO::File;
	if (!$fh->open('> ' . $f)) {
		print("Unable to open $f for writing\n");
		return;
	}
	print $fh "# vim:ft=bip:ts=2\n";
	print $fh "# Auto-generated BIP IRC Proxy configuration $ts \n";
	print $fh "#\n";
	print $fh "### Global options\n";
	foreach my $k (keys(%{$cf{'global'}})) {
		next if ($cf{'global'}->{$k} eq undef);
		next if ($optdesc{'global'}->{$k}->{'nosave'} eq 1);
		my $t = $optdesc{'global'}->{$k}->{'type'};
		if ($t eq 's') {
			print $fh "$k = \"" . $cf{'global'}->{$k} . "\";\n";
		} else {
			print $fh "$k = " . $cf{'global'}->{$k} . ";\n";
		}
	}
	print $fh "\n";
	print $fh "### Networks\n";
	foreach my $e (@{$cf{'networks'}}) {
		my $out = printBlock("", 'network', $e, 1);
		print $fh $out;
	}
	print $fh "\n";
	print $fh "### Users\n";
	foreach my $e (@{$cf{'users'}}) {
		my $out = printBlock("", 'user', $e, 1);
		print $fh $out;
	}
	print $fh "\n";
	$fh->close;
	print("Configuration saved in $f\n");
	my $u = (exists($cf{'users'}) ? scalar @{$cf{'users'}}
		: 0);
	my $n = (exists($cf{'networks'}) ? scalar @{$cf{'networks'}}
		: 0);
	print "You haven't set global options\n" if (!$global_done);
	print "$u users defined, $n networks defined\n";
	print "The certificate/key pair is in $certout\n"
		if ($cert_done eq 1);
	print "Configuration has been generated in $CFILE\n";
		print "You have to rename all generated files to use them\n";
	return;
}

sub storeConfig {
	my ($f) = @_;
	my ($fh);

	$fh = new IO::File;
	$fh->open('> ' . $f) || return "Unable to open $f for writing";
	print $fh serialize(\%cf);
	$fh->close;
	return "Configuration stored in $f";
}

sub printBlock {
	my ($prefix, $name, $e, $level) = @_;
	my $out = '';

	fatal("Too much recursion levels ($level)") if ($level ge $maxlevel);
		
	$out .= $prefix . $name . " {\n";
	foreach my $k (@{$optorder{$name}}) {
		next if ($k eq undef);
		next if ($e->{$k} eq undef);
		next if ($optdesc{$name}->{$k}->{'nosave'} eq 1);
		my $t = $optdesc{$name}->{$k}->{'type'};
		if ($t eq 's' || $t eq 'p') {
			$out .= $prefix . "\t$k = \"" . $e->{$k} . "\";\n";
		} elsif (ref($e->{$k}) eq 'ARRAY') {
			foreach my $e2 (@{$e->{$k}}) {
				$out .= printBlock($prefix . "\t", $k, $e2, $level+1);
			}
		} else {
			$out .= $prefix .  "\t$k = " . $e->{$k} . ";\n";
		}
	}
	$out .= $prefix . "};\n\n";
	return $out;
}

sub addEntry {
	my ($section, $nopause) = @_;
	my ($e, $opts);

	$opts = $optdesc{$section};

	foreach my $n (@{$optorder{$section}}) {
		if ($n eq undef) {
			print("\n");
			next;
		}

		my $v = $optdesc{$section}->{$n};
		my $r = checkDepends($n, $v);
		if ($r) {
			$e->{$n} = undef;
			print("$r\n") if ($DEBUG);
			next;
		}
		if ($v->{'type'} eq 'e') {
			my $first = 1;
			do {
				if ($v->{'optional'} eq 1 || !$first) {
					my $a = askbool("Do you want to add a new $n ?", 'true');
					last if ($a eq 'false');
				}
				print("\nAdding a new $n :\n");
				my $e2 = addEntry($n, 1);
				if (ref($e->{$n}) eq 'ARRAY') {
					push(@{$e->{$n}}, $e2);
				} else {
					$e->{$n} = [ $e2 ];
				}
				$first = 0;
			} while (1);
		} else {
			$e->{$n} = askOpt($v);
		}
	}
	pause() if (!$nopause);
	return $e;
}

sub pause {
	my ($txt) = @_;

	$txt = "Press any key to continue" if (!$txt);
	print("\n" . $txt . "\n");
	<STDIN>;
}

sub printMenu {
	my ($mhead, $mopts, $mfoot, $mask) = @_;

	push(@{$mhead}, undef);
	if ($mode eq 'normal') {
		push(@{$mhead},
			"WARNING: non-advanced mode, some 'expert' " .
			"options'll be hidden !");
	} else {
		push(@{$mhead}, undef);
	}
	push(@{$mhead}, undef);
	print($clear_string);
	print("###########################################################" .
		"###################\n# ");
	print(join("\n# ", @{$mhead}));
	print("\n");
	print("\n");
	foreach my $n (sort {$a <=> $b} keys(%{$mopts})) {
		if ($mopts->{$n} eq undef) {
			print("\n");
			next;
		}
		printf('  %2d. %s%s', $n, $mopts->{$n}, "\n");
	}
	print("\n");
	print(join("\n", @{$mfoot}));
	print("\n");
	print("\n");
	return askval($mask, undef, 1);
}

sub printUsers {
	my ($txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $num, $warn, $act, $out);

	$mhead = [
		"Bip's user list",
	];
	$mfoot = [ $txt ];
	$mask = "Enter id of the user to edit ?";
	$mopts = { 0 => 'Return to main menu'};
	$mopts->{"0.5"} = undef;
	$num = 1;
	foreach my $n (@{$cf{'users'}}) {
		$mopts->{$num} = $n->{'name'} . ': ' .
			(scalar @{$n->{'connection'}}) . ' connections.';
		$num++;
	}

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act =~ /^\d+$/) {
		my $n = $cf{'users'};
		my $c = $num-1;
		if (($num-$act) le 0) {
			$out = "There are only $c users";
		} else {
			$out = printEditUser($act-1);
		}
	} else {
		$out = "Invalid user ID";
	}
	printUsers($out);
}

sub printNetworks {
	my ($txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $num, $warn, $act, $out);

	$mhead = [
		"Bip's network list",
	];
	$mfoot = [ $txt ];
	$mask = "Enter ID of the network to edit ?";
	$mopts = { 0 => 'Return to main menu'};
	$mopts->{"0.5"} = undef;
	$num = 1;
	foreach my $n (@{$cf{'networks'}}) {
		$mopts->{$num} = $n->{'name'} . ': ' . (scalar @{$n->{'server'}})
				. ' servers, SSL ' . ($n->{'ssl'} eq 'true' ?
						'enabled' : 'disabled');
		$num++;
	}

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act =~ /^\d+$/) {
		my $n = $cf{'networks'};
		my $c = $num-1;
		if (($num-$act) le 0) {
			$out = "There are only $c networks";
		} else {
			$out = printEditNetwork($act-1);
		}
	} else {
		$out = "Invalid network ID";
	}
	printNetworks($out);
}

sub addChannel {
	my ($uid, $cid) = @_;
	my ($cnt, @o, $n, $c, $name);

	return "Invalid user ID $uid"
		if ((scalar @{$cf{'users'}}) le $uid);
	$n = $cf{'users'}[$uid];
	return "Invalid connection ID $cid"
		if ((scalar @{$n->{'connection'}}) le $cid);
	my $e = addEntry('channel');
	if ($e) {
		push(@{$n->{'connection'}[$cid]->{'channel'}}, $e);
		return "Channel " . $e->{'name'} . " added";
	} else {
		return "Channel add failed";
	}

}

sub addServer {
	my ($id) = @_;

	return "Invalid network ID $id"
		if ((scalar @{$cf{'networks'}}) le $id);
	my $e = addEntry('server');
	if ($e) {
		push(@{$cf{'networks'}[$id]->{'server'}}, $e);
		return "Server " . $e->{'host'} . " added";
	} else {
		return "Server add failed";
	}
}

sub addConnection {
	my ($id) = @_;

	return "Invalid user ID $id"
		if ((scalar @{$cf{'users'}}) le $id);
	my $e = addEntry('connection');
	if ($e) {
		push(@{$cf{'users'}[$id]->{'connection'}}, $e);
		return "Connection " . $e->{'name'} . " added";
	} else {
		return "Connection add failed";
	}
}


sub deleteServer {
	my ($net, $sid) = @_;
	my ($sname, $ss, $cnt, @o);

	return "Invalid network ID $net"
		if ((scalar @{$cf{'networks'}}) le $net);
	$ss = $cf{'networks'}[$net]->{'server'};
	return "Invalid server ID $sid" if ((scalar @{$ss}) lt $sid);
	@o = ();
	$cnt = 0;
	foreach my $s (@{$ss}) {
		if ($sid ne $cnt) {
			push(@o, $s);
		} else {
			$sname = $s->{'host'};
		}
		$cnt++;
	}
	$cf{'networks'}[$net]->{'server'} = [ @o ];
	return "Server $sname removed";
}

sub delUser {
	my ($id) = @_;
	my ($cnt, @o, $name);

	return "Invalid user ID $id"
		if ((scalar @{$cf{'users'}}) le $id);
	$cnt = 0;
	@o = ();
	foreach my $n (@{$cf{'users'}}) {
		if ($id ne $cnt) {
			push(@o, $n);
		} else {
			$name = $n->{'name'};
		}
		$cnt++;
	}
	$cf{'users'} = [ @o ];
	return "User $name removed";
}

sub delNetwork {
	my ($id) = @_;
	my ($cnt, @o, $name);

	return "Invalid network ID $id"
		if ((scalar @{$cf{'networks'}}) le $id);
	$cnt = 0;
	@o = ();
	foreach my $n (@{$cf{'networks'}}) {
		if ($id ne $cnt) {
			push(@o, $n);
		} else {
			$name = $n->{'name'};
		}
		$cnt++;
	}
	$cf{'networks'} = [ @o ];
	return "Network $name removed";
}

sub deleteConn {
	my ($uid, $cid) = @_;
	my ($cnt, @o, $n, $name);

	return "Invalid user ID $uid"
		if ((scalar @{$cf{'users'}}) le $uid);
	$n = $cf{'users'}[$uid];
	return "Invalid connection ID $cid"
		if ((scalar @{$n->{'connection'}}) le $cid);

	$cnt = 0;
	@o = ();
	foreach my $n (@{$n->{'connection'}}) {
		if ($cid ne $cnt) {
			push(@o, $n);
		} else {
			$name = $n->{'name'};
		}
		$cnt++;
	}
	$cf{'users'}[$uid]->{'connection'} = [ @o ];
	return "Connection $name removed";
}

sub deleteChannel {
	my ($uid, $cid, $chid) = @_;
	my ($cnt, @o, $n, $c, $name);

	return "Invalid user ID $uid"
		if ((scalar @{$cf{'users'}}) le $uid);
	$n = $cf{'users'}[$uid];
	return "Invalid connection ID $cid"
		if ((scalar @{$n->{'connection'}}) le $cid);
	$c = $n->{'connection'}[$cid];
	return "Invalid channel ID $chid"
		if ((scalar @{$c->{'channel'}}) le $chid);

	$cnt = 0;
	@o = ();
	foreach my $n (@{$c->{'channel'}}) {
		if ($chid ne $cnt) {
			push(@o, $n);
		} else {
			$name = $n->{'name'};
		}
		$cnt++;
	}
	$cf{'users'}[$uid]->{'connection'}[$cid]->{'channel'} = [ @o ];
	return "Channel $name removed";
}


sub printEditConnOptions {
	my ($num, $num2, $txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $warn, $act, $out);
	my ($n, $c, $name, $sub, $cnt);

	return "Invalid user ID $num"
		if ((scalar @{$cf{'users'}}) le $num);
	$n = $cf{'users'}[$num];
	return "Invalid connection ID $num2"
		if ((scalar @{$n->{'connection'}}) le $num2);
	$c = $n->{'connection'}[$num2];
	$name = $c->{'name'};
	$mhead = [
		"Edit connection options $name/" . $n->{'name'},
	];
	$mfoot = [ $txt ];
	$mopts = { 0 => 'Return to connection ' . $name,
		"0.5" => undef,
	};
	$cnt = 1;
	my %oo = ();
	foreach my $s (@{$optorder{'connection'}}) {
		next if (!$s);
		next if ($optdesc{'connection'}->{$s}->{'type'} eq 'e');
		next if ($optdesc{'connection'}->{$s}->{'nosave'} eq 1);
		next if ($mode eq 'normal' &&
				$optdesc{'connection'}->{$s}->{'adv'} eq 1);
		$mopts->{$cnt} = "Change $s: ";
		$mopts->{$cnt} .= $c->{$s} if (defined $c->{$s});
		$oo{$cnt} = $s;
		$cnt++;
	}

	$act = int(printMenu($mhead, $mopts, $mfoot, $mask));
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act =~ /^\d+$/) {
		my $c = $cnt-1;
		if (($cnt-$act) le 0) {
			$out = "There are only $c options";
		} else {
			my $on = $oo{$act};
			$cf{'users'}[$num]->{'connection'}[$num2]->{$on} =
				askOpt($optdesc{'connection'}->{$on},
				$cf{'users'}[$num]->{'connection'}[$num2]->{$on});
			$out = "Option $on set";
			pause();
		}
	} else {
		$out = "Invalid option ID";
	}
	printEditConnOptions($num, $num2, $out);
}

sub printEditConnection {
	my ($num, $num2, $txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $warn, $act, $out);
	my ($n, $name, $sub, $cnt, $c);

	return "Invalid user ID $num"
		if ((scalar @{$cf{'users'}}) le $num);
	$n = $cf{'users'}[$num];
	return "Invalid connection ID $num2"
		if ((scalar @{$n->{'connection'}}) le $num2);
	$c = $n->{'connection'}[$num2];
	$name = $c->{'name'};
	$sub = $c->{'channel'};
	$mhead = [
		"Edit connection $name/" . $n->{'name'},
	];
	$mfoot = [ $txt ];
	$mask = "What do you want to do ?";
	$mopts = { 0 => 'Return to user ' . $n->{'name'},
		1 => 'Add a channel',
		2 => 'Edit options',
		3 => 'Remove this connection',
		"3.5" => undef,
	};
	$cnt = 4;
	foreach my $s (@{$sub}) {
		$mopts->{$cnt} = "Delete channel " . $s->{'name'};
		$mopts->{$cnt} .= '/' .	$s->{'key'} if (defined $s->{'key'} &&
				$s->{'key'} ne '');
		$cnt++;
	}

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act eq 1) {
		$out = addChannel($num, $num2);
	} elsif ($act eq 2) {
		return printEditConnOptions($num, $num2);
	} elsif ($act eq 3) {
		return deleteConn($num, $num2);
	} elsif ($act =~ /^\d+$/) {
		my $c = $cnt-4;
		if (($cnt-$act) le 0) {
			$out = "This connection has only $c channels";
		} else {
			$out = deleteChannel($num, $num2, $act-4);
		}
	} else {
		$out = "Invalid channel ID";
	}
	printEditConnection($num, $num2, $out);

}

sub printEditUserOptions {
	my ($num, $txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $warn, $act, $out);
	my ($n, $name, $sub, $cnt);

	return "Invalid user ID $num"
		if ((scalar @{$cf{'users'}}) le $num);
	$n = $cf{'users'}[$num];
	$name = $n->{'name'};
	$mhead = [
		"Edit user $name options",
	];
	$mfoot = [ $txt ];
	$mask = "What do you want to do ?";
	$mopts = { 0 => 'Return to user ' . $name,
		"0.5" => undef,
	};
	$cnt = 1;
	my %oo = ();
	foreach my $s (@{$optorder{'user'}}) {
		next if (!$s);
		next if ($optdesc{'user'}->{$s}->{'type'} eq 'e');
		next if ($optdesc{'user'}->{$s}->{'nosave'} eq 1);
		next if ($mode eq 'normal' &&
				$optdesc{'user'}->{$s}->{'adv'} eq 1);
		$mopts->{$cnt} = "Change $s: ";
		$mopts->{$cnt} .= $n->{$s} if (defined $n->{$s});
		$oo{$cnt} = $s;
		$cnt++;
	}

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act =~ /^\d+$/) {
		my $c = $cnt-1;
		if (($cnt-$act) le 0) {
			$out = "There are only $c options";
		} else {
			my $on = $oo{$act};
			$cf{'users'}[$num]->{$on} = askOpt(
				$optdesc{'user'}->{$on},
				$cf{'users'}[$num]->{$on});
			$out = "Option $on set";
			pause();
		}
	} else {
		$out = "Invalid option ID";
	}
	printEditUserOptions($num, $out);


}

sub printEditUser {
	my ($num, $txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $warn, $act, $out);
	my ($n, $name, $sub, $cnt);

	return "Invalid user ID $num"
		if ((scalar @{$cf{'users'}}) le $num);
	$n = $cf{'users'}[$num];
	$name = $n->{'name'};
	$sub = $n->{'connection'};
	$mhead = [
		"Edit user $name",
	];
	$mfoot = [ $txt ];
	$mask = "What do you want to do ?";
	$mopts = { 0 => 'Return to users list',
		1 => 'Add a connection',
		2 => 'Edit options',
		3 => 'Remove this user',
		"3.5" => undef,
	};
	$cnt = 4;
	foreach my $s (@{$sub}) {
		$mopts->{$cnt} = "Edit connection " . $s->{'name'};
		$cnt++;
	}

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act eq 1) {
		$out = addConnection($num);
	} elsif ($act eq 2) {
		return printEditUserOptions($num);
	} elsif ($act eq 3) {
		return delUser($num);
	} elsif ($act =~ /^\d+$/) {
		my $c = $cnt-4;
		if (($cnt-$act) le 0) {
			$out = "This user has only $c connections";
		} else {
			$out = printEditConnection($num, $act-4)
		}
	} else {
		$out = "Invalid connection ID";
	}
	printEditUser($num, $out);

}

sub printEditNetwork {
	my ($num, $txt) = @_;
	my ($mopts, $mhead, $mfoot, $mask, $warn, $act, $out);
	my ($n, $name, $sub, $cnt);

	return "Invalid network ID $num"
		if ((scalar @{$cf{'networks'}}) le $num);
	$n = $cf{'networks'}[$num];
	$name = $n->{'name'};
	$sub = $n->{'server'};
	$mhead = [
		"Edit network $name",
	];
	$mfoot = [ $txt ];
	$mask = "What do you want to do ?";
	$mopts = { 0 => 'Return to networks list',
		1 => 'Add a server',
		2 => 'Remove this network',
		"2.5" => undef,
	};
	$cnt = 3;
	foreach my $s (@{$sub}) {
		$mopts->{$cnt} = "Delete server: " . $s->{'host'} . '/' .
				$s->{'port'};
		$cnt++;
	}

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
		return;
	} elsif ($act eq 1) {
		$out = addServer($num);
	} elsif ($act eq 2) {
		return delNetwork($num);
	} elsif ($act =~ /^\d+$/) {
		my $c = $cnt-3;
		if (($cnt-$act) le 0) {
			$out = "This network has only $c servers";
		} else {
			$out = deleteServer($num, $act-3)
		}
	} else {
		$out = "Invalid server ID";
	}
	printEditNetwork($num, $out);
}

sub main_menu {
	my ($txt) = @_;
	my ($act, $out, $warn, $mopts, $mhead, $mfoot);
	my ($mhead, $mask);

	$mopts = {
		1	=> 'Set global options',
		2	=> 'Add a new network',
		3	=> 'Add a new user',
		3.5	=> undef,
		4	=> 'View global options',
		5	=> 'View/Edit/Delete networks',
		6	=> 'View/Edit/Delete users',
		7	=> 'Generate a server certificate/key pair',
		8	=> 'Switch to ' . invMode($mode) . ' mode',
		8.5	=> undef,
		10	=> 'Exit: store, write configuration and exit',
		11	=> 'Exit without saving',
		12	=> 'Store configuration for later use',
		12.5	=> undef,
		20	=> 'Reset config options',
		21	=> 'Load stored config',
		22	=> 'Parse and load current config (todo)',
	};
	$mhead = [
		"Welcome to bip configuration program.",
		"This script will help you build a configuration file",
	];
	$mfoot = [ $txt ];
	$mask = "What do you want to do ?";

	$act = printMenu($mhead, $mopts, $mfoot, $mask);
	print($clear_string);
	if ($act eq 0) {
	} elsif ($act eq 1) {
		$out = setOptions();
	} elsif ($act eq 2) {
		$out = addEntry('network');
		if ($out) {
			push(@{$cf{'networks'}}, $out);
			$out = "New network added";
		} else {
			$out = "Network add failed";
		}
	} elsif ($act eq 3) {
		$out = addEntry('user');
		if ($out) {
			push(@{$cf{'users'}}, $out);
			$out = "New user added";
		} else {
			$out = "User add failed";
		}
	} elsif ($act eq 4) {
		$out = printOptions();
	} elsif ($act eq 5) {
		$out = printNetworks();
	} elsif ($act eq 6) {
		$out = printUsers();
	} elsif ($act eq 7) {
		$out = makeCert();
	} elsif ($act eq 8) {
		$mode = invMode();
		$out = "Ok, configuration mode set to $mode";
	} elsif ($act eq 10) {
		print Dumper(\%cf) if ($DEBUG);
		$out = storeConfig($sfile);
		print ("$out\n") if ($out);
		writeConfig($CFILE);
		exit(0);
	} elsif ($act eq 11) {
		print Dumper(\%cf) if ($DEBUG);
		exit(0);
	} elsif ($act eq 12) {
		$out = storeConfig($sfile);
		print ("$out\n") if ($out);
		pause();
	} elsif ($act eq 20) {
		$out = resetConfig();
	} elsif ($act eq 21) {
		$out = loadConfig($sfile);
	}
	main_menu($out);
}

sub invMode {
	return ($mode eq 'advanced' ? 'normal' : 'advanced');
}

if (! -e $bipdir) {
	mkdir($bipdir) || fatal("Unable to create bip's dir `$bipdir'");
} elsif (! -d $bipdir) {
	fatal("Bip's dir `$bipdir' already exists and is not a directory");
} elsif (! -w $bipdir) {
	fatal("Bip's dir `$bipdir' already exists and is not writable");
}

main_menu();
#sets config backlog
#different user/nick/real ?


####################
# Serialize code, from Scott Hurring's serialize serialize module
# see http://hurring.com/ for more
# TODO maybe use Storable ?

sub serialize {
	my ($value) = @_;
	return serialize_value($value);
}

sub serialize_key {
	my ($value) = @_;
	my $s;
	
	# Serialize this as an integer
	if ($value =~ /^\d+$/) {
		# Kevin Haidl - PHP can only handle (((2**32)/2) - 1) 
		# before value must be serialized as a double
		if (abs($value) > ((2**32)/2-1)) {
			$s = "d:$value;";
		}
		else {
			$s = "i:$value;";
		}
	}
	
	# Serialize everything else as a string
	else {
		my $vlen = length($value);
		$s = "s:$vlen:\"$value\";";
	}
	
	return $s;
}

sub serialize_value {
	my ($value) = @_;
	my $s;
	
	$value = defined($value) ? $value : '';
	
	# This is a hash ref
	if ( ref($value) =~ /hash/i) {
		#The data in the hashref
		my $num = keys(%{$value});
		$s .= "a:$num:{";
		foreach my $k ( keys(%$value) ) {
			$s .= serialize_key( $k );
			$s .= serialize_value( $$value{$k} );
		}
		$s .= "}";
	}

	# This is an array ref
	elsif ( ref($value) =~ /array/i) {
		#The data in the arrayref
		my $num = @{$value};
		$s .= "a:$num:{";
		for (my $k=0; $k < @$value; $k++ ) {
			$s .= serialize_key( $k );
			$s .= serialize_value( $$value[$k] );
		}
		$s .= "}";
	}

	# This is a double
	# Thanks to Konrad Stepien <konrad@interdata.net.pl>
	# for pointing out correct handling of negative numbers.
	elsif ($value =~ /^\-?(\d+)\.(\d+)$/) {
		$s = "d:$value;";
	}

	# This is an integer
	elsif ($value =~ /^\-?\d+$/) {
		# Kevin Haidl - PHP can only handle (((2**32)/2) - 1) 
		# before value must be serialized as a double
		if (abs($value) > ((2**32)/2-1)) {
			$s = "d:$value;";
		}
		else {
			$s = "i:$value;";
		}
	}
	
	# This is a NULL value
	#
	# Only values of "\0" will be serialized as NULL
	# Empty strings are not NULL, they are simply empty strings.
	# @note Differs from v0.7 where string "NULL" was serialized as "N;"
	elsif ($value eq "\0")  {
		$s = "N;";
	}
	
	# Anything else is interpreted as a string
	else {
		my $vlen = length($value);
		$s = "s:$vlen:\"$value\";";
	}
	
	return $s;
}

sub unserialize {
	my ($string) = @_;
	return unserialize_value($string);
}

sub unserialize_value {
	my ($value) = @_;
	
	# Thanks to Ron Grabowski [ronnie (at) catlover.com] for suggesting
	# the need for single-value unserialize code
	
	# This is an array
	if ($value =~ /^a:(\d+):\{(.*)\}$/) {
		serialize_dbg("Unserializing array");
		
		my @chars = split(//, $2);
		
		# Add one extra char at the end so that the loop has one extra
		# cycle to hit the 'set' state and set the final value
		# Otherwise it'll terminate before setting the last value
		push(@chars, ';');
		
		return unserialize_sub({}, $1*2, \@chars);
	}
	
	# This is a single string
	elsif ($value =~ /^s:(\d+):(.*);$/) {
		serialize_dbg("Unserializing single string ($value)");
		#$string =~ /^s:(\d+):/;
		return $2;
		#return substr($string, length($1) + 4, $1);
	}
		
	# This is a single integer or double value
	elsif ($value =~ /^(i|d):(\-?\d+\.?\d+?);$/) {
		serialize_dbg("Unserializing integer or double ($value)");
		return $2
		#substr($string, 2) + 0;
	}
	
	# This is a NULL value
	# Thanks to Julian Jares [jjares at uolsinectis.com.ar]
	elsif ($value == /^N;$/i) {
		serialize_dbg("Unserializing NULL value ($value)");
		return "\0";
	}
	
	# This is a boolean
	# Thanks to Charles M Hall (cmhall at hawaii dot edu)
	elsif ($value =~/^b:(\d+);$/) {
		serialize_dbg("Unserializing boolean value ($value)");
		return $1;
	}
	
	# Invalid data
	else {
		serialize_dbg("Unserializing BAD DATA!\n($value)");
		die("Trying to unserialize bad data!");
		return '';
	}

}

sub unserialize_sub {
	my ($hashref, $keys, $chars) = @_;
	my ($temp, $keyname, $skip, $strlen);
	my $mode = 'normal';		#default mode
	
	serialize_dbg("> unserialize: $hashref, $keys, $chars");

	# Loop through the data char-by-char, eating them as we go...
	while ( defined(my $c = shift @{$chars}) )
	{
		serialize_dbg("\twhile [$mode] = $c (skip=$skip)");
	
		# Processing a serialized string
		# Format: s:length:"data"
		if ($mode eq 'string') {
			$skip = 1;	#how many chars should 'readstring' skip?
					#skip initial quote " at the beginning.
	
			#find out how many chars need to be read
			if ($c =~ /\d+/) {
				#get the length of string
				$strlen = $strlen . $c;
			}
	
			#if we already have a length, and see ':', we know that
			#the actual string is coming next (see format above)
	
			if (($strlen =~ /\d+/) && ($c eq ':')) {
				serialize_dbg("[string] length = $strlen");
				$mode = 'readstring';
			}
	
		}
		# Read $strlen number of characters into $temp
		elsif ($mode eq 'readstring') {
			next			if ($skip && ($skip-- > 0));
			$mode = 'set', next	if (!$strlen--);
	
			$temp .= $c;
	
		}
	
		# Process a serialized integer
		# Format: i:data
		elsif ($mode eq 'integer') {
			next 			if ($c eq ':');
			$mode = 'set', next	if ($c eq ';');
	
			# Grab the digits
			# Thanks to Konrad Stepien <konrad@interdata.net.pl>
			# for pointing out correct handling of negative numbers.
			if ($c =~ /\-|\d+/) {
				if ($c eq '-') {
					$temp .= $c unless $temp;
				} else {
					$temp .= $c;
				}
			}
		}
	
		# Process a serialized double
		# Format: d:data
		elsif ($mode eq 'double') {
			next 			if ($c eq ':');
			$mode = 'set', next	if ($c eq ';');
	
			# Grab the digits
			# Thanks to Konrad Stepien <konrad@interdata.net.pl>
			# for pointing out correct handling of negative numbers.
			if ($c =~ /\-|\d+|\./) {
				if ($c eq '-') {
					$temp .= $c unless $temp;
				} else {
					$temp .= $c;
				}
			}
		}
	
		# Process a serialized NULL value
		# Format: N
		# Thanks to Julian Jares [jjares at uolsinectis.com.ar]
		elsif ($mode eq 'null') {
	
			# Set $temp to something perl will recognize as null "\0"
			# Don't unserialize as an empty string, becuase PHP 
			# serializes empty srings as empty strings, not null.
			$temp = "\0";
	
			$mode = 'set', next;
		}
	
		# Process an array
		# Format: a:num_of_keys:{...}
		elsif ($mode eq 'array') {
	
			# Start of array definition, start processing it
			if ($c eq '{') {
	
				$temp = unserialize_sub( $$hashref{$keyname}, ($temp*2), $chars );

				# If temp is an empty array, change to {}
				# Thanks to Charles M Hall (cmhall at hawaii dot edu)
				if(!defined($temp) || $temp eq "") {
					$temp = {};
				}
				
				$mode = 'set', next;
			}
	
			# Reading in the number of keys in this array
			elsif ($c =~ /\d+/) {
				$temp = $temp . $c;
				serialize_dbg("array_length = $temp ($c)");
			}
		}
	
		# Do something with the $temp variable we read in.
		# It's either holding data for a key or a value.
		elsif ($mode eq 'set') {
	
			# The keyname has already been set, so that means
			# $temp holds the value
			if (defined($keyname)) {
				serialize_dbg("set [$keyname]=$temp");
	
				$$hashref{$keyname} = $temp;	
				
				# blank out keyname
				undef $keyname;
			}
	
			# $temp holds a keyname
			else {
				serialize_dbg("set KEY=$temp");
				$keyname = $temp;
			}
	
			undef $temp;
			$mode = 'normal';	# dont eat any chars
		}
	
		# Figure out what the upcoming value is and set the state for it.
		if ($mode eq 'normal') {
			# Blank out temp vars used by previous state.
			$strlen = $temp = '';
	
			if (!$keys) {
				serialize_dbg("return normally, finished processing keys");
				return $hashref;
			}
	
			# Upcoming information is integer
			if ($c eq 'i') {
				$mode = 'integer';
				$keys--;
			}
			# Upcoming information is a bool,
			# process the same as an integer
			if ($c eq 'b') {
				$mode = 'integer';
				$keys--;
			}
			# Upcoming information is a double
			if ($c eq 'd') {
				$mode = 'double';
				$keys--;
			}
			# Upcoming information is string
			if ($c eq 's') {
				$mode = 'string';
				$keys--;
			}
			# Upcoming information is array/hash
			if ($c eq 'a') {
				$mode = 'array';
				$keys--;
			}
			# Upcoming information is a null value
			if ($c eq 'N') {
				$mode = 'null';
				$keys--;
			}
		}

	} #while there are chars to process


	# You should never hit this point.
	# If you do hit this, it means that the code was expecting more 
	# characters than it was given.
	# Perhaps your data was unexpectedly truncated or mutilated?

	serialize_dbg("> unserialize_sub ran out of chars when it was expecting more.");
	die("unserialize_sub() ran out of characters when it was expecting more.");
	
	return 0;
}

sub serialize_dbg {
	my ($string) = @_;
	if ($SERIALIZE_DBG) {
		print $string ."\n";
	}
}