File: logic.rb

package info (click to toggle)
apt-listbugs 0.1.47
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,048 kB
  • sloc: ruby: 2,339; sh: 166; makefile: 64
file content (1536 lines) | stat: -rw-r--r-- 57,787 bytes parent folder | download
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
# encoding: UTF-8
#
# logic.rb: contains most logic from original apt-listbugs.
#
# Copyright (C) 2002       Masato Taruishi <taru@debian.org>
# Copyright (C) 2006-2008  Junichi Uekawa <dancer@debian.org>
# Copyright (C) 2007       Famelis George <famelis@otenet.gr>
# Copyright (C) 2008-2024  Francesco Poli <invernomuto@paranoici.org>
# Copyright (C) 2009-2010  Ryan Niebur <ryan@debian.org>
# Copyright (C) 2013       Google Inc
# Copyright (C) 2015       Michael Gold <michael@bitplane.org>
#
#  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.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License with
#  the Debian GNU/Linux distribution in file /usr/share/common-licenses/GPL-2;
#  if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

require 'getoptlong'
require 'debian'
require 'unicode'
require 'aptlistbugs/debian/bts'
require 'thread'
require 'tempfile'
require 'gettext'
require 'rss/maker'
require 'fcntl'
require 'aptlistbugs/debian/apt_preferences'
require 'open3'

include GetText


