aboutsummaryrefslogtreecommitdiffstats
path: root/bin/common/srtool_utils.py
blob: ac65d42d451d8fde06acd199bea143f0cbe7f1a5 (plain)
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
#!/usr/bin/env python3
#
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# Security Response Tool Commandline Tool
#
# Copyright (C) 2018-2019  Wind River Systems
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# 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 along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import os
import sys
import argparse
import sqlite3
from datetime import datetime, date
import time
import re

# load the srt.sqlite schema indexes
dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, dir_path)
from common.srt_schema import ORM

# Setup:
verbose = False
cmd_skip = 0
cmd_count = 0
force = False

srtDbName = 'srt.sqlite'

#################################
# Common routines
#

# quick development/debugging support
def _log(msg):
    DBG_LVL =  os.environ['SRTDBG_LVL'] if ('SRTDBG_LVL' in os.environ) else 2
    DBG_LOG =  os.environ['SRTDBG_LOG'] if ('SRTDBG_LOG' in os.environ) else '/tmp/srt_dbg.log'
    if 1 == DBG_LVL:
        print(msg)
    elif 2 == DBG_LVL:
        f1=open(DBG_LOG, 'a')
        f1.write("|" + msg + "|\n" )
        f1.close()

#################################
# reset sources
#

# source_data = (source_id)
def commit_to_source(conn, source_data):
    sql = ''' UPDATE orm_datasource
              SET loaded = ?
              WHERE id = ?'''
    cur = conn.cursor()
    print("UPDATE_SCORE:%s" % str(source_data))
    cur.execute(sql, source_data)

def sources(cmnd):
    conn = sqlite3.connect(srtDbName)
    c = conn.cursor()

    print('Sources(%s)' % cmnd)

    c.execute("SELECT * FROM orm_datasource")
    is_change = False
    for ds in c:
        if 'set' == cmnd:
            commit_to_source(conn,(True,ds[ORM.DATASOURCE_ID]))
            is_change = True
        elif 'reset' == cmnd:
            commit_to_source(conn,(False,ds[ORM.DATASOURCE_ID]))
            is_change = True
        elif 'reset_not_nist' == cmnd:
            if 'nist' != ds[ORM.DATASOURCE_SOURCE]:
                print("RESETTING Data source [%s] data='%s' of '%s' load state from '%s' is '%s'" % (ds[ORM.DATASOURCE_ID],ds[ORM.DATASOURCE_DATA],ds[ORM.DATASOURCE_DESCRIPTION],ds[ORM.DATASOURCE_SOURCE],ds[ORM.DATASOURCE_LOADED]))
                commit_to_source(conn,(False,ds[ORM.DATASOURCE_ID]))
            else:
                commit_to_source(conn,(True,ds[ORM.DATASOURCE_ID]))
            is_change = True
        elif 'triage_keywords' == cmnd:
            if 'triage_keywords' == ds[ORM.DATASOURCE_DATA]:
                print("RESETTING Data source [%s] data='%s' of '%s' load state from '%s' is '%s'" % (ds[ORM.DATASOURCE_ID],ds[ORM.DATASOURCE_DATA],ds[ORM.DATASOURCE_DESCRIPTION],ds[ORM.DATASOURCE_SOURCE],ds[ORM.DATASOURCE_LOADED]))
                commit_to_source(conn,(False,ds[ORM.DATASOURCE_ID]))
                is_change = True
        else:
            print("Data source [%s] data='%s' of '%s' load state from '%s' is '%s'" % (ds[ORM.DATASOURCE_ID],ds[ORM.DATASOURCE_DATA],ds[ORM.DATASOURCE_DESCRIPTION],ds[ORM.DATASOURCE_SOURCE],ds[ORM.DATASOURCE_LOADED]))

    if is_change:
        conn.commit()


def settings():
    conn = sqlite3.connect(srtDbName)
    c = conn.cursor()

    # Scan the SRTool Settings
    c.execute("SELECT * FROM orm_srtsetting")

    for setting in c:
        print("Setting[%s] = '%s'" % (setting[ORM.SRTSETTING_NAME], setting[ORM.SRTSETTING_VALUE][0:40]))


#################################
# remove_app_sources
#

def remove_app_sources(master_app):
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    # Scan the SRTool Settings
    cur.execute("SELECT * FROM orm_datasource")

    is_change = False
    for setting in cur:
        if master_app == setting[ORM.DATASOURCE_SOURCE]:
            print("Deleting [%s] = '%s','%s'" % (setting[ORM.DATASOURCE_ID], setting[ORM.DATASOURCE_SOURCE], setting[ORM.SRTSETTING_VALUE]))
            sql = 'DELETE FROM orm_datasource WHERE id=?'
            cur_write.execute(sql, (setting[ORM.DATASOURCE_ID],))
            is_change = True

    if is_change:
        conn.commit()
    conn.close()

#################################
# fix_new_reserved
#

