This file is indexed.

/usr/sbin/openvas-migrate-to-postgres is in openvas-manager 6.0.9-2.

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

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
#!/bin/sh
#
# migrate-to-postgres
# This script migrates an OpenVAS installation from SQLite to Postgres.
#
# Authors:
# Timo Pollmeier <timo.pollmeier@greenbone.net>
# Matthew Mundell <matthew.mundell@greenbone.net>
#
# Copyright:
# Copyright (C) 2014 Greenbone Networks GmbH
#
# 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
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

VERSION=20140904

# SETTINGS
# ========

# SCRIPT_NAME is the name the script will use to identify itself and to mark
# log messages.
SCRIPT_NAME="openvas-migrate-to-postgres"

# LOG_CMD defines the command to use for logging. To have logger log to stderr
# as well as syslog, add "-s" here.
LOG_CMD="logger -s -t $SCRIPT_NAME"

SQLITE3="sqlite3 -noheader -bail"
PSQL="psql -v ON_ERROR_STOP=1 -q --pset pager=off -d tasks -t"

# Maximum number of retries if database is locked
if [ -z "$MAX_SQL_RETRIES" ]; then
  MAX_SQL_RETRIES="1" # 0 : try only once
fi

# Delay between retries
if [ -z "$SQL_RETRY_DELAY" ]; then
  SQL_RETRY_DELAY="10m" # allowed unit suffixes: see sleep command
fi

[ -r /etc/openvas/migrate-to-postgres.conf ] && . /etc/openvas/migrate-to-postgres.conf

SQLITE_DB_DIR="/var/lib/openvas/mgr"
SQLITE_DB="$SQLITE_DB_DIR/tasks.db"

SQLITE=`command -v sqlite3`

log_debug () {
  $LOG_CMD -p daemon.debug $1
}

log_info () {
  $LOG_CMD -p daemon.info $1
}

log_notice () {
  $LOG_CMD -p daemon.notice $1
}

log_warning () {
  $LOG_CMD -p daemon.warning $1
}

log_err () {
  $LOG_CMD -p daemon.err $1
}

reset_sql_tries () {
  try_sql=1
  sql_retries=0
}

test_sql_exit () {
  exit_code=$?
  try_sql=0
  if [ 0 -ne "$exit_code" ]
  then
    log_err "$1: sql command exited with code $exit_code."
    exit 1
  fi
}

sqlite () {
  $SQLITE3 $SQLITE_DB "$1"
}

pg () {
  log_debug "SQL: $1"
  $PSQL -c "$1"
  exit_code=$?
  if [ 0 -ne "$exit_code" ]
  then
    log_err "$1: psql exited with code $exit_code for sql: $1."
    exit 1
  fi
}

does_pg_db_exist () {
  PG_DB_EXISTS=`pg "SELECT EXISTS (SELECT table_name
                    FROM information_schema.tables
                    WHERE table_catalog = 'tasks'
                    AND table_schema = 'public'
                    AND table_name = 'meta')
                    ::integer;"`
  return $PG_DB_EXISTS
}

is_db_broken () {
  log_info "Checking SQLite3 database."
  DB_BROKEN=0
  if [ ! -e $SQLITE_DB ]
  then
    return
  fi

  # Index report_hosts_by_host may have been created with COLLATE collate_ip.
  # collate_ip has been removed.  So just recreate the index.
  reset_sql_tries
  until [ "$try_sql" -eq 0 ]
  do
    sqlite "DROP INDEX report_hosts_by_host;"
    test_sql_exit "Could not drop index report_hosts_by_host"
  done
  reset_sql_tries
  until [ "$try_sql" -eq 0 ]
  do
    sqlite "CREATE INDEX report_hosts_by_host ON report_hosts (host);"
    test_sql_exit "Could not create index report_hosts_by_host"
  done

  reset_sql_tries
  until [ "$try_sql" -eq 0 ]
  do
    DB_INTEGRITY=`sqlite "PRAGMA integrity_check;"`
    test_sql_exit "Could not check CERT database integrity"
  done
  if [ "$DB_INTEGRITY" != "ok" ]
  then
    DB_BROKEN=1
    log_warning "Database integrity check failed."
  fi
}