class AppConfig
  QUERYBTS = "/usr/bin/querybts"
  SENSIBLE_BROWSER = "/usr/bin/sensible-browser"
  XDG_OPEN = "/usr/bin/xdg-open"
  WWW_BROWSER = "/usr/bin/www-browser"

  def usage(stream = $stderr)
    stream.print _("Usage: "), File.basename($0),
      _(" [options] <command> [arguments]"),
      "\n",
      _("Options:\n"),
      # TRANSLATORS: the colons (:) in the following strings are vertically aligned, please keep their alignment consistent
      # TRANSLATORS: the \"all\" between quotes should not be translated
      sprintf(_(" -s <severities>  : Filter bugs by severities you want to see\n                    (or \"all\" for all)\n                    [%s].\n"), @severity.join(',')),
      _(" -T <tags>        : Filter bugs by tags you want to see.\n"),
      sprintf(_(" -S <states>      : Filter bugs by pending-state categories you want to see\n                    [%s].\n"), @stats.join(',')),
      _(" -B <bug#>        : Filter bugs by number, showing only the specified bugs.\n"),
      _(" -r <release>     : Filter bugs by distribution release, showing only the bugs\n                    that affect the specified release.\n"),
      _(" -D               : Show downgraded packages, too.\n"),
      sprintf(_(" -u <url>         : SOAP URL for Debian Bug Tracking System\n                    [%s].\n"), @soapurl),
      _(" -H <hostname>    : Hostname of Debian Bug Tracking System\n                    (for http, deprecated).\n"),
      _(" -p <port>        : Port number of the server\n                    (for http, deprecated).\n"),
      sprintf(_(" -P <priority>    : Pin-Priority value [%s].\n"), @pin_priority),
      _(" -E <title>       : Title of RSS output.\n"),
      _(" -q               : Don't display progress bar.\n"),
      _(" -C <apt.conf>    : Additional apt.conf file to use.\n"),
      _(" -F               : Automatically pin all buggy packages.\n"),
      _(" -N               : Never automatically pin packages.\n"),
      _(" -y               : Assume yes for all questions.\n"),
      _(" -n               : Assume no for all questions.\n"),
      _(" -a               : Assume the default reply for all questions.\n"),
      _(" -d               : Debug.\n"),
      _(" -h               : Display this help and exit.\n"),
      _(" -v               : Show version number and exit.\n"),
      _("Commands:\n"),
      _(" apt              : Apt mode.\n"),
      _(" list <pkg>..     : List bug reports of the specified packages.\n"),
      _(" rss <pkg>..      : List bug reports of the specified packages in RSS.\n"),
      _("See the manual page for the long options.\n")
  end

  def initialize
    @severity = ["critical", "grave", "serious"]
    @tag = nil
    @stats = ["pending", "forwarded", "pending-fixed", "fixed", "done"]
    # TRANSLATORS: the following six strings refer to a plural quantity of bugs
    # TRANSLATORS: please note that "Outstanding" means "unresolved", not "exceptional"
    @statmap = [["pending", _("Outstanding")],
                ["forwarded", _("Forwarded")],
                ["pending-fixed", _("Pending Upload")],
                ["fixed", _("Fixed in NMU")],
                ["absent", _("From other Branch")],
                ["done", _("Resolved in some Version")]]
    @fbugs = nil
    @distro = nil
    @other_releases = nil
    @show_downgrade = false
    @soapurl = "https://bugs.debian.org:443/cgi-bin/soap.cgi"
    @hostname = "bugs.debian.org"
    @port = 80
    @querystep = 200
    @parsestep = 200
    @quiet = false
    @command = nil
    @parser = nil
    @querybts = nil
    @browser = nil
    @cmd_prefix = ""
    o, e, s = Open3.capture3("logname")
    @ext_user = ""
    if s.success? && o != nil
      @ext_user = o.chomp
    end
    if @ext_user.empty?
      # if the user's login name cannot be determined,
      # act as if root privileges could not be dropped
      @ext_user = "root"
    end
    @ext_uid = "unknown uid"
    @parentcmd = Process.ppid

    @ignore_bugs = read_ignore_bugs("/etc/apt/listbugs/ignore_bugs")
    @system_ignore_bugs = read_ignore_bugs("/var/lib/apt-listbugs/ignore_bugs")
    @ignore_bugs.each { |bug|
      @system_ignore_bugs.add(bug, false)
    }
    @frontend = ConsoleFrontend.new( self )
    @pin_priority = "30000"
    @apt_conf = nil

    @yes = nil
    @default_reply = nil
    @force_pin = nil

    @arrow = "->"
    if Locale.charset == "UTF-8"
      @arrow = "→"
    end

    @debugfile = $stderr
  end

  attr_accessor :severity, :stats, :quiet, :title
  attr_accessor :show_downgrade, :tag, :fbugs, :querystep, :parsestep
  attr_accessor :frontend, :pin_priority, :yes, :ignore_regexp, :force_pin
  attr_accessor :default_reply
  attr_reader :command, :parser, :querybts, :ignore_bugs, :system_ignore_bugs
  attr_reader :browser, :arrow, :cmd_prefix, :ext_user, :ext_uid, :debugfile
  attr_reader :parentcmd, :distro, :other_releases

  def parse_options
    all_severities = ["critical","grave","serious","important","normal","minor","wishlist"]
    if /sev_list='(.*)'/ =~ `apt-config #{@apt_conf} shell sev_list AptListbugs::Severities`
      if $1 == "all"
        @severity = all_severities
      else
        @severity = $1.split(',')
      end
    end

    if /dr='(.*)'/ =~ `apt-config #{@apt_conf} shell dr AptListbugs::DistroRelease`
      @distro = $1
    end

    if /soap_url='(.*)'/ =~ `apt-config #{@apt_conf} shell soap_url AptListbugs::URL`
      @soapurl = $1
    end

    if /qb='(.*)'/ =~ `apt-config #{@apt_conf} shell qb AptListbugs::QueryStep`
      @querystep = $1.to_i if $1.to_i > 0
    end

    if /qb='(.*)'/ =~ `apt-config #{@apt_conf} shell qb AptListbugs::ParseStep`
      @parsestep = $1.to_i if $1.to_i > 0
    end

    opt_parser = GetoptLong.new
    opt_parser.set_options(['--help', '-h', GetoptLong::NO_ARGUMENT],
                           ['--severity', '-s', GetoptLong::REQUIRED_ARGUMENT],
                           ['--version', '-v', GetoptLong::NO_ARGUMENT],
                           ['--tag', '-T', GetoptLong::REQUIRED_ARGUMENT],
                           ['--stats', '-S', GetoptLong::REQUIRED_ARGUMENT],
                           ['--bugs', '-B', GetoptLong::REQUIRED_ARGUMENT],
                           ['--distro-release', '-r', GetoptLong::REQUIRED_ARGUMENT],
                           ['--show-downgrade', '-D', GetoptLong::NO_ARGUMENT],
                           ['--url', '-u', GetoptLong::REQUIRED_ARGUMENT],
                           ['--hostname', '-H', GetoptLong::REQUIRED_ARGUMENT],
                           ['--port', '-p', GetoptLong::REQUIRED_ARGUMENT],
                           ['--pin-priority', '-P', GetoptLong::REQUIRED_ARGUMENT],
                           ['--title', '-E', GetoptLong::REQUIRED_ARGUMENT],
                           ['--quiet', '-q', GetoptLong::NO_ARGUMENT],
                           ['--aptconf', '-C', GetoptLong::REQUIRED_ARGUMENT],
                           ['--force-pin', '-F', GetoptLong::NO_ARGUMENT],
                           ['--force-no-pin', '-N', GetoptLong::NO_ARGUMENT],
                           ['--force-yes', '-y', GetoptLong::NO_ARGUMENT],
                           ['--force-no', '-n', GetoptLong::NO_ARGUMENT],
                           ['--force-default', '-a', GetoptLong::NO_ARGUMENT],
                           ['--debug', '-d', GetoptLong::NO_ARGUMENT]
                           );

    begin
      opt_parser.each_option { |optname, optargs|
        case optname
        when '--help'
          usage($stdout)
          exit 0
        when '--version'
          puts $VERSION
          exit 0
        when '--severity'
          case optargs
          when "all"
            @severity = all_severities
          else
            @severity = optargs.split(',')
          end
        when '--tag'
          @tag = optargs.split(',')
        when '--stats'
          @stats = optargs.split(',')
        when '--bugs'
          @fbugs = optargs.split(',')
        when '--distro-release'
          @distro = optargs
        when '--show-downgrade'
          @show_downgrade = true
        when '--url'
          @soapurl = optargs
        when '--hostname'
          @hostname = optargs
          @soapurl = "http://#{@hostname}:#{@port}/cgi-bin/soap.cgi"
          # TRANSLATORS: "W: " is a label for warnings; you may translate it with a suitable abbreviation of the word "warning"
          $stderr.puts _("W: ") + sprintf(_("%s IS DEPRECATED. USE --url INSTEAD"), "--hostname")
        when '--port'
          @port = optargs.to_i
          @soapurl = "http://#{@hostname}:#{@port}/cgi-bin/soap.cgi"
          $stderr.puts _("W: ") + sprintf(_("%s IS DEPRECATED. USE --url INSTEAD"), "--port")
        when '--pin-priority'
          @pin_priority = optargs
        when '--title'
          @title = optargs
        when '--quiet'
          @quiet = true
        when '--aptconf'
          @apt_conf = " -c " + optargs
        when '--debug'
          $DEBUG = 1
        when '--force-yes'
          @yes = true
          @default_reply = nil
        when '--force-no'
          @yes = false
          @default_reply = nil
        when '--force-default'
          @yes = nil
          @default_reply = true
        when '--force-pin'
          @force_pin = true
        when '--force-no-pin'
          @force_pin = false
        end
      }
    rescue GetoptLong::AmbiguousOption, GetoptLong::NeedlessArgument,
        GetoptLong::MissingArgument, GetoptLong::InvalidOption
      usage
      exit 1
    end

    if $DEBUG
      if /df='(.*)'/ =~ `apt-config #{@apt_conf} shell df AptListbugs::DebugFile`
        df = $1
        begin
          @debugfile = File.open(df, "w")
        rescue Errno::EACCES
          $stderr.puts _("W: ") + sprintf(_("Cannot write to %s"), df)
          @debugfile = $stderr
        end
      end
    end

    if ! $stdout.isatty
      @quiet = true
      @yes = false if @yes.nil?
      @force_pin = true if @force_pin.nil?
    else
      @force_pin = false if @force_pin.nil?
    end

    # warn the user about unknown (possibly misspelled) severities
    (@severity - all_severities).each { |unrec|
      $stderr.puts _("W: ") + sprintf(_("Unrecognized severity '%s' will be ignored by the Debian BTS."), unrec)
    }

    @title = sprintf(_("Bugs of severity %s"), @severity.join(', ')) if ! @title

    @distro = nil if @distro == "ANY"
    if ! @distro.nil?
      case @distro
      when "unstable"
        o, e, s = Open3.capture3("distro-info --codename --devel")
        if s.success?
          @distro = o.chomp
        end
      when "testing", "stable", "oldstable"
        o, e, s = Open3.capture3("distro-info --codename --#{@distro}")
        if s.success?
          @distro = o.chomp
        end
      end

      # abort on unknown (possibly misspelled) distribution release
      c = "distro-info --codename --all"
      o, e, s = Open3.capture3(c)
      if s.success?
        @other_releases = o.split("\n")
        if @other_releases.delete(@distro).nil?
          $stderr.puts _("E: ") + sprintf(_("Unrecognized distribution release '%s'."), @distro)
          exit 1
        end
      else
        $stderr.puts _("E: ") + sprintf(_("Cannot determine list of distribution releases with command %s"), c)
        exit 1
      end

      @debugfile.puts "Distribution release: #{@distro}" if $DEBUG
      @debugfile.puts "Other known releases: #{@other_releases.join(",")}" if $DEBUG
    end

    # http_proxy sanity check
    if ENV["HTTP_PROXY"] != nil && ENV["http_proxy"] == nil
      $stderr.puts _("W: ") + _("sanity check failed: environment variable http_proxy is unset and HTTP_PROXY is set.")
    end

    # enable proxy for SOAP
    if ENV["http_proxy"] != nil && ENV["soap_use_proxy"] != "on"
      ENV["soap_use_proxy"] = "on"
    end

    # proxy settings in apt.conf
    if /http_proxy='(.*)'/ =~ `apt-config #{@apt_conf} shell http_proxy acquire::http::proxy`
      @debugfile.puts "proxy configuration from apt.conf: #{$1}" if $DEBUG
      if $1 == 'DIRECT' || $1 == ''
        @debugfile.puts "Disabling proxy due to DIRECT, or empty string" if $DEBUG
        ENV.delete("http_proxy")
        ENV.delete("soap_use_proxy")
      else
        ENV["http_proxy"] = $1
        ENV["soap_use_proxy"] = "on"
      end
    end
    if /proxy_detect='(.*)'/ =~ `apt-config #{@apt_conf} shell proxy_detect acquire::http::proxy-auto-detect`
      @debugfile.puts "auto proxy detect command from apt.conf: #{$1}" if $DEBUG
      if FileTest.executable?("#{$1}")
        detected_proxy = `#{$1}`.chomp
        @debugfile.puts "auto detected proxy: #{detected_proxy}" if $DEBUG
        if /^http/ =~ detected_proxy
          ENV["http_proxy"] = detected_proxy
          ENV["soap_use_proxy"] = "on"
        else
          @debugfile.puts "Ignoring auto detected proxy not beginning with 'http'" if $DEBUG
        end
      else
        $stderr.puts _("W: ") + sprintf(_("Cannot execute auto proxy detect command %s"), $1)
      end
    end
    if /http_proxy='(.*)'/ =~ `apt-config #{@apt_conf} shell http_proxy acquire::http::proxy::bugs.debian.org`
      @debugfile.puts "proxy configuration from apt.conf, specific for bugs.debian.org: #{$1}" if $DEBUG
      if $1 == 'DIRECT'
        @debugfile.puts "Disabling proxy due to DIRECT" if $DEBUG
        ENV.delete("http_proxy")
        ENV.delete("soap_use_proxy")
      else
        ENV["http_proxy"] = $1
        ENV["soap_use_proxy"] = "on"
      end
    end

    # command
    command = ARGV.shift
    case command
    when nil
      $stderr.puts _("E: ") + _("You need to specify a command.")
      usage
      exit 1
    when "list"
      @command = "list"
    when "apt"
      @command = "apt"
    when "rss"
      @command = "rss"
    else
      $stderr.puts _("E: ") + _("Unknown command ") +  "'#{command}'."
      usage
      exit 1
    end

    @parser =
      Debian::BTS::Parser::SoapIndex.new(@soapurl, @debugfile)

    if FileTest.executable?("#{QUERYBTS}")
      @querybts = QUERYBTS
    end

    if FileTest.executable?("#{SENSIBLE_BROWSER}")
      @browser = SENSIBLE_BROWSER
    elsif FileTest.executable?("#{XDG_OPEN}")
      @browser = XDG_OPEN
    elsif FileTest.executable?("#{WWW_BROWSER}")
      @browser = WWW_BROWSER
    end

    if Process.euid == 0
      # running as root
      # external programs are better run after dropping root privileges
      # and without accessing the graphical environment
      if @ext_user != "root"
        # running as root, after becoming root (with "su -", "sudo", ...)
        # the original user name is @ext_user
        # use setpriv to drop root privileges
        @cmd_prefix = "env -u DISPLAY -u XAUTHORITY setpriv --reuid #{@ext_user} --init-groups "
      end
    else
      # not running as root
      # external programs may be run as the effective userid
      o, e, s = Open3.capture3("whoami")
      @ext_user = ""
      if s.success? && o != nil
        @ext_user = o.chomp
      end
      # if the effective user name cannot be determined, leave it empty
    end
    o, e, s = Open3.capture3("id -u #{@ext_user}")
    if s.success? && o != nil
      @ext_uid = o.chomp
    end

    @debugfile.puts "PPID is #{@parentcmd}" if $DEBUG
    begin
      require 'sys/proctable'
      @parentcmd = Sys::ProcTable.ps(pid: @parentcmd).ppid
      @parentcmd = Sys::ProcTable.ps(pid: @parentcmd).cmdline
    rescue LoadError
      @parentcmd = nil
    end

    if /ignore_regexp='(.*)'/ =~ `apt-config #{@apt_conf} shell ignore_regexp AptListbugs::IgnoreRegexp`
      @ignore_regexp = $1
    end
  end

  # return the descriptive name for a status
  def statmap(stat)
    r=@statmap.assoc(stat)
    if r then
      r[1]
    else
      stat
    end
  end

  def read_ignore_bugs(path)
    ignore_bugs = IgnoreBugs.new(path)
  end