# Is this reserved by Mitre? Is '** RESERVED **' within the first 20 char positions?
def fix_new_reserved():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    cur.execute('SELECT * FROM orm_cve WHERE status = "%s"' % ORM.STATUS_NEW)
    i = 0
    j = 0
    for cve in cur:
        i += 1

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s\r' % (i,cve[ORM.CVE_NAME]), end='')
        if (0 == i % 200):
            conn.commit()
        # Development/debug support
        if cmd_skip:
            if i < cmd_skip:
                continue
        if cmd_count:
            if (i - cmd_skip) > cmd_count:
                print("Count return: %s,%s" % (i,cmd_count))
                break

        reserved_pos = cve[ORM.CVE_DESCRIPTION].find('** RESERVED **')
        if (0 <= reserved_pos) and (20 > reserved_pos):
            print("STATUS_NEW_RESERVED:%s:%s:%s" % (cve[ORM.CVE_STATUS],cve[ORM.CVE_NAME],cve[ORM.CVE_DESCRIPTION][:40]))
            # NOTE: we do not touch 'cve.srt_updated' for this background change
            sql = ''' UPDATE orm_cve
                      SET status = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (ORM.STATUS_NEW_RESERVED, cve[ORM.CVE_ID],))
            j += 1
    print("\nCVE COUNT=%5d,%5d" % (i,j))
    conn.commit()

#################################
# fix_new_tags
#

# Fix the None "cve.tags" fields
def fix_new_tags():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    cur.execute('SELECT * FROM orm_cve')
    i = 0
    j = 0
    for cve in cur:
        i += 1

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s\r' % (i,cve[ORM.CVE_NAME]), end='')
        if (0 == i % 200):
            conn.commit()
        # Development/debug support
        if cmd_skip:
            if i < cmd_skip:
                continue
        if cmd_count:
            if (i - cmd_skip) > cmd_count:
                print("Count return: %s,%s" % (i,cmd_count))
                break

        if not cve[ORM.CVE_TAGS]:
            # NOTE: we do not touch 'cve.srt_updated' for this background change
            sql = ''' UPDATE orm_cve
                      SET tags = ?
                      WHERE id = ?'''
            cur_write.execute(sql, ('', cve[ORM.CVE_ID],))
            j += 1
    print("\nCVE COUNT=%5d,%5d" % (i,j))
    conn.commit()

#################################
# fixup fix_name_sort
#

# Recompute all of the CVE name_sort fields
def fix_name_sort():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    cur.execute('SELECT * FROM orm_cve')
    for i,cve in enumerate(cur):
        name_sort = get_name_sort(cve[ORM.CVE_NAME])

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s to %20s\r' % (i,cve[ORM.CVE_NAME],name_sort), end='')
        if (0 == i % 200):
            conn.commit()

        # NOTE: we do not touch 'cve.srt_updated' for this background change
        sql = ''' UPDATE orm_cve
                  SET name_sort = ?
                  WHERE id = ?'''
        cur_write.execute(sql, (name_sort, cve[ORM.CVE_ID],))
    conn.commit()

#################################
# fixup fix_cve_recommend
#

# Reset empty CVE recommend fields to the proper integer zero
def fix_cve_recommend():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    cur.execute('SELECT * FROM orm_cve WHERE recommend = ""')
    i = 0
    fix_count = 0
    for cve in cur:
        i += 1

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s\r' % (i,cve[ORM.CVE_NAME]), end='')

        #
        # Fix miss-write to lastModifiedDate, missing integer for recommend
        #

        fix = False

        lastModifiedDate = cve[ORM.CVE_LASTMODIFIEDDATE]
        if '0' == lastModifiedDate:
            lastModifiedDate = ''
            fix = True

        recommend = cve[ORM.CVE_RECOMMEND]
        if not recommend:
            recommend = 0
            fix = True

        # NOTE: we do not touch 'cve.srt_updated' for this background change
        if fix:
            sql = ''' UPDATE orm_cve
                      SET recommend = ?, lastModifiedDate = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (recommend, lastModifiedDate, cve[ORM.CVE_ID],))

            fix_count += 1
            if (199 == fix_count % 200):
                conn.commit()

    print("CVE RECOMMEND FIX COUNT=%d of %d" % (fix_count,i))
    if fix_count:
        conn.commit()
    conn.close()

#################################
# fixup fix_srt_dates
#

# Reset older 'date' values as 'datetime' values

def _fix_datetime(value,default):
    if (not value) or (not value[0].isdigit()):
        return(default)
    elif ':' in value:
        return(value)
    else:
        return(datetime.strptime(value, '%Y-%m-%d'))

def _fix_date(value,default):
    if (not value) or (not value[0].isdigit()):
        return(False,default)
    elif not ':' in value:
        return(False,value)
    else:
        value = re.sub('\..*','',value)
        dt = datetime.strptime(value,ORM.DATASOURCE_DATETIME_FORMAT)
        return(True,dt.strftime(ORM.DATASOURCE_DATE_FORMAT))