do_help () {
  echo "$0: Migrate Manager database from SQLite3 to Postgres"
  echo " --help     display this help"
  echo " --selftest perform self-test"
  echo " --version  display version"
  echo ""
  exit 0
}

create_tables_133() {
  log_info "Creating tables."

  pg "CREATE TABLE IF NOT EXISTS current_credentials
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL);";

  pg "CREATE TABLE IF NOT EXISTS meta
       (id SERIAL PRIMARY KEY,
        name text UNIQUE NOT NULL,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS users
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        password text,
        timezone text,
        hosts text,
        hosts_allow integer,
        ifaces text,
        ifaces_allow integer,
        method text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS agents
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        installer bytea,
        installer_64 text,
        installer_filename text,
        installer_signature_64 text,
        installer_trust integer,
        installer_trust_time integer,
        howto_install text,
        howto_use text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS agents_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        installer bytea,
        installer_64 text,
        installer_filename text,
        installer_signature_64 text,
        installer_trust integer,
        installer_trust_time integer,
        howto_install text,
        howto_use text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS alerts
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        event integer,
        condition integer,
        method integer,
        filter integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS alerts_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        event integer,
        condition integer,
        method integer,
        filter integer,
        filter_location integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS alert_condition_data
       (id SERIAL PRIMARY KEY,
        alert integer REFERENCES alerts (id) ON DELETE RESTRICT,
        name text,
        data text);";

  pg "CREATE TABLE IF NOT EXISTS alert_condition_data_trash
       (id SERIAL PRIMARY KEY,
        alert integer REFERENCES alerts_trash (id) ON DELETE RESTRICT,
        name text,
        data text);";

  pg "CREATE TABLE IF NOT EXISTS alert_event_data
       (id SERIAL PRIMARY KEY,
        alert integer REFERENCES alerts (id) ON DELETE RESTRICT,
        name text,
        data text);";

  pg "CREATE TABLE IF NOT EXISTS alert_event_data_trash
       (id SERIAL PRIMARY KEY,
        alert integer REFERENCES alerts_trash (id) ON DELETE RESTRICT,
        name text,
        data text);";

  pg "CREATE TABLE IF NOT EXISTS alert_method_data
       (id SERIAL PRIMARY KEY,
        alert integer REFERENCES alerts (id) ON DELETE RESTRICT,
        name text,
        data text);";

  pg "CREATE TABLE IF NOT EXISTS alert_method_data_trash
       (id SERIAL PRIMARY KEY,
        alert integer REFERENCES alerts_trash (id) ON DELETE RESTRICT,
        name text,
        data text);";

  pg "CREATE TABLE IF NOT EXISTS filters
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        type text,
        term text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS filters_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        type text,
        term text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS groups
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS groups_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS group_users
       (id SERIAL PRIMARY KEY,
        \"group\" integer REFERENCES groups (id) ON DELETE RESTRICT,
        \"user\" integer REFERENCES users (id) ON DELETE RESTRICT);";

  pg "CREATE TABLE IF NOT EXISTS group_users_trash
       (id SERIAL PRIMARY KEY,
        \"group\" integer REFERENCES groups_trash (id) ON DELETE RESTRICT,
        \"user\" integer REFERENCES users (id) ON DELETE RESTRICT);";

  pg "CREATE TABLE IF NOT EXISTS roles
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS roles_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS role_users
       (id SERIAL PRIMARY KEY,
        role integer REFERENCES roles (id) ON DELETE RESTRICT,
        \"user\" integer REFERENCES users (id) ON DELETE RESTRICT);";

  pg "CREATE TABLE IF NOT EXISTS role_users_trash
       (id SERIAL PRIMARY KEY,
        role integer REFERENCES roles (id) ON DELETE RESTRICT,
        \"user\" integer REFERENCES users (id) ON DELETE RESTRICT);";

  pg "CREATE TABLE IF NOT EXISTS nvt_selectors
       (id SERIAL PRIMARY KEY,
        name text,
        exclude integer,
        type integer,
        family_or_nvt text,
        family text);";

  pg "CREATE TABLE IF NOT EXISTS port_lists
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS port_lists_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS port_ranges
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        port_list integer REFERENCES port_lists (id) ON DELETE RESTRICT,
        type integer,
        start integer,
        \"end\" integer,
        comment text,
        exclude integer);";

  pg "CREATE TABLE IF NOT EXISTS port_ranges_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        port_list integer REFERENCES port_lists_trash (id) ON DELETE RESTRICT,
        type integer,
        start integer,
        \"end\" integer,
        comment text,
        exclude integer);";

  pg "CREATE TABLE IF NOT EXISTS port_names
       (id SERIAL PRIMARY KEY,
        number integer,
        protocol text,
        name text,
        UNIQUE (number, protocol));";

  pg "CREATE TABLE IF NOT EXISTS lsc_credentials
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        login text,
        password text,
        comment text,
        private_key text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS lsc_credentials_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        login text,
        password text,
        comment text,
        private_key text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS targets
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        hosts text,
        exclude_hosts text,
        reverse_lookup_only integer,
        reverse_lookup_unify integer,
        comment text,
        lsc_credential integer,
        ssh_port text,
        smb_lsc_credential integer,
        port_range integer REFERENCES port_lists (id) ON DELETE RESTRICT,
        alive_test integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS targets_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        hosts text,
        exclude_hosts text,
        reverse_lookup_only integer,
        reverse_lookup_unify integer,
        comment text,
        lsc_credential integer,
        ssh_port text,
        smb_lsc_credential integer,
        port_range integer,
        ssh_location integer,
        smb_location integer,
        port_list_location integer,
        alive_test integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS configs
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        nvt_selector text,
        comment text,
        family_count integer,
        nvt_count integer,
        families_growing integer,
        nvts_growing integer,
        type integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS configs_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        nvt_selector text,
        comment text,
        family_count integer,
        nvt_count integer,
        families_growing integer,
        nvts_growing integer,
        type integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS config_preferences
       (id SERIAL PRIMARY KEY,
        config integer REFERENCES configs (id) ON DELETE RESTRICT,
        type text,
        name text,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS config_preferences_trash
       (id SERIAL PRIMARY KEY,
        config integer REFERENCES configs_trash (id) ON DELETE RESTRICT,
        type text,
        name text,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS schedules
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        first_time integer,
        period integer,
        period_months integer,
        duration integer,
        timezone text,
        initial_offset integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS schedules_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        first_time integer,
        period integer,
        period_months integer,
        duration integer,
        timezone text,
        initial_offset integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS slaves
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        host text,
        port text,
        login text,
        password text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS slaves_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        host text,
        port text,
        login text,
        password text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS scanners
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text,
        comment text,
        host text,
        port integer,
        type integer,
        ca_pub text,
        key_pub text,
        key_priv text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS scanners_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text,
        comment text,
        host text,
        port integer,
        type integer,
        ca_pub text,
        key_pub text,
        key_priv text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS tasks
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text,
        hidden integer,
        comment text,
        run_status integer,
        start_time integer,
        end_time integer,
        config integer,
        target integer,
        schedule integer,
        schedule_next_time integer,
        slave integer,
        scanner integer,
        config_location integer,
        target_location integer,
        schedule_location integer,
        slave_location integer,
        upload_result_count integer,
        hosts_ordering text,
        alterable integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS task_files
       (id SERIAL PRIMARY KEY,
        task integer REFERENCES tasks (id) ON DELETE RESTRICT,
        name text,
        content text);";

  pg "CREATE TABLE IF NOT EXISTS task_alerts
       (id SERIAL PRIMARY KEY,
        task integer REFERENCES tasks (id) ON DELETE RESTRICT,
        alert integer,
        alert_location integer);";

  pg "CREATE TABLE IF NOT EXISTS task_preferences
       (id SERIAL PRIMARY KEY,
        task integer REFERENCES tasks (id) ON DELETE RESTRICT,
        name text,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS reports
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        hidden integer,
        task integer REFERENCES tasks (id) ON DELETE RESTRICT,
        date integer,
        start_time integer,
        end_time integer,
        nbefile text,
        comment text,
        scan_run_status integer,
        slave_progress integer,
        slave_task_uuid text,
        slave_uuid text,
        slave_name text,
        slave_host text,
        slave_port integer,
        source_iface text);";

  pg "CREATE TABLE IF NOT EXISTS report_counts
       (id SERIAL PRIMARY KEY,
        report integer REFERENCES reports (id) ON DELETE RESTRICT,
        \"user\" integer REFERENCES users (id) ON DELETE RESTRICT,
        severity decimal,
        count integer,
        override integer,
        end_time integer);";

  pg "CREATE TABLE IF NOT EXISTS results
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        task integer REFERENCES tasks (id) ON DELETE RESTRICT,
        host text,
        port text,
        nvt text,
        type text,
        description text,
        report integer REFERENCES reports (id) ON DELETE RESTRICT,
        nvt_version text,
        severity real,
        qod integer,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        date integer);";

  pg "CREATE TABLE IF NOT EXISTS report_formats
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        extension text,
        content_type text,
        summary text,
        description text,
        signature text,
        trust integer,
        trust_time integer,
        flags integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS report_formats_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        extension text,
        content_type text,
        summary text,
        description text,
        signature text,
        trust integer,
        trust_time integer,
        flags integer,
        original_uuid text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS report_format_params
       (id SERIAL PRIMARY KEY,
        report_format integer REFERENCES report_formats (id) ON DELETE RESTRICT,
        name text,
        type integer,
        value text,
        type_min bigint,
        type_max bigint,
        type_regex text,
        fallback text);";

  pg "CREATE TABLE IF NOT EXISTS report_format_params_trash
       (id SERIAL PRIMARY KEY,
        report_format integer REFERENCES report_formats_trash (id) ON DELETE RESTRICT,
        name text,
        type integer,
        value text,
        type_min bigint,
        type_max bigint,
        type_regex text,
        fallback text);";

  pg "CREATE TABLE IF NOT EXISTS report_format_param_options
       (id SERIAL PRIMARY KEY,
        report_format_param integer REFERENCES report_format_params (id) ON DELETE RESTRICT,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS report_format_param_options_trash
       (id SERIAL PRIMARY KEY,
        report_format_param integer REFERENCES report_format_params_trash (id) ON DELETE RESTRICT,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS report_hosts
       (id SERIAL PRIMARY KEY,
        report integer REFERENCES reports (id) ON DELETE RESTRICT,
        host text,
        start_time integer,
        end_time integer,
        attack_state text,
        current_port integer,
        max_port integer);";

  pg "CREATE TABLE IF NOT EXISTS report_host_details
       (id SERIAL PRIMARY KEY,
        report_host integer REFERENCES report_hosts (id) ON DELETE RESTRICT,
        source_type text,
        source_name text,
        source_description text,
        name text,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS report_results
       (id SERIAL PRIMARY KEY,
        report integer REFERENCES reports (id) ON DELETE RESTRICT,
        result integer REFERENCES results (id) ON DELETE RESTRICT);";

  pg "CREATE TABLE IF NOT EXISTS nvt_preferences
       (id SERIAL PRIMARY KEY,
        name text UNIQUE NOT NULL,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS nvts
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        oid text UNIQUE NOT NULL,
        version text,
        name text,
        comment text,
        summary text,
        copyright text,
        cve text,
        bid text,
        xref text,
        tag text,
        category text,
        family text,
        cvss_base text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS nvt_cves
       (id SERIAL PRIMARY KEY,
        nvt integer REFERENCES nvts (id) ON DELETE RESTRICT,
        oid text,
        cve_name text);";

  pg "CREATE TABLE IF NOT EXISTS notes
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        nvt text NOT NULL,
        creation_time integer,
        modification_time integer,
        text text,
        hosts text,
        port text,
        severity double precision,
        task integer,
        result integer,
        end_time integer);";

  pg "CREATE TABLE IF NOT EXISTS notes_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        nvt text NOT NULL,
        creation_time integer,
        modification_time integer,
        text text,
        hosts text,
        port text,
        severity double precision,
        task integer,
        result integer,
        end_time integer);";

  pg "CREATE TABLE IF NOT EXISTS overrides
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        nvt text NOT NULL,
        creation_time integer,
        modification_time integer,
        text text,
        hosts text,
        new_severity double precision,
        port text,
        severity double precision,
        task integer,
        result integer,
        end_time integer);";

  pg "CREATE TABLE IF NOT EXISTS overrides_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        nvt text NOT NULL,
        creation_time integer,
        modification_time integer,
        text text,
        hosts text,
        new_severity double precision,
        port text,
        severity double precision,
        task integer,
        result integer,
        end_time integer);";

  pg "CREATE TABLE IF NOT EXISTS permissions
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        resource_type text,
        resource integer,
        resource_uuid text,
        resource_location integer,
        subject_type text,
        subject integer,
        subject_location integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS permissions_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        resource_type text,
        resource integer,
        resource_uuid text,
        resource_location integer,
        subject_type text,
        subject integer,
        subject_location integer,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS settings
       (id SERIAL PRIMARY KEY,
        uuid text NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        value text);";

  pg "CREATE TABLE IF NOT EXISTS tags
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        resource_type text,
        resource integer,
        resource_uuid text,
        resource_location integer,
        active integer,
        value text,
        creation_time integer,
        modification_time integer);";

  pg "CREATE TABLE IF NOT EXISTS tags_trash
       (id SERIAL PRIMARY KEY,
        uuid text UNIQUE NOT NULL,
        owner integer REFERENCES users (id) ON DELETE RESTRICT,
        name text NOT NULL,
        comment text,
        resource_type text,
        resource integer,
        resource_uuid text,
        resource_location integer,
        active integer,
        value text,
        creation_time integer,
        modification_time integer);";
}

migrate_rest () {
  # Remove stray task_alerts.
  sqlite "DELETE FROM task_alerts WHERE alert_location = 0 AND alert NOT IN (SELECT id FROM alerts);"
  test_sql_exit "Failed to clean up task_alerts"
  sqlite "DELETE FROM task_alerts WHERE alert_location = 1 AND alert NOT IN (SELECT id FROM alerts_trash);"
  test_sql_exit "Failed to clean up task_alerts (trash alerts)"

  # Remove stray report_format_params_trash.
  sqlite "DELETE FROM report_format_params_trash WHERE report_format NOT IN (SELECT id FROM report_formats_trash);"
  test_sql_exit "Failed to clean up report_format_params_trash"

  # Remove stray report_format_param_options_trash.
  sqlite "DELETE FROM report_format_param_options_trash WHERE report_format_param NOT IN (SELECT id FROM report_format_params_trash);"
  test_sql_exit "Failed to clean up report_format_param_options_trash"

  # Remove stray report_hosts.  Not sure where these came from.
  sqlite "DELETE FROM report_hosts WHERE report NOT IN (SELECT id FROM reports);"
  test_sql_exit "Failed to clean up report_hosts"

  # Remove stray report_host_details.  Not sure where these came from.
  sqlite "DELETE FROM report_host_details WHERE report_host NOT IN (SELECT id FROM report_hosts);"
  test_sql_exit "Failed to clean up report_host_details"

  # Make end_time in tasks consistent.
  #
  # Manager --migrate only does this in migrate_135_to_136, but Postgres needs
  # the end_times to be a single type for import.
  sqlite "UPDATE tasks SET end_time = (SELECT reports.end_time FROM reports WHERE task = tasks.id ORDER BY id DESC LIMIT 1) WHERE EXISTS (SELECT id FROM reports WHERE task = tasks.id);"
  test_sql_exit "Failed to make end_time in tasks consistent"

  # Make end_time in report_hosts consistent.

  # 2011-11-03T12:41:34+02:00, 2011-11-08T19:57:06Z
  sqlite "UPDATE report_hosts SET end_time = strftime ('%s', end_time) WHERE end_time GLOB '*-*-*T*:*:*[+-]*:*' OR end_time GLOB '*-*-*T*:*:*Z';"
  test_sql_exit "Failed to make end_time in report_hosts consistent"

  # Fri Sep  3 05:12:34 2010
  #
  # Assume that this time matches the current timezone, may change the
  # time, but it seems these are only from very old reports anyway.
  echo "BEGIN EXCLUSIVE;
        CREATE TEMPORARY TABLE months (number, name);
        INSERT INTO months (number, name) VALUES ('01', 'Jan');
        INSERT INTO months (number, name) VALUES ('02', 'Feb');
        INSERT INTO months (number, name) VALUES ('03', 'Mar');
        INSERT INTO months (number, name) VALUES ('04', 'Apr');
        INSERT INTO months (number, name) VALUES ('05', 'May');
        INSERT INTO months (number, name) VALUES ('06', 'Jun');
        INSERT INTO months (number, name) VALUES ('07', 'Jul');
        INSERT INTO months (number, name) VALUES ('08', 'Aug');
        INSERT INTO months (number, name) VALUES ('09', 'Sep');
        INSERT INTO months (number, name) VALUES ('10', 'Oct');
        INSERT INTO months (number, name) VALUES ('11', 'Nov');
        INSERT INTO months (number, name) VALUES ('12', 'Dec');
        UPDATE report_hosts SET end_time = strftime ('%s', substr (end_time, 21) || '-' || (select number from months where name = substr (end_time, 5, 3)) || '-' || replace (substr (end_time, 9, 2), ' ', '0') || 'T' || substr (end_time, 12, 9)) WHERE end_time GLOB '??? ??? ?? ??:??:?? ????';
        COMMIT;" | $SQLITE3 -batch $SQLITE_DB
  test_sql_exit "Failed to make end_time in report_hosts consistent"

  log_info "Dumping SQLite3 data:"
  TEMP_DIR=`mktemp -d`
  log_debug "TEMP_DIR: $TEMP_DIR"

  # These must be ordered to respect foreign keys.
  #
  # To get all tables use ".tables" or
  #     SELECT tbl_name FROM sqlite_master WHERE type='table' and tbl_name not like 'sqlite_%'
  #
  # These table are left out: report_counts nvts nvt_cves
  #
  TABLES="users configs config_preferences meta nvt_preferences nvt_selectors lsc_credentials lsc_credentials_trash port_lists port_ranges targets schedules slaves tasks reports report_hosts report_formats report_format_params report_format_param_options results report_results task_files configs_trash config_preferences_trash report_formats_trash report_format_params_trash report_format_param_options_trash schedules_trash slaves_trash targets_trash report_host_details task_preferences port_lists_trash port_ranges_trash alerts_trash alert_event_data_trash alert_method_data_trash alerts alert_condition_data alert_event_data alert_method_data task_alerts alert_condition_data_trash groups group_users filters filters_trash port_names settings roles role_users overrides overrides_trash notes notes_trash groups_trash roles_trash tags_trash group_users_trash role_users_trash scanners scanners_trash permissions_trash permissions tags"

  log_debug "TABLES: $TABLES"
  for TABLE in $TABLES; do
    # Get the Postgres columns because the import CSV must be in that order.
    #
    # This also works around extra columns that were hanging around in old
    # database.
    #
    COLS=`pg "SELECT string_agg ('\"' || column_name || '\"', ',') from (select column_name from information_schema.columns where table_schema = 'public' and table_name = '$TABLE' order by ordinal_position) as sub;"`
    log_debug "COLS: $COLS"
    # Pipe SQLite CSV output into Postgres COPY FROM.
    $SQLITE3 -csv $SQLITE_DB "SELECT $COLS FROM $TABLE;" | pg "COPY $TABLE ($COLS) FROM STDIN DELIMITER ',' CSV";
    test_sql_exit "Could not generate CSV for $TABLE"
  done

  # Force a --rebuild.
  pg "DELETE FROM meta WHERE name = 'nvts_feed_version';"

  log_info "Resetting Postgres sequences"
  # Reset ID sequences, because the COPY specified the ID values explicitly.
  pg "SELECT 'SELECT 1'
             || ' WHERE'
             || ' SETVAL'
             || '  (' || quote_literal (quote_ident (PGT.schemaname)
             ||          '.' || quote_ident (S.relname)) || ','
             ||     ' COALESCE'
             ||     '  ((SELECT MAX (' || quote_ident (C.attname) || ')'
             ||     '    FROM ' || quote_ident (PGT.schemaname)
             ||                    '.' || quote_ident (T.relname) || '),'
             ||     '   1))'
             || ' < 0;'
      FROM pg_class AS S,
           pg_depend AS D,
           pg_class AS T,
           pg_attribute AS C,
           pg_tables AS PGT
      WHERE S.relkind = 'S'
      AND S.oid = D.objid
      AND D.refobjid = T.oid
      AND D.refobjid = C.attrelid
      AND D.refobjsubid = C.attnum
      AND T.relname = PGT.tablename
      ORDER BY S.relname;" > $TEMP_DIR/reset.sql;
  test_sql_exit "Could not generate reset SQL"
  $PSQL -f $TEMP_DIR/reset.sql | sed '/^\s*$/d'
  test_sql_exit "Could not run reset SQL"

  rm -rf $TEMP_DIR
}

migrate () {
  DB_VERSION=`sqlite "select value from meta where name = 'database_version';" 2>/dev/null | tr -d '\n\r' || echo 0`
  case "$DB_VERSION" in
    133)
      log_info "Migrating database (version 133)."
      create_tables_133;
      migrate_rest;;

    134)
      log_info "Migrating database (version 134)."
      create_tables_133;

      pg "ALTER TABLE targets ADD COLUMN esxi_lsc_credential integer;"
      pg "ALTER TABLE targets_trash ADD COLUMN esxi_lsc_credential integer;"
      pg "ALTER TABLE targets_trash ADD COLUMN esxi_location integer;"

      migrate_rest;;

    135)
      log_info "Migrating database (version 135)."
      create_tables_133;

      pg "ALTER TABLE targets ADD COLUMN esxi_lsc_credential integer;"
      pg "ALTER TABLE targets_trash ADD COLUMN esxi_lsc_credential integer;"
      pg "ALTER TABLE targets_trash ADD COLUMN esxi_location integer;"

      migrate_rest

      pg "DROP TABLE report_results;";;

    136)
      log_info "Migrating database (version 136)."
      create_tables_133;

      pg "ALTER TABLE targets ADD COLUMN esxi_lsc_credential integer;"
      pg "ALTER TABLE targets_trash ADD COLUMN esxi_lsc_credential integer;"
      pg "ALTER TABLE targets_trash ADD COLUMN esxi_location integer;"

	  pg "UPDATE tasks
	      SET end_time = (SELECT reports.end_time FROM reports
		                  WHERE task = tasks.id ORDER BY id DESC LIMIT 1)
		  WHERE EXISTS (SELECT id FROM reports WHERE task = tasks.id);"

	  pg "UPDATE tasks
	      SET end_time = NULL
		  WHERE NOT EXISTS (SELECT id FROM reports WHERE task = tasks.id);"

      migrate_rest

      pg "DROP TABLE report_results;";;

    *)
      log_notice "Database version not supported."
      exit 1
  esac
}