end

class IgnoreBugs < Array

  @@path_mutex = {}

  def initialize(path)
    super()
    @path = path
    @@path_mutex[path] = Mutex.new if @@path_mutex[path] == nil

    if FileTest.exist?(path)
      begin
        open(path).each { |line|
          bug = line.encode(Encoding.default_external, undef: :replace, invalid: :replace)
          if /^\s*#/ =~ bug
            next
          end
          if /^\s*(\S+)/ =~ bug
            self << $1
          end
        }
      rescue Errno::EACCES
        # read-access is not possible, warn the user that the
        # file won't be taken into account
        $stderr.puts _("W: ") + sprintf(_("Cannot read from %s"), @path)
      end
    end

    @gavewritewarning = nil
  end

  def add(entry, write=true)
    if write == true
      @@path_mutex[@path].synchronize {
        begin
          open(@path, "a") { |file|
            file.puts entry
          }
        rescue Errno::EACCES
          # write-access is not possible, warn the user that the
          # file won't be updated
          if @gavewritewarning.nil?
            $stderr.puts _("W: ") + sprintf(_("Cannot write to %s"), @path)
            @gavewritewarning = true
          end
        end
      }
    end
    self << entry
  end

end

class Viewer

  def initialize(config)
    @config = config
  end

  class SimpleViewer < Viewer

    def initialize(config)
      super(config)
      @bugmap = {}
      @hold_pkg_keys = []
      @dodged_bugnums = []
      @ignored_bugnums = []
      @pref_str = ""
    end

    def view(new_pkgs, cur_pkgs, bugs)
      if display_bugs(bugs, new_pkgs.keys, cur_pkgs, new_pkgs) == false
        return true
      end

      if @config.command == "list"
        return true
      end

      answer = "n"
      while true
        ask_str = _("Are you sure you want to install/upgrade the above packages?").dup
        if @hold_pkg_keys.empty? && @dodged_bugnums.empty?
          ask_str << " [Y/n/?/...]"
        else
          ask_str << " [N/?/...]"
        end
        if @config.force_pin
          a = "p"
        else
          if @config.default_reply
            a = ""
          else
            if @config.yes.nil?
              a = @config.frontend.ask ask_str
            else
              a = "y" if @config.yes
              a = "n" if ! @config.yes
            end
          end
        end
        if a.nil?
          a = "got nil!"
          @config.frontend.puts ""
        end
        if a == ""
          if @hold_pkg_keys.empty? && @dodged_bugnums.empty?
            answer = "y"
          else
            answer = "n"
          end
        else
          answer = a.downcase.strip
        end
        case answer

        when "y"
          if @hold_pkg_keys.empty? && @dodged_bugnums.empty?
            save(bugs)
            return true
          end

        when "n"
          save(bugs)
          return false

        when /^(#|b)?(\d+)$/
          if @config.querybts != nil
            bugnum = nil
            if $1 == "b"
              if @bugmap.has_key?($2)
                bugnum = @bugmap[$2]
              else
                @config.frontend.puts sprintf(_("%s is unknown"), "b#{$2}")
              end
            else
              bugnum = $2
            end
            if ! bugnum.nil?
              @config.debugfile.puts "Invoking querybts for ##{bugnum}" if $DEBUG
              querybtscommandline = "#{@config.cmd_prefix}#{@config.querybts} -u text #{bugnum}"
              if system(querybtscommandline)
                @config.debugfile.puts "successfully invoked querybts" if $DEBUG
              else
                $stderr.puts _("W: ") + _("Failed to invoke querybts.")
                $stderr.puts " #{querybtscommandline}"
              end
            end
          else
            @config.frontend.puts sprintf(_("You must install the reportbug package to be able to do this"))
          end

        when /^i\s+(b)?(\d+)$/
          bugnum = nil
          if $1 == "b"
            if @bugmap.has_key?($2)
              bugnum = @bugmap[$2]
            else
              @config.frontend.puts sprintf(_("%s is unknown"), "b#{$2}")
            end
          else
            bugnum = $2
          end
          if ! bugnum.nil?
            bug = bugs.extract(bugnum)
            bug = @config.parser.parse_bug(bugnum) if bug.nil?
            if bug.nil?
              @config.frontend.puts sprintf(_("%s is unknown to the BTS"), bugnum)
            else
              bugs_to_ignore = [bugnum]
              bugs_to_ignore.concat(bug.mergeids)
              bugs_to_ignore.each { |bugnum|
                if ! @config.system_ignore_bugs.include?(bugnum) &&
                   ! @ignored_bugnums.include?(bugnum)
                  @ignored_bugnums << bugnum
                  # TRANSLATORS: "ignored" refers to one singular bug
                  @config.frontend.puts sprintf(_("%s ignored"), bugnum)
                else
                  # TRANSLATORS: "ignored" refers to one singular bug
                  @config.frontend.puts sprintf(_("%s already ignored"), bugnum)
                end
              }
            end
          end

        when "i"
          bugs.filter_out(@dodged_bugnums+@ignored_bugnums).each { |bug|
            if ! @hold_pkg_keys.include?(bug.pkg_key)
              if ! @config.system_ignore_bugs.include?(bug.bug_number) && ! @ignored_bugnums.include?(bug.bug_number)
                @ignored_bugnums << bug.bug_number
                @config.frontend.puts sprintf(_("%s ignored"), bug.bug_number)
              end
            end
          }

        when "r"
          display_bugs(bugs, new_pkgs.keys, cur_pkgs, new_pkgs)

        when /^p\s+(.+)$/
          pkg_keys = $1.split(/\s+/)
          # TRANSLATORS: %{plist} is a comma-separated list of %{npkgs} packages to be pinned.
          if @config.frontend.yes_or_no? ngettext(
           "The following %{npkgs} package will be pinned:\n %{plist}\nAre you sure?",
           "The following %{npkgs} packages will be pinned:\n %{plist}\nAre you sure?",
           pkg_keys.size) % {:npkgs => pkg_keys.size,
                             :plist => pkg_keys.join(', ')}
            h, e = pinned(pkg_keys, cur_pkgs, bugs)
            @hold_pkg_keys.concat(h) if h != nil
          end

        when /^d\s+(.+)$/
          bug_names = $1.split(/\s+/)
          bugnames = []
          bugnums  = []
          bug_names.each { |name|
            bugnum = nil
            if /^(b)?(\d+)$/ =~ name
              if $1 == "b"
                bugnum = @bugmap[$2] if @bugmap.has_key?($2)
              else
                bugnum =         $2  if @bugmap.has_value?($2)
              end
            end
            if bugnum.nil?
              @config.frontend.puts sprintf(_("%s is unknown"), "'#{name}'")
            else
              bugnames << name
              bugnums  << bugnum
              bug = bugs.extract(bugnum)
              bugnums.concat(bug.mergeids) unless bug.nil?
            end
          }
          feared_bugs = bugs.filter_out(@dodged_bugnums+@ignored_bugnums).filter_in(bugnums)
          pkgs = {}
          feared_bugs.each { |bug|
            pkgs[bug.pkg_key] = 1 unless @hold_pkg_keys.include?(bug.pkg_key)
          }
          if pkgs.size != 0
            # TRANSLATORS: %{blist} is a comma-separated list of %{nbugs} bugs to be dodged.
            if @config.frontend.yes_or_no? ngettext(
             "The following %{nbugs} bug will be dodged:\n %{blist}\nAre you sure?",
             "The following %{nbugs} bugs will be dodged:\n %{blist}\nAre you sure?",
             bugnames.size) % {:nbugs => bugnames.size,
                               :blist => bugnames.join(', ')}
              h, e = pinned(pkgs.keys, cur_pkgs, feared_bugs)
              @dodged_bugnums.concat(e) if e != nil
            end
          end

        when "c"
          @config.debugfile.puts bugs if $DEBUG
          display_bugs_as_html(bugs, cur_pkgs, new_pkgs, "c")

        when "w"
          @config.debugfile.puts bugs if $DEBUG
          if @config.browser != nil
            display_bugs_as_html(bugs, cur_pkgs, new_pkgs)
          else
            @config.frontend.puts sprintf(_("You must install a web browser package to be able to do this"))
          end

        when "p"
          pkgs = {}
          prev_pinned_pkgs = {}
          begin
            p = Debian::AptPreferences.new
            p.pins.each { |pin|
              prev_pinned_pkgs[pin["Package"]] = 1
            }
          rescue
            # something went wrong while parsing preferences: assume no pins
          end
          filtered_bugs = bugs.filter_out(@dodged_bugnums+@ignored_bugnums)
          filtered_bugs.each { |bug|
            if ! prev_pinned_pkgs.has_key?(bug.pkg_key)
              pkgs[bug.pkg_key] = 1 unless @hold_pkg_keys.include?(bug.pkg_key)
            end
          }
          if pkgs.size != 0
            @config.yes = true if @config.force_pin
            if @config.frontend.yes_or_no? ngettext(
             "The following %{npkgs} package will be pinned:\n %{plist}\nAre you sure?",
             "The following %{npkgs} packages will be pinned:\n %{plist}\nAre you sure?",
             pkgs.size) % {:npkgs => pkgs.size,
                           :plist => pkgs.keys.join(', ')}
              h, e = pinned(pkgs.keys, cur_pkgs, bugs)
              @hold_pkg_keys.concat(h) if h != nil
            end
            save(bugs) if @config.force_pin
          else
            @config.frontend.puts sprintf(_("All selected packages are already pinned. Ignoring %s command."), answer)
          end
          return false if @config.force_pin

        when "u"
          if @hold_pkg_keys.empty? && @dodged_bugnums.empty? && @ignored_bugnums.empty?
            @config.frontend.puts sprintf(_("There are no dodge/pin/ignore operations to undo. Ignoring %s command."), answer)
          else
            if @config.frontend.yes_or_no?(_("All the dodge/pin/ignore operations will be undone.\nAre you sure?"))
              @hold_pkg_keys = []
              @dodged_bugnums = []
              @ignored_bugnums = []
              @pref_str = ""
              display_bugs(bugs, new_pkgs.keys, cur_pkgs, new_pkgs)
            end
          end

        else
          if @hold_pkg_keys.empty? && @dodged_bugnums.empty?
            @config.frontend.puts "" +
              # TRANSLATORS: the dashes (-) in the following strings are vertically aligned, please keep their alignment consistent
              _("     y     - continue the APT installation.\n")
          end
          @config.frontend.puts "" +
            _("     n     - stop the APT installation.\n")
          if @config.querybts != nil
            @config.frontend.puts "" +
            # TRANSLATORS: %{prog} is the name of a program, %{user} is a user name.
              _("   <num>   - query the specified bug number\n             (uses %{prog} as user %{user}).\n") %
                {:prog => File.basename(@config.querybts),
                 :user => @config.ext_user} +
              _("  #<num>   - same as <num>.\n") +
              _("   b<id>   - same as <num>, but query the bug identified by <id>.\n")
          end
          @config.frontend.puts "" +
            _("     r     - redisplay bug lists.\n") +
            _("     c     - compose bug lists in HTML.\n")
          if @config.browser != nil
            @config.frontend.puts _("     w     - display bug lists in HTML\n             (uses %{prog} as user %{user}).\n") %
              {:prog => File.basename(@config.browser),
               :user => @config.ext_user}
          end
          @config.frontend.puts "" +
            _(" d <num>.. - dodge bugs <num> by pinning affected packages\n             (restart APT session to enable).\n") +
            _(" d b<id>.. - dodge bugs identified by <id> by pinning affected packages\n             (restart APT session to enable).\n") +
            _(" p <pkg>.. - pin packages <pkg>\n             (restart APT session to enable).\n") +
            _(" p         - pin all the above packages\n             (restart APT session to enable).\n") +
            _(" i <num>   - mark bug number <num> as ignored.\n") +
            _(" i b<id>   - mark the bug identified by <id> as ignored.\n") +
            _(" i         - mark all the above bugs as ignored.\n") +
            _("     u     - undo all the dodge/pin/ignore operations done so far.\n") +
            _("     ?     - print this help.\n")
        end
      end
    end

    def save(bugs)
      if @pref_str != ""
        filename = "/etc/apt/preferences.d/apt-listbugs"
        begin
          File.open(filename, "a") { |io| io.puts @pref_str }
        rescue Errno::EACCES
          # write-access is not possible, warn the user that the
          # file won't be updated
          $stderr.puts _("W: ") + sprintf(_("Cannot write to %s"), filename)
        end
      end
      @ignored_bugnums.each { |bugnum|
        bug = bugs.extract(bugnum)
        bug = @config.parser.parse_bug(bugnum) if bug.nil?
        if ! bug.nil?
          @config.system_ignore_bugs.add(bug)
          @config.system_ignore_bugs.add(bugnum)
        end
      }
    end

    def bugs_of_pkg( bugs, pkg_key )
      b = []
      bugs.each { |bug|
        b << bug if bug.pkg_key == pkg_key
      }
      b
    end

    def pinned(pkg_keys, cur_pkgs, bugs)
      holdstr = ""
      pinned_pkg_keys = []
      explanation_bugs = []
      notheld_pkg_keys = pkg_keys - @hold_pkg_keys
      notheld_pkg_keys.each { |pkg_key|
        my_bugs = bugs_of_pkg(bugs.filter_out(@dodged_bugnums+@ignored_bugnums),
                              pkg_key)
        if my_bugs.size > 0 || @config.frontend.yes_or_no?(sprintf(
         _("None of the above bugs is assigned to package %s\nAre you sure you want to pin it?"),
         pkg_key))
          pin_ver = "0.no.version"
          pin_pri = @config.pin_priority
          if cur_pkgs[pkg_key] != nil
            pin_ver = cur_pkgs[pkg_key]['version']
          else
            pin_ver = "*"
            pin_pri = "-30000"
          end
          pinned_pkg_keys << pkg_key
          holdstr << "\nExplanation: Pinned by apt-listbugs at #{Time.now}"
          holdstr << "\nExplanation: Pinning requested by #{@config.ext_user} (#{@config.ext_uid})"
          holdstr << " during command: #{@config.parentcmd}" if ! @config.parentcmd.nil?
          my_bugs.each { |bug|
            holdstr << "\nExplanation:   ##{bug.bug_number}: #{bug.desc}"
            explanation_bugs << bug.bug_number
          }
          holdstr << "\nPackage: #{pkg_key}\nPin: version #{pin_ver}"
          holdstr << "\nPin-Priority: #{pin_pri}\n"
        end
      }
      @config.debugfile.puts holdstr if $DEBUG
      if holdstr != ""
        @pref_str << holdstr
        # TRANSLATORS: %{packgl} is a comma-separated list of %{npackg} packages.
        @config.frontend.puts ngettext(
         "Restart APT session to enable pinning for the following %{npackg} package:\n %{packgl}\n",
         "Restart APT session to enable pinning for the following %{npackg} packages:\n %{packgl}\n",
         pinned_pkg_keys.size) % {:npackg => pinned_pkg_keys.size,
                                  :packgl => pinned_pkg_keys.join(', ')}
        return pinned_pkg_keys, explanation_bugs
      end
      return nil
    end

    def display_bugs(bugs, pkg_keys, cur_pkgs, new_pkgs)
      # routine to display every bug that is available and relevant

      filtered_bugs = bugs.filter_out(@dodged_bugnums+@ignored_bugnums)
      notheld_pkg_keys = pkg_keys - @hold_pkg_keys
      bugs_statistics = {}
      @config.stats.each { |stat|
        @config.severity.each { |severity|
          notheld_pkg_keys.each { |pkg_key|
            p_bug_numbers = []
            bug_exist = 0
            bugs_statistics[pkg_key] = 0 unless bugs_statistics[pkg_key]
            filtered_bugs.each_by_category(pkg_key, severity, stat) { |bug|
              next if p_bug_numbers.include?(bug.bug_number)
              bugs_statistics[pkg_key] += 1
              p_bug_numbers << bug.bug_number
              if bug_exist == 0
                # TRANSLATORS: %{sevty} is the severity of some of the bugs found for package %{packg}.
                buf = _("%{sevty} bugs of %{packg} (") % {:sevty => severity,
                                                          :packg => pkg_key}
                buf += "#{cur_pkgs[pkg_key]['version']} " if cur_pkgs[pkg_key] != nil
                buf += "#{@config.arrow} #{new_pkgs[pkg_key]['version']}) <#{@config.statmap(bug.stat)}>"
                @config.frontend.puts buf
                bug_exist = 1
              end
              if bug.id.nil?
                bug.id = @bugmap.length.next
                @bugmap[bug.id.to_s] = bug.bug_number
              end
              bug_str = " b#{bug.id} - ##{bug.bug_number} - #{bug.desc}"
              # TRANSLATORS: "Found" refers to one singular bug
              bug_str += sprintf(_(" (Found: %s)"), "#{bug.found}") if ( ! bug.found.nil? ) && $DEBUG
              # TRANSLATORS: "Fixed" refers to one singular bug
              bug_str += sprintf(_(" (Fixed: %s)"), "#{bug.fixed}") if ! bug.fixed.nil?
              @config.frontend.puts bug_str
              if bug.mergeids.size > 0
                # TRANSLATORS: "Merged" refers to one singular bug
                bug_str =  _("   Merged with:").dup()
                bug.mergeids.each { |m|
                  bug_str << " #{m}"
                  p_bug_numbers << m
                }
                @config.frontend.puts bug_str
              end
            }
          }
        }
      }
      stat_str_ary = []
      bugs_statistics.each_pair { |pkg_key, num|
        if num > 0
          # TRANSLATORS: %{nbugs} is the number of bugs found for package %{packg}.
          buf = ngettext("%{packg}(%{nbugs} bug)",
                         "%{packg}(%{nbugs} bugs)", num) % {:packg => pkg_key,
                                                            :nbugs => num}
          stat_str_ary << buf
        end
      }
      if stat_str_ary.size > 0
        @config.frontend.puts _("Summary:\n ") + stat_str_ary.join(', ')
        return true
      else
        return false
      end
    end

    def each_state_table(o, bugs, stats)
      stats.each { |stat|
        sub = bugs.sub("stat", stat)
        if sub.size > 0
          o.print "\n    <table class=\"bug_table\" summary="
          # TRANSLATORS: this is a summary description of the structure of a table (for accessibility)
          o.print _("The top row describes the meaning of the columns; the other rows describe bug reports, one per row").encode(:xml => :attr)
          o.print ">\n"
          o.puts "      <caption>\n        " + @config.statmap(stat).encode(:xml => :text)
          o.puts "      </caption>"
          o.puts "\n      <tr class=\"header\">"
          o.puts "        <th class=\"pkg\">" + _("package").encode(:xml => :text) + "</th>"
          o.puts "\n        <th>" + _("version change").encode(:xml => :text) + "</th>"
          o.puts "\n        <th>" + _("severity").encode(:xml => :text) + "</th>"
          o.puts "\n        <th>" + _("bug number").encode(:xml => :text) + "</th>"
          o.puts "\n        <th class=\"desc\">" + _("description").encode(:xml => :text) + "</th>"
          o.puts "      </tr>"
          yield sub
          o.puts "    </table>\n    <hr class=\"nocss\" />"
        end
      }
    end

    def display_bugs_as_html(bugs, cur_pkgs, new_pkgs, cmd = "w")
      tmp = Tempfile.new(["apt-listbugs", ".html"])
      tmp.chmod(0644)
      tmp.puts "<?xml version=\"1.0\" encoding=\"#{Locale.charset}\"?>"
      tmp.puts "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
      tmp.puts "    \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"
      tmp.puts "\n<html xmlns=\"http://www.w3.org/1999/xhtml\">"
      tmp.puts "<head>"
      tmp.puts "  <meta http-equiv=\"Content-type\" content=\"text/html; charset=#{Locale.charset}\" />"
      tmp.puts "  <meta name=\"generator\" content=\"apt-listbugs\" />"
      tmp.puts "\n  <title>" + _("Relevant bugs for your upgrade").encode(:xml => :text) + "</title>"
      tmp.puts "  <link href=\"/etc/apt/listbugs/bug-list.css\" rel=\"stylesheet\" type=\"text/css\" />"
      tmp.puts "</head>\n\n<body>\n  <div id=\"page_title\">"
      tmp.puts "    <h1 class=\"title\">" + _("Relevant bugs for your upgrade").encode(:xml => :text) + "</h1>"
      tmp.puts "\n    <h5 class=\"generated\">" + _("by apt-listbugs").encode(:xml => :text) + "</h5>"
      tmp.puts "  </div>\n\n  <div id=\"page_body\">"
      tmp.puts "    <hr class=\"nocss\" />"

      filtered_bugs = bugs.filter_out(@dodged_bugnums+@ignored_bugnums)
      filtered_bugs.reject! { |bug| @hold_pkg_keys.include?(bug.pkg_key) }
      each_state_table(tmp, filtered_bugs, @config.stats) { |bugs|
        p_bug_numbers = []
        bugs.each { |bug|
          next if p_bug_numbers.include?(bug.bug_number)
          p_bug_numbers << bug.bug_number
          p_bug_numbers += bug.mergeids
          pkg_key = bug.pkg_key
          tmp.puts "\n      <tr class=#{bug.severity.encode(:xml => :attr)}>"
          tmp.puts "        <td class=\"pkg\">#{pkg_key.encode(:xml => :text)}</td>"
          tmp.print "\n        <td>"
          tmp.print "#{cur_pkgs[pkg_key]['version'].encode(:xml => :text)} " if cur_pkgs[pkg_key] != nil
          tmp.print "#{@config.arrow.encode(:xml => :text)} #{new_pkgs[pkg_key]['version'].encode(:xml => :text)}" if new_pkgs[pkg_key] != nil
          tmp.puts "</td>\n\n        <td>#{bug.severity.encode(:xml => :text)}</td>"
          tmp.puts "\n        <td><a href=\"http://bugs.debian.org/#{bug.bug_number}\">##{bug.bug_number}</a></td>"
          tmp.puts "\n        <td class=\"desc\">#{bug.desc.encode(:xml => :text)}</td>\n      </tr>"
        }
      }

      tmp.puts "  </div>\n</body>\n</html>"
      tmp.close

      case cmd
      when "c"
        @config.frontend.puts "" +
          _("You can view the bug lists in HTML at the following URI:\n") +
          "file://" + tmp.path + "\n"
      when "w"
        @config.debugfile.puts "Invoking browser for #{tmp.path}" if $DEBUG
        browsercommandline = "#{@config.cmd_prefix}#{@config.browser} #{tmp.path}"
        if system(browsercommandline)
          @config.debugfile.puts "successfully invoked browser" if $DEBUG
        else
          $stderr.puts _("W: ") + _("Failed to invoke browser.")
          $stderr.puts " #{browsercommandline}"
        end
        clear_stdin
      end
    end

    private
    def clear_stdin(parent = true)
      flags=$stdin.fcntl(Fcntl::F_GETFL)
      if parent
        while clear_stdin(false)
          nil
        end
      else
        begin
          $stdin.read_nonblock(10000000)
          return true
        rescue Errno::EAGAIN
          return false
        ensure
          $stdin.fcntl(Fcntl::F_SETFL, flags)
        end
      end
    end
  end


  class RSSViewer < Viewer

    def initialize(config)
      super(config)
    end

    def view(new_pkgs, cur_pkgs, bugs)
      rss = RSS::Maker.make("2.0") { |maker|
        maker.channel.about = ""
        maker.channel.title = @config.title
        maker.channel.description = @config.title
        maker.channel.link = "http://bugs.debian.org/"

        p_bug_numbers = []

        bugs.each { |bug|
          if @config.stats.include?( bug.stat )
            next if p_bug_numbers.include?(bug.bug_number)
            p_bug_numbers << bug.bug_number
            item = maker.items.new_item
            item.link = "http://bugs.debian.org/#{bug.bug_number}"
            item.title = "##{bug.bug_number} - #{bug.desc}"
            item.date = Time.parse("#{bug.time.year}/#{bug.time.month}/#{bug.time.day} #{bug.time.hour}:#{bug.time.min}:#{bug.time.sec}")

            buf = ""

            buf << "<ul>\n"
            buf << "<li>" + _("bug number")       + ": ##{bug.bug_number}</li>\n"
            buf << "<li>" + _("package")          + ": #{bug.pkg_key}</li>\n"
            buf << "<li>" + _("severity")         + ": #{bug.severity}</li>\n"
            buf << "<li>" + _("category of bugs") + ": #{@config.statmap(bug.stat)}</li>\n"
            buf << "<li>" + _("tags")             + ": #{bug.tags.join(',')}</li>\n" if bug.tags.size > 0

            if bug.mergeids.size > 0
              buf << "<li>" + _("   Merged with:")
              bug.mergeids.each { |id|
                url  = "http://bugs.debian.org/#{id}"
                buf << " <a href=\"#{url}\">#{id}</a>"
                p_bug_numbers << id
              }
              buf << "</li>\n"
            end
            buf << "</ul>\n"

            item.description = buf

          end
        }

      }
      @config.frontend.puts rss.to_s
    end

  end

end


module Factory

  CONCURRENCY_LEVEL = 3

  def done?(done)
    _("Done") == done
  end

  def config
      @@config
  end

  def config=(c)
      @@config = c
  end

  def create(arg, *args)
    raise _("Not Implemented")
  end

  module_function :config, :config=, :create, :done?
  public :create

  module BugsFactory
    extend Factory

    def delete_ignore_pkgs(new_pkgs)
      new_pkgs.delete_if { |pkg_key, pkg|
        config.system_ignore_bugs.include?(pkg_key)
      }
    end

    def create(ma_copies)
      bugs = Debian::Bugs.new
      retrycount = 10 # retry 10 times

      mutex = Mutex.new
      threads = []
      # TRANSLATORS: this sentence, followed by the translation of "Done" (see above) should fit in less than 79 columns to work well with default width terminals
      yield _("Retrieving bug reports..."), "0%"
      begin
        config.debugfile.puts " Using QueryStep = #{config.querystep}" if $DEBUG
        config.debugfile.puts " Using ParseStep = #{config.parsestep}" if $DEBUG
        # obtain the array of bugs
        bugs = config.parser.parse(ma_copies, config.querystep, config.parsestep, config.severity) { |pct|
          yield _("Retrieving bug reports..."), pct
        }
      rescue SOAP::HTTPStreamError => exception
        config.frontend.puts _(" Fail")
        config.debugfile.puts " Exception: " + exception.class.to_s if $DEBUG
        $stderr.puts _("E: ") + _("HTTP GET failed")
        retrycount -= 1
        if config.frontend.yes_or_no?(_("Retry downloading bug information?")) && retrycount > 0
          config.querystep = 1 if config.querystep != 1 && config.frontend.yes_or_no?(_("One package at a time?"))
          config.parsestep = 1 if config.parsestep != 1 && config.frontend.yes_or_no?(_("One bug report at a time?"))
          retry
        end
        raise _("Exiting with error") if ! config.frontend.yes_or_no?(_("Continue the installation anyway?"), false)
        bugs = []
      rescue SOAP::EmptyResponseError => exception
        config.frontend.puts _(" Fail")
        config.debugfile.puts " Exception: " + exception.class.to_s if $DEBUG
        $stderr.puts _("E: ") + _("Empty stream from SOAP")
        retrycount -= 1
        if config.frontend.yes_or_no?(_("Retry downloading bug information?")) && retrycount > 0
          config.querystep = 1 if config.querystep != 1 && config.frontend.yes_or_no?(_("One package at a time?"))
          config.parsestep = 1 if config.parsestep != 1 && config.frontend.yes_or_no?(_("One bug report at a time?"))
          retry
        end
        raise _("Exiting with error") if ! config.frontend.yes_or_no?(_("Continue the installation anyway?"), false)
        bugs = []
      rescue Exception => exception
        config.frontend.puts _(" Fail")
        config.debugfile.puts " Exception: " + exception.class.to_s if $DEBUG
        config.frontend.puts _("Error retrieving bug reports from the server with the following error message:")
        $stderr.puts _("E: ") + "#{$!}"
        if exception.kind_of? SocketError
          config.frontend.puts _("It appears that your network connection is down. Check network configuration and try again")
        else
          config.frontend.puts _("It could be because your network is down, or because of broken proxy servers, or the BTS server itself is down. Check network configuration and try again")
        end
        retrycount -= 1
        if config.frontend.yes_or_no?(_("Retry downloading bug information?")) && retrycount > 0
          config.querystep = 1 if config.querystep != 1 && config.frontend.yes_or_no?(_("One package at a time?"))
          config.parsestep = 1 if config.parsestep != 1 && config.frontend.yes_or_no?(_("One bug report at a time?"))
          retry
        end
        raise _("Exiting with error") if ! config.frontend.yes_or_no?(_("Continue the installation anyway?"), false)
        bugs = []
      end
      yield _("Retrieving bug reports..."), "100%"

      if block_given?
        yield _("Retrieving bug reports..."), _("Done")
      end
      bugs
    end

    def delete_ignore_bugs(bugs)
      # ignoring ignore_bugs
      bugs.delete_if { |bug| config.system_ignore_bugs.include?(bug.bug_number) }
    end

    def delete_regexp_bugs(bugs, regexp)
      config.debugfile.puts "Ignoring regexp: #{regexp}" if $DEBUG
      bugs.delete_if { |bug| bug.desc =~ /#{config.ignore_regexp}/ }
    end

    def delete_uninteresting_bugs(bugs)
      # ignoring all bugs but the requested ones
      bugs.delete_if { |bug| !config.fbugs.include?(bug.bug_number) }
    end

    def iterate_fixed_found_version(bts_versions, src_name)
      # iterate relevant versions, used to parsing Fixed and Found tags of BTS
      if bts_versions.nil?
        return;
      end
      bts_versions.split(" ").each { |version|
        # check each version
        case version
        when /^(.*)\/(.*)$/
          if $1 == src_name
            yield $2
          else
            # TODO: ignore this until src_name is really the source package name
            # yield nil
            yield $2
          end
        else
          yield version
        end
      }
    end

    def find_max_version_below_ver(bts_versions, new_ver, src_name)
      # find the max version from found/fixed that is below or equal to new_ver
      # data format of bts_versions:
      # space-delimited sequence of SRC_PACKAGE/VERSION or VERSION items.

      maxver=nil
      iterate_fixed_found_version(bts_versions, src_name) { |ver|
        # check each ver
        if Debian::Dpkg.compare_versions(ver, "le", new_ver) &&
            ( maxver == nil || Debian::Dpkg.compare_versions(maxver, "le", ver) )
          maxver = ver
        end
      }
      maxver
    end

    def find_min_version_above_ver(bts_versions, new_ver, src_name)
      # find the min version from found/fixed that is strictly above new_ver
      # data format of bts_versions:
      # space-delimited sequence of SRC_PACKAGE/VERSION or VERSION items.

      minver=nil
      iterate_fixed_found_version(bts_versions, src_name) { |ver|
        # check each ver
        if Debian::Dpkg.compare_versions(ver, "gt", new_ver) &&
            ( minver == nil || Debian::Dpkg.compare_versions(minver, "ge", ver) )
          minver = ver
        end
      }
      minver
    end

    def am_i_buggy(src_name, ver, fixed, found)
      # find out if this version is buggy or not depending on the
      # fixed / found arrays.

      config.debugfile.puts " .. checking ver #{ver} against fixed:#{fixed} found:#{found}" if $DEBUG

      fixed_max_below = nil
      found_max_below = nil

      fixed_min_above = nil
      found_min_above = nil

      fixed_max_below = find_max_version_below_ver(fixed, ver, src_name) if ! fixed.nil?
      found_max_below = find_max_version_below_ver(found, ver, src_name) if ! found.nil?

      fixed_min_above = find_min_version_above_ver(fixed, ver, src_name) if ! fixed.nil?
      found_min_above = find_min_version_above_ver(found, ver, src_name) if ! found.nil?

      val=true

      if fixed_max_below == nil && found_max_below == nil
        # this is a hard thing to handle, but do some guessing here...
        # the bug was not fixed or found before this version:
        # it either means it wasn't found before this version,
        # or 'found' version info is missing from BTS
        if found_min_above == nil
          # no new version found;
          # which I guess means that the BTS is missing version info
          config.debugfile.puts " ... no found info: I guess I am buggy" if $DEBUG
          val=true
        else
          # found_min_above is not nil, which means I may not be buggy;
          # except for a case where it's fixed before the found_min,
          # which probably means 'found' info is missing from BTS
          if fixed_min_above == nil ||
              Debian::Dpkg.compare_versions(fixed_min_above, "gt", found_min_above)
            config.debugfile.puts " ... bug found in a later version: I guess I am not buggy" if $DEBUG
            val=false
          else
            config.debugfile.puts " ... bug fixed in a later version before it's found again: I guess I am buggy" if $DEBUG
            val=true
          end
        end
      else if fixed_max_below == nil
             # the bug was found before (or in) this version, but fixed
             # later (or never): it means I am buggy
             config.debugfile.puts " ... bug found in a prior version, but not yet fixed: I am buggy" if $DEBUG
             val=true
           else if found_max_below == nil || Debian::Dpkg.compare_versions(fixed_max_below, "gt", found_max_below)
                  # the bug was not found between the latest fixed version
                  # and this version: it means I am not buggy
                  config.debugfile.puts " ... bug not found between the latest fixed version and this version: I am not buggy" if $DEBUG
                  val=false
                else
                  # the bug was indeed found between the latest fixed version
                  # and this version: it means I am buggy
                  config.debugfile.puts " ... bug found between the latest fixed version and this version: I am buggy" if $DEBUG
                  val=true
                end
           end
      end

      val
    end

    def bug_is_irrelevant(src_name, cur_ver, new_ver, bug_number, fixed, found, bug_stat="")
      # find out if the bug number is irrelevant for this specific upgrade, from fixed/found information.
      # @return false: bug is relevant, true: bug is irrelevant, should be removed.
      val = false

      config.debugfile.puts "Start checking: #{bug_number}" if $DEBUG

      # ignore bugs that have no fixed version info, and are closed with a XXXX-done
      if fixed.nil? && bug_stat == "done"
        config.debugfile.puts "bug apparently closed with XXXX-done without version info" if $DEBUG
        val = true
      else if new_ver.nil?
             # no specific version was given for the package, which means that we are interested in all (non archived) bugs
             config.debugfile.puts "no package version given" if $DEBUG
             val = false
           else if cur_ver.nil?
                  # no known installed version, which means that we want to check the new version
                  val = true if ! am_i_buggy(src_name, new_ver, fixed, found)
                else
                  # both versions are known, which means that we want to check whether the upgrade may introduce this bug into the system
                  val = true if am_i_buggy(src_name, cur_ver, fixed, found) || ( ! am_i_buggy(src_name, new_ver, fixed, found))
                end
           end
      end

      config.debugfile.puts "in conclusion, for bug #{bug_number} comparing fixed:[#{fixed}], found:[#{found}], cur_ver:#{cur_ver} and new_ver:#{new_ver} results in removal:#{val}" if $DEBUG
      val
    end

    def delete_irrelevant_bugs (bugs, cur_pkgs, new_pkgs)
      # Ignore bugs that do not apply to the installing version.

      max=bugs.size
      step=(max/100)*10+1
      i=0
      # TRANSLATORS: this sentence, followed by the translation of "Done" (see above) should fit in less than 79 columns to work well with default width terminals
      yield _("Parsing Found/Fixed information..."), "0%"

      bugs.delete_if { |bug|
        val = false
        pkg_key = bug.pkg_key
        new_ver = nil
        cur_ver = nil
        new_ver = new_pkgs[pkg_key]["version"] if new_pkgs[pkg_key] != nil
        cur_ver = cur_pkgs[pkg_key]["version"] if cur_pkgs[pkg_key] != nil

        # treat back-ported versions as if they were the corresponding
        # official versions (this special handling is necessary until
        # we can query the BTS version tracking directly, see #694979#19,
        # and until back-ports are correctly handled by BTS version tracking)
        new_o_ver = nil
        cur_o_ver = nil
        new_o_ver = new_ver.gsub(/~bpo[0-9].*$/, '') if new_ver != nil
        cur_o_ver = cur_ver.gsub(/~bpo[0-9].*$/, '') if cur_ver != nil

        # show progress
        yield _("Parsing Found/Fixed information..."),
        "#{(i.to_f/max.to_f*100).to_i}%" if (i % step) == 0
        i += 1

        # TODO: this should actually be the source package name...
        # use the binary package name, until there is a better strategy
        src_name = new_pkgs[pkg_key]
        src_name = src_name["package"] if src_name != nil

        val = true if bug_is_irrelevant(src_name, cur_o_ver, new_o_ver,
                                        bug.bug_number, bug.fixed, bug.found, bug.stat)
        val
      }
      yield _("Parsing Found/Fixed information..."), "100%"
      yield _("Parsing Found/Fixed information..."), _("Done")
      bugs
    end

    def delete_unwanted_tag_bugs( bugs )
      config.debugfile.puts "checking unwanted bugs: #{bugs}" if $DEBUG
      bugs.delete_if { |bug|
        val = false
        config.debugfile.puts "#{bug}" if $DEBUG
        config.tag.each { |tag|
          if bug.tags && bug.tags.include?( tag )
            config.debugfile.puts "#{bug} is tagged #{tag}" if $DEBUG
          else
            val = true
          end
        }
        val
      }
    end

    def delete_not_for_us_bugs( bugs )
      config.debugfile.puts "checking not-for-us bugs: #{bugs}" if $DEBUG
      bugs.delete_if { |bug|
        val = false
        config.debugfile.puts "#{bug}" if $DEBUG
        if bug.tags && ! bug.tags.include?( config.distro )
          config.debugfile.puts "#{bug} does not specifically affect our release (#{config.distro})" if $DEBUG
          config.other_releases.reverse_each { |release|
            if bug.tags.include?( release )
              config.debugfile.puts "#{bug} specifically affects release #{release}" if $DEBUG
              val = true
              break
            end
          }
        end
        val
      }
    end

    module_function :delete_ignore_pkgs, :create, :delete_ignore_bugs,
    :delete_uninteresting_bugs,
    :delete_regexp_bugs,
    :bug_is_irrelevant,
    :am_i_buggy,
    :delete_irrelevant_bugs, :delete_unwanted_tag_bugs,
    :delete_not_for_us_bugs,
    :find_max_version_below_ver,
    :find_min_version_above_ver,
    :iterate_fixed_found_version

  end

end

class ConsoleFrontend

  def initialize( config )
    @old = ""
    @config = config
  end

  def progress(msg, val)
    $stdout.print "\r"
    $stdout.print " " * Unicode.width(@old)
    $stdout.print "\r"
    @old = "#{msg} #{val}"
    $stdout.print @old
    $stdout.flush
    $stdout.puts "" if Factory.done?(val)
  end

  def puts(msg)
    $stdout.puts msg
  end

  def ask(msg)
    $stdout.print "#{msg} "
    $stdout.flush
    line = nil
    line = $stdin.gets
    if line != nil
      line.chomp!
    end
    return line
  end

  def yes_or_no?(msg, default = true)
    return @config.yes if ! @config.yes.nil?
    return default if @config.default_reply
    while true
      msgyn = "#{msg}"
      if default == true
        msgyn << " [Y/n]"
      else
        msgyn << " [y/N]"
      end
      a = ask msgyn
      if a.nil?
        $stdout.print "\n"
      else
        answer = a.downcase.strip
        case answer
        when ""
          return default
        when "y"
          return true
        when "n"
          return false
        end
      end
    end
  end

  def close
  end
end

### ;;;
### Local Variables: ***
### dancer-test-run-chdir: "../.." ***
### End: ***