def fix_srt_datetime(scope):
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    if ('d' == scope) or ('all' == scope):
        cur.execute('SELECT * FROM orm_defect')
        i = 0
        is_change_count = 0
        for defect in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: %20s\r' % (i,defect[ORM.DEFECT_NAME]), end='')
            if (0 == i % 200):
                conn.commit()
            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if (i - cmd_skip) > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            defect_srt_updated = _fix_datetime(defect[ORM.DEFECT_SRT_UPDATED],defect[ORM.DEFECT_DATE_UPDATED])
            if defect_srt_updated == defect[ORM.DEFECT_SRT_UPDATED]:
                continue

            sql = ''' UPDATE orm_defect
                      SET srt_updated = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (defect_srt_updated, defect[ORM.DEFECT_ID],))
            is_change_count += 1
        print("DEFECT DATE FIX COUNT=%d/%d" % (is_change_count,i))
        conn.commit()

    # INVESTIGATION DATE FIX COUNT=1089363, real 12m20.041s = 1472 recs/sec
    if ('i' == scope) or ('all' == scope):
        cur.execute('SELECT * FROM orm_investigation')
        i = 0
        is_change_count = 0
        for investigation in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: %20s\r' % (i,investigation[ORM.INVESTIGATION_NAME]), end='')
            if (0 == i % 200):
                conn.commit()
                time.sleep(0.1) # give time for Sqlite to sync
            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if (i - cmd_skip) > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            srt_updated = _fix_datetime(investigation[ORM.INVESTIGATION_SRT_UPDATED],None)
            srt_created = _fix_datetime(investigation[ORM.INVESTIGATION_SRT_CREATED],None)
            if (not srt_updated) or (not srt_created):
                print("ERROR[%d]: bad date field at '%s', U=%s,C=%s" % (i,investigation[ORM.INVESTIGATION_ID],investigation[ORM.INVESTIGATION_SRT_UPDATED],investigation[ORM.INVESTIGATION_SRT_CREATED]))
                exit(1)
            if (srt_updated == investigation[ORM.INVESTIGATION_SRT_UPDATED]) and (srt_created == investigation[ORM.INVESTIGATION_SRT_CREATED]):
                continue

            sql = ''' UPDATE orm_investigation
                      SET srt_updated = ?, srt_created = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (srt_updated, srt_created, investigation[ORM.INVESTIGATION_ID],))
            is_change_count += 1
        print("INVESTIGATION DATE FIX COUNT=%d/%d" % (is_change_count,i))
        conn.commit()

    # VULNERABILITY DATE FIX COUNT=86585, real 1m2.969s = 1374 recs/sec
    if ('v' == scope) or ('all' == scope):
        cur.execute('SELECT * FROM orm_vulnerability')
        i = 0
        is_change_count = 0
        for vulnerability in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: %20s\r' % (i,vulnerability[ORM.VULNERABILITY_NAME]), end='')
            if (0 == i % 200):
                conn.commit()
                time.sleep(0.1) # give time for Sqlite to sync
            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if (i - cmd_skip) > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            srt_updated = _fix_datetime(vulnerability[ORM.VULNERABILITY_SRT_UPDATED],None)
            srt_created = _fix_datetime(vulnerability[ORM.VULNERABILITY_SRT_CREATED],None)
            if (not srt_updated) or (not srt_created):
                print("ERROR[%d]: bad date field at '%s', U=%s,C=%s" % (i,vulnerability[ORM.VULNERABILITY_ID],vulnerability[ORM.VULNERABILITY_SRT_UPDATED],vulnerability[ORM.VULNERABILITY_SRT_CREATED]))
                exit(1)
            if (srt_updated == vulnerability[ORM.VULNERABILITY_SRT_UPDATED]) and (srt_created == vulnerability[ORM.VULNERABILITY_SRT_CREATED]):
                continue

            sql = ''' UPDATE orm_vulnerability
                      SET srt_updated = ?, srt_created = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (srt_updated, srt_created, vulnerability[ORM.VULNERABILITY_ID],))
            is_change_count += 1
        print("VULNERABILITY DATE FIX COUNT=%d/%d" % (is_change_count,i))
        conn.commit()

    # CVE DATE FIX COUNT=86585, real 1m2.969s = 1374 recs/sec
    # NOTE: only ACK dates need fixing, received bad apha content from srtool_mitre
    if ('c' == scope) or ('all' == scope):
        cur.execute('SELECT * FROM orm_cve')
        i = 0
        # Sparse updates
        is_change = False
        is_change_count = 0
        for cve in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: %20s\r' % (i,cve[ORM.CVE_NAME]), end='')
            if (0 == i % 200) and is_change:
                conn.commit()
                time.sleep(0.1) # give time for Sqlite to sync
                is_change = False

            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if is_change_count > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            is_change = False

            if cve[ORM.CVE_ACKNOWLEDGE_DATE]:
                acknowledge_date = _fix_datetime(cve[ORM.CVE_ACKNOWLEDGE_DATE],'alpha')
                # If the default 'alpha' happens, then date had bad format and must go away
                if ('alpha' == acknowledge_date) or (acknowledge_date != cve[ORM.CVE_ACKNOWLEDGE_DATE]):
                    acknowledge_date = None
                    is_change = True

            srt_updated = _fix_datetime(cve[ORM.CVE_SRT_UPDATED],None)
            srt_created = _fix_datetime(cve[ORM.CVE_SRT_CREATED],None)
            if (not srt_updated) or (not srt_created):
                print("ERROR[%d]: bad date field at '%s', U=%s,C=%s" % (i,cve[ORM.CVE_ID],cve[ORM.CVE_SRT_UPDATED],cve[ORM.CVE_SRT_CREATED]))
                exit(1)
            if (srt_updated != cve[ORM.CVE_SRT_UPDATED]) or (srt_created != cve[ORM.CVE_SRT_CREATED]):
                is_change = True

            # Anything to do?
            if not is_change:
                continue

            is_change_count += 1
            sql = ''' UPDATE orm_cve
                      SET srt_updated = ?, srt_created = ?, acknowledge_date = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (srt_updated, srt_created, acknowledge_date, cve[ORM.CVE_ID],))
            is_change_count += 1
        print("CVE DATE FIX COUNT=%d/%d" % (is_change_count,i))
        conn.commit()

    # Fix CVE History
    if scope in ('ch','all','history'):
        cur.execute('SELECT * FROM orm_cvehistory')
        i = 0
        # Sparse updates
        is_change = False
        is_change_count = 0
        for cve_history in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: \r' % (i), end='')
            if (0 == i % 200) and is_change:
                conn.commit()
                time.sleep(0.1) # give time for Sqlite to sync
                is_change = False

            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if is_change_count > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            updated,history_date = _fix_date(cve_history[ORM.CVEHISTORY_DATE],'')
            if not updated:
                continue

            is_change = True
            sql = ''' UPDATE orm_cvehistory
                      SET date = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (history_date, cve_history[ORM.CVEHISTORY_ID],))
            is_change_count += 1

        # Commit all remaining changes
        if is_change:
            conn.commit()
        print("CVE HISTORY DATE FIX COUNT=%d/%d" % (is_change_count,i))

    # Fix Vulnerability History
    if scope in ('vh','all','history'):
        cur.execute('SELECT * FROM orm_vulnerabilityhistory')
        i = 0
        # Sparse updates
        is_change = False
        is_change_count = 0
        for vulnerabilityhistory in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: \r' % (i), end='')
            if (0 == i % 200) and is_change:
                conn.commit()
                time.sleep(0.1) # give time for Sqlite to sync
                is_change = False

            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if is_change_count > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            updated,history_date = _fix_date(vulnerabilityhistory[ORM.VULNERABILITYHISTORY_DATE],'')
            if not updated:
                continue

            is_change = True
            sql = ''' UPDATE orm_vulnerabilityhistory
                      SET date = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (history_date, vulnerabilityhistory[ORM.VULNERABILITYHISTORY_ID],))
            is_change_count += 1

        # Commit all remaining changes
        if is_change:
            conn.commit()
        print("VULNERABILITY HISTORY DATE FIX COUNT=%d/%d" % (is_change_count,i))

    # Fix Investigation History
    if scope in ('ih','all','history'):
        cur.execute('SELECT * FROM orm_investigationhistory')
        i = 0
        # Sparse updates
        is_change = False
        is_change_count = 0
        for investigation_history in cur:
            i += 1

            # Progress indicator support
            if 0 == i % 10:
                print('%05d: \r' % (i), end='')
            if (0 == i % 200) and is_change:
                conn.commit()
                time.sleep(0.1) # give time for Sqlite to sync
                is_change = False

            # Development/debug support
            if cmd_skip:
                if i < cmd_skip:
                    continue
            if cmd_count:
                if is_change_count > cmd_count:
                    print("Count return: %s,%s" % (i,cmd_count))
                    break

            updated,history_date = _fix_date(investigation_history[ORM.INVESTIGATIONHISTORY_DATE],'')
            if not updated:
                continue

            is_change = True
            sql = ''' UPDATE orm_investigationhistory
                      SET date = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (history_date, investigation_history[ORM.INVESTIGATIONHISTORY_ID],))
            is_change_count += 1

        # Commit all remaining changes
        if is_change:
            conn.commit()
        print("INVESTIGATION HISTORY DATE FIX COUNT=%d/%d" % (is_change_count,i))

#################################
# fixup fix_cve_srt_create
#

# Reset CVE srt_create to NIST release dates
def fix_reset_nist_to_create(cve_prefix):
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    def date_nist2srt(nist_date,default,cve_name,i):
        if not nist_date or (4 > len(nist_date)):
            return default
        try:
            return(datetime.strptime(nist_date, '%Y-%m-%d'))
        except Exception as e:
            print("\n\ndate_nist2srt:%s,%s,%s,%s" % (cve_name,e,cve_name,i))
            exit(1)
            return default

    cur.execute('SELECT * FROM orm_cve WHERE name LIKE "'+cve_prefix+'%"')

    i = 0
    for cve in cur:
        i += 1

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s\r' % (i,cve[ORM.CVE_NAME]), end='')
        if (0 == i % 200):
            conn.commit()
            print('')
        # Development/debug support
        if cmd_skip and (i < cmd_skip): continue
        if cmd_count and ((i - cmd_skip) > cmd_count): break

        nist_released = date_nist2srt(cve[ORM.CVE_PUBLISHEDDATE],cve[ORM.CVE_SRT_CREATED],cve[ORM.CVE_NAME],i)
        nist_modified = date_nist2srt(cve[ORM.CVE_LASTMODIFIEDDATE],cve[ORM.CVE_SRT_UPDATED],cve[ORM.CVE_NAME],i)

        sql = ''' UPDATE orm_cve
                  SET srt_created = ?, srt_updated = ?
                  WHERE id = ?'''
        cur_write.execute(sql, (nist_released, nist_modified, cve[ORM.CVE_ID],))
    print("CVE DATE FIX COUNT=%d" % i)
    conn.commit()

#################################
# fixup fix_missing_create_dates
#

# Reset CVE None creation dates to 2019-01-01, out of the way of reports
def fix_missing_create_dates():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    fix_date =  datetime.strptime('Jan 1 2019', '%b %d %Y')
    fix_count = 0

    cur.execute('SELECT * FROM orm_cve')
    i = 0
    for cve in cur:
        i += 1

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s\r' % (i,cve[ORM.CVE_NAME]), end='')
        if (0 == i % 200):
#            conn.commit()
            #print('')
            pass
        # Development/debug support
        if cmd_skip:
            if i < cmd_skip:
                continue
        if cmd_count:
            if (i - cmd_skip) > cmd_count:
                print("Count return: %s,%s" % (i,cmd_count))
                break

        fix = False
        if not cve[ORM.CVE_SRT_CREATED] or (0 > cve[ORM.CVE_SRT_CREATED].find(':')):
            srt_created = fix_date
            fix = True
        else:
            srt_created = cve[ORM.CVE_SRT_CREATED]
            #srt_created = datetime.strptime(cve[ORM.CVE_SRT_CREATED],'%Y-%m-%d')
        if not cve[ORM.CVE_SRT_UPDATED] or (0 > cve[ORM.CVE_SRT_UPDATED].find(':')):
            srt_updated = fix_date
            fix = True
        else:
            srt_updated = cve[ORM.CVE_SRT_UPDATED]
            #srt_updated = datetime.strptime(cve[ORM.CVE_SRT_UPDATED],'%Y-%m-%d')

        if fix:
            sql = ''' UPDATE orm_cve
                      SET srt_created = ?, srt_updated = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (srt_created, srt_updated, cve[ORM.CVE_ID],))
            fix_count += 1
    print("CVE DATE FIX COUNT=%d of %d" % (fix_count,i))
    conn.commit()