do_self_test () {
  if [ -z "$SELFTEST_STDERR" ]
  then
    SELFTEST_STDERR=0
  fi

  if [ -z "$SQLITE" ]; then
    if [ 0 -ne $SELFTEST_STDERR ]
    then
      echo "sqlite3 not found (required)." 1>&2
    fi
    log_err "sqlite3 not found (required)."
    SELFTEST_FAIL=1
  fi

  if [ ! -f $SQLITE_DB ]
  then
    if [ 0 -ne $SELFTEST_STDERR ]
    then
      echo "SQLITE_DB ($SQLITE_DB) not found." 1>&2
    fi
    log_err "SQLITE_DB ($SQLITE_DB) not found."
    SELFTEST_FAIL=1
  fi
}

while test $# -gt 0; do
 case "$1" in
        --version)
          echo $VERSION
          exit 0
           ;;
        --help)
          do_help
          exit 0
          ;;
        --selftest)
          SELFTEST_FAIL=0
          SELFTEST_STDERR=1
          do_self_test
          exit $SELFTEST_FAIL
          ;;
      esac
      shift
done

SELFTEST_FAIL=0
do_self_test
if [ $SELFTEST_FAIL -ne 0 ]
then
  exit 1
fi

is_db_broken
if [ $DB_BROKEN -eq 1 ]
then
  log_notice "Corrupt database, skipping migration."
  exit 1
else
  does_pg_db_exist
  if [ $PG_DB_EXISTS -eq 1 ]
  then
    log_notice "Postgres database exists already, skipping migration."
    exit 0
  fi
fi
migrate
log_info "Done."

exit 0