#################################
# fixup fix_public_reserved
#

# Reset CVE 'New-Reserved' if now public from NIST
def fix_public_reserved():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_write = conn.cursor()

    fix_count = 0

    cur.execute('SELECT * FROM orm_cve WHERE status = "%s"' % ORM.STATUS_NEW_RESERVED)
    i = 0
    for cve in cur:
        i += 1

        # Progress indicator support
        if 0 == i % 10:
            print('%05d: %20s %d\r' % (i,cve[ORM.CVE_NAME],cve[ORM.CVE_STATUS]), end='')
        if (0 == i % 200):
            conn.commit()
            #print('')
            pass
        # Development/debug support
        if cmd_skip:
            if i < cmd_skip:
                continue
        if cmd_count:
            if (i - cmd_skip) > cmd_count:
                print("Count return: %s,%s" % (i,cmd_count))
                break

        if  cve[ORM.CVE_CVSSV3_BASESCORE] or cve[ORM.CVE_CVSSV2_BASESCORE]:
            sql = ''' UPDATE orm_cve
                      SET status = ?
                      WHERE id = ?'''
            cur_write.execute(sql, (ORM.STATUS_NEW, cve[ORM.CVE_ID],))
            fix_count += 1
    print("CVE DATE FIX COUNT=%d of %d" % (fix_count,i))
    conn.commit()

#################################
# fix_remove_bulk_cve_history
#

# Remove a specific/accidental set of bulk CVE history updates intended to be background
def fix_foo():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_cve = conn.cursor()
    cur_del = conn.cursor()

    fix_count = 0

    print("FOO=%s\n\n" % ORM.STATUS_NEW_RESERVED)

    cur.execute('SELECT * FROM orm_cvehistory WHERE date LIKE "2019-03-2%"')

    i = 0
    for cvehistory in cur:
        i += 1

        # Progress indicator support
        if 9 == i % 10:
#            print('%05d: %20s %s    \r' % (i,cvehistory[ORM.CVEHISTORY_COMMENT],cvehistory[ORM.CVEHISTORY_DATE]), end='')
            pass
        if (0 == i % 200):
#            conn.commit()
            #print('')
            pass
        # Development/debug support
        if cmd_skip and (i < cmd_skip): continue
        if cmd_count and ((i - cmd_skip) > cmd_count): break

        if not (cvehistory[ORM.CVEHISTORY_DATE] in ('2019-03-28','2019-03-27')):
            continue
        if not (cvehistory[ORM.CVEHISTORY_COMMENT].startswith("UPDATE(CVE):")):
            continue

        cur_cve.execute('SELECT * FROM orm_cve WHERE id = "%s"' %  cvehistory[ORM.CVEHISTORY_CVE_ID])
        cve = cur_cve.fetchone()
        if not (cve[ORM.CVE_NAME].startswith("CVE-200")):
            continue

        if 19 == fix_count % 20:
            print("%4d) CVE=%s,CH_Comment=%s,CH_Date=%s" % (fix_count,cve[ORM.CVE_NAME],cvehistory[ORM.CVEHISTORY_COMMENT],cvehistory[ORM.CVEHISTORY_DATE]))

        mydata = cur_del.execute("DELETE FROM orm_cvehistory WHERE id=?", (cvehistory[ORM.CVEHISTORY_ID],))
        fix_count += 1

    print("CVE DATE FIX COUNT=%d of %d" % (fix_count,i))
    conn.commit()

#################################
# fix_defects_to_products
#

#
def fix_defects_to_products():
    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_cve = conn.cursor()
    cur_del = conn.cursor()

    fix_count = 0

    # Find all products
    products = {}
    cur.execute('SELECT * FROM orm_product')
    for product in cur:
        id =  product[ORM.PRODUCT_ID]
        name =  "%s %s %s" % (product[ORM.PRODUCT_NAME],product[ORM.PRODUCT_VERSION],product[ORM.PRODUCT_PROFILE])
        products[id] = name
        print("[%2d] %s" % (id,name))

    # Test product field for all defects
    cur.execute('SELECT * FROM orm_defect')
    i = 0
    for defect in cur:
        i += 1

        # Progress indicator support
        if 99 == i % 100:
            print('%05d: %-20s\r' % (i,defect[ORM.DEFECT_NAME]), end='')
            pass
        if (0 == i % 200):
#            conn.commit()
            #print('')
            pass
        # Development/debug support
        if cmd_skip and (i < cmd_skip): continue
        if cmd_count and ((i - cmd_skip) > cmd_count): break

        product_id = defect[ORM.DEFECT_PRODUCT_ID]
        if not product_id in products:
            print("ERROR:[%5d] %-20s => %s" % (defect[ORM.DEFECT_ID],defect[ORM.DEFECT_NAME],product_id))

#    print("CVE DATE FIX COUNT=%d of %d" % (fix_count,i))
    conn.commit()

#################################
# find_multiple_defects
#

def find_multiple_defects():

    conn = sqlite3.connect(srtDbName)
    cur_i2d = conn.cursor()
    cur_inv = conn.cursor()
    cur_def = conn.cursor()

    cur_inv.execute('SELECT * FROM orm_investigation')
    count = 0
    for i,investigation in enumerate(cur_inv):
        if 0 == i % 100:
           print("%4d) V=%-30s\r" % (i,investigation[ORM.VULNERABILITY_NAME]), end='')

        cur_i2d.execute('SELECT * FROM orm_investigationtodefect WHERE investigation_id = "%s"' % investigation[ORM.INVESTIGATION_ID])
        i2d_list = cur_i2d.fetchall()
        if 1 < len(i2d_list):
            count += 1
            for k,i2d in enumerate(i2d_list):
                cur_def.execute('SELECT * FROM orm_defect WHERE id = "%s"' %  i2d[ORM.INVESTIGATIONTODEFECT_DEFECT_ID])
                defect = cur_def.fetchone()
                if defect[ORM.DEFECT_NAME].startswith("LIN10"):
                    if 0 == k:
                        print("[%02d] Multiple defects for investigation '%s':" % (count,investigation[ORM.INVESTIGATION_NAME]))
                    print("  [%02d] %s: %s (%s)" % (k+1,defect[ORM.DEFECT_NAME],defect[ORM.DEFECT_SUMMARY],ORM.get_orm_string(defect[ORM.DEFECT_RESOLUTION],ORM.DEFECT_RESOLUTION_STR)))
    conn.close()

#################################
# find_duplicate_names
#

def find_duplicate_names():

    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()


    cur.execute('SELECT * FROM orm_cve')
    cve_dict = {}
    for i,cve in enumerate(cur):
        if 0 == i % 100:
           print("%4d) C=%-30s\r" % (i,cve[ORM.CVE_NAME]), end='')

        if not cve[ORM.CVE_NAME] in cve_dict:
            cve_dict[cve[ORM.CVE_NAME]] = cve[ORM.CVE_ID]
        else:
            print("\nERROR:Multiple cve names '%s'" % cve[ORM.CVE_NAME])
            print("   a) id=%d" % cve_dict[cve[ORM.CVE_NAME]])
            print("   b) id=%d" % cve[ORM.CVE_ID])
    cve_dict = {}
    print('')

    cur.execute('SELECT * FROM orm_vulnerability')
    vul_dict = {}
    for i,vulnerability in enumerate(cur):
        if 0 == i % 100:
           print("%4d) V=%-30s\r" % (i,vulnerability[ORM.VULNERABILITY_NAME]), end='')

        if not vulnerability[ORM.VULNERABILITY_NAME] in vul_dict:
            vul_dict[vulnerability[ORM.VULNERABILITY_NAME]] = vulnerability[ORM.VULNERABILITY_ID]
        else:
            print("\nERROR:Multiple vulnerability names '%s'" % vulnerability[ORM.VULNERABILITY_NAME])
            print("   a) id=%d" % vul_dict[vulnerability[ORM.VULNERABILITY_NAME]])
            print("   b) id=%d" % vulnerability[ORM.VULNERABILITY_ID])
    vul_dict = {}
    print('')

    cur.execute('SELECT * FROM orm_investigation')
    inv_dict = {}
    for i,investigation in enumerate(cur):
        if 0 == i % 100:
           print("%4d) I=%-30s\r" % (i,investigation[ORM.INVESTIGATION_NAME]), end='')

        if not investigation[ORM.INVESTIGATION_NAME] in inv_dict:
            inv_dict[investigation[ORM.INVESTIGATION_NAME]] = investigation[ORM.INVESTIGATION_ID]
        else:
            print("\nERROR:Multiple investigation names '%s'" % investigation[ORM.INVESTIGATION_NAME])
            print("   a) id=%d" % inv_dict[investigation[ORM.INVESTIGATION_NAME]])
            print("   b) id=%d" % investigation[ORM.INVESTIGATION_ID])
    inv_dict = {}
    print('')

    cur.execute('SELECT * FROM orm_defect')
    dev_dict = {}
    for i,defect in enumerate(cur):
        if 0 == i % 100:
           print("%4d) D=%-30s\r" % (i,defect[ORM.DEFECT_NAME]), end='')

        if not defect[ORM.DEFECT_NAME] in dev_dict:
            dev_dict[defect[ORM.DEFECT_NAME]] = defect[ORM.DEFECT_ID]
        else:
            print("\nERROR:Multiple defect names '%s'" % defect[ORM.DEFECT_NAME])
            print("   a) id=%d" % dev_dict[defect[ORM.DEFECT_NAME]])
            print("   b) id=%d" % defect[ORM.DEFECT_ID])
    dev_dict = {}
    print('')

    conn.close()

#################################
# find_bad_links
#

def find_bad_links():

    conn = sqlite3.connect(srtDbName)
    cur = conn.cursor()
    cur_del = conn.cursor()

    #
    print('\n=== CVE Source Check ===\n')
    #

    cur.execute('SELECT * FROM orm_cvesource')
    is_change = False
    for i,cs in enumerate(cur):
        cveid = cs[ORM.CVESOURCE_CVE_ID]
        srcid = cs[ORM.CVESOURCE_DATASOURCE_ID]
        if 0 == i % 100:
            print("%4d) CVE=%6d,SRC=%6d\r" % (cs[ORM.CVESOURCE_ID],cveid,srcid), end='')
        error = False
        if (1 > cveid): error = True
        if (1 > srcid): error = True

        if error:
            print("ERROR: [%4d] CVE=%6d,SRC=%6d" % (cs[ORM.CVESOURCE_ID],cveid,srcid))
            if force:
                sql = 'DELETE FROM orm_cvesource WHERE id=?'
                cur_del.execute(sql, (cs[ORM.CVESOURCE_ID],))
                is_change = True

    print('')
    if is_change:
        conn.commit()

    #
    print('\n=== Defect to Product Check ===\n')
    #

    # Find all products
    products = {}
    cur.execute('SELECT * FROM orm_product')
    for product in cur:
        id =  product[ORM.PRODUCT_ID]
        name =  "%s %s %s" % (product[ORM.PRODUCT_NAME],product[ORM.PRODUCT_VERSION],product[ORM.PRODUCT_PROFILE])
        products[id] = name
        print("[%2d] %s" % (id,name))

    # Test product field for all defects
    cur.execute('SELECT * FROM orm_defect')
    i = 0
    for defect in cur:
        i += 1

        # Progress indicator support
        if 99 == i % 100:
            print('%05d: %-20s\r' % (i,defect[ORM.DEFECT_NAME]), end='')
            pass
        if (0 == i % 200):
#            conn.commit()
            #print('')
            pass
        # Development/debug support
        if cmd_skip and (i < cmd_skip): continue
        if cmd_count and ((i - cmd_skip) > cmd_count): break

        product_id = defect[ORM.DEFECT_PRODUCT_ID]
        if not product_id in products:
            print("ERROR:[%5d] %-20s => %s" % (defect[ORM.DEFECT_ID],defect[ORM.DEFECT_NAME],product_id))

    conn.close()


#################################
# main loop
#

def main(argv):
    global verbose
    global cmd_skip
    global cmd_count
    global force

    # setup
    parser = argparse.ArgumentParser(description='srtool.py: manage the SRTool database')
    parser.add_argument('--sources', '-s', nargs='?', const='display', help='SRTool Sources')
    parser.add_argument('--reset-sources', '-r', action='store_const', const='reset_sources', dest='command', help='Reset SRTool Sources')
    parser.add_argument('--settings', '-S', action='store_const', const='settings', dest='command', help='Show the SRT Settings')
    parser.add_argument('--remove-app-sources', dest='remove_app_sources', help='Remove data sources for a previous app')

    parser.add_argument('--fix-name-sort', action='store_const', const='fix_name_sort', dest='command', help='Recalulate the CVE name sort values')
    parser.add_argument('--fix-cve-recommend', action='store_const', const='fix_cve_recommend', dest='command', help='Fix the empty CVE recommend values')
    parser.add_argument('--fix-new-reserved', action='store_const', const='fix_new_reserved', dest='command', help='Reset new reserved CVEs to NEW_RESERVED')
    parser.add_argument('--fix-new-tags', action='store_const', const='fix_new_tags', dest='command', help='Reset new cve.tags')
    parser.add_argument('--fix-srt-datetime', dest='fix_srt_datetime', help='Fix SRT dates to datetimes [all|c|v|i|d|history|ch|vh|ih|dh]')
    parser.add_argument('--fix-reset-nist-to-create', dest='fix_reset_nist_to_create', help='Bulk reset CVE [prefix*] srt_create dates to NIST release dates')
    parser.add_argument('--fix-missing-create-dates', action='store_const', const='fix_missing_create_dates', dest='command', help='Reset CVE srt_create dates to NIST release dates')
    parser.add_argument('--fix-public-reserved', action='store_const', const='fix_public_reserved', dest='command', help='Reset CVE NEW_RESERVED if now public')
    parser.add_argument('--fix-remove-bulk-cve-history', action='store_const', const='fix_remove_bulk_cve_history', dest='command', help='foo')

    parser.add_argument('--find-multiple-defects', action='store_const', const='find_multiple_defects', dest='command', help='foo')
    parser.add_argument('--find-duplicate-names', action='store_const', const='find_duplicate_names', dest='command', help='foo')

    parser.add_argument('--fix-defects-to-products', action='store_const', const='fix_defects_to_products', dest='command', help='foo')
    parser.add_argument('--find-bad-links', action='store_const', const='find_bad_links', dest='command', help='Find bad links, e.g. "orm_cvesource" (with "-f" to fix)')

    parser.add_argument('--force', '-f', action='store_true', dest='force', help='Force the update')
    parser.add_argument('--update-skip-history', '-H', action='store_true', dest='update_skip_history', help='Skip history updates')
    parser.add_argument('--verbose', '-v', action='store_true', dest='verbose', help='Debugging: verbose output')
    parser.add_argument('--skip', dest='skip', help='Debugging: skip record count')
    parser.add_argument('--count', dest='count', help='Debugging: short run record count')

    args = parser.parse_args()

    master_log = open(os.path.join(script_pathname, "update_logs/master_log.txt"), "a")

    verbose = args.verbose
    if None != args.skip:
        cmd_skip = int(args.skip)
    if None != args.count:
        cmd_count = int(args.count)
    force = args.force

    if args.sources:
        if args.sources.startswith('s'):
            sources("set")
        elif 0 <= args.sources.find('nist'):
            sources("reset_not_nist")
        elif args.sources.startswith('r'):
            sources("reset")
        elif args.sources.startswith('t'):
            sources("triage_keywords")
        else:
            sources("display")
    elif 'reset_sources' == args.command:
        sources('reset')
    elif 'settings' == args.command:
        settings()

    elif args.remove_app_sources:
        remove_app_sources(args.remove_app_sources)

    elif 'fix_name_sort' == args.command:
        fix_name_sort()
    elif 'fix_cve_recommend' == args.command:
        fix_cve_recommend()
    elif 'fix_new_reserved' == args.command:
        fix_new_reserved()
    elif 'fix_new_tags' == args.command:
        fix_new_tags()
    elif args.fix_srt_datetime:
        fix_srt_datetime(args.fix_srt_datetime)
    elif args.fix_reset_nist_to_create:
        fix_reset_nist_to_create(args.fix_reset_nist_to_create)
    elif 'fix_missing_create_dates' == args.command:
        fix_missing_create_dates()
    elif 'fix_public_reserved' == args.command:
        fix_public_reserved()
    elif 'fix_remove_bulk_cve_history' == args.command:
        fix_remove_bulk_cve_history()
    elif 'fix_defects_to_products' == args.command:
        fix_defects_to_products()


    elif 'find_multiple_defects' == args.command:
        find_multiple_defects()
    elif 'find_duplicate_names' == args.command:
        find_duplicate_names()
    elif 'find_bad_links' == args.command:
        find_bad_links()


    else:
        print("Command not found")
    master_log.close()

if __name__ == '__main__':
    script_pathname = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
    main(sys.argv[1:])