scripts / analyse-votes-AN /
Sébastien Marque améliore la sortie
98426b7 5 years ago
2 contributor
580 lines | 27.699kb
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#!/bin/bash

for tool in sqlite3 getopt md5sum mktemp; do
    which $tool > /dev/null 2>&1 || {
        echo missing tool $tool
        exit 1
    }
done

IFS_=$IFS

function sqlite_request () {
    sqlite3 "$in_ram_database" <<< "$1"
}

function create_database () {
    if test ${#groupes[@]} -eq 0; then
        echo "unable to find groupes in $config_file" >&2
        exit 1
    fi

    sqlite_request "create table if not exists votes (id integer primary key, nom text)"
    sqlite_request "create table if not exists url (id integer primary key autoincrement, url text)"
    sqlite_request "create table if not exists députés (id integer primary key autoincrement, nom text, groupe integer)"
    sqlite_request "create table if not exists groupes (id integer primary key autoincrement, nom text, nom_court text)"
    sqlite_request "create table if not exists scrutins (num integer primary key, date text not null, intitulé text non null, adoption boolean, url integer)"
    sqlite_request "create table if not exists dépouillement (député integer not null, scrutin integer not null, groupe integer not null, vote integer not null)"

    v_id=0
    for v in Pour Contre Abstention Non-votant; do
        if test -z $(sqlite_request "select nom from votes where id is $v_id"); then
            sqlite_request "insert into votes values ($v_id, '$v')"
        else
            test -z $(sqlite_request "select nom from votes where id is $v_id and nom is '$v'") \
                && sqlite_request "update votes set nom = '$v' where id is $v_id)"
        fi
        let v_id++
    done
    unset v_id v

    for g in ${!groupes[@]}; do
        test -z $(sqlite_request "select id from groupes where nom is '${groupes[$g]}' and nom_court is '$g'") \
            && sqlite_request "insert into groupes (nom, nom_court) values ('${groupes[$g]}', '$g')"
    done
    unset g groupes

    test -z $(sqlite_request "select id from url where id = 0") \
        && sqlite_request "insert into url values (0, '')"
}

function update_database () {
    test "$no_db_update" = $true_flag && return
    tempfile="/dev/shm/scrutin.$$"
    progress=0
    first_=$first
    first=$(sqlite_request "select count(num) from scrutins")
    if test ${first:-0} -lt $last; then
        echo "récupération des scrutins n°$((${first:-0}+1)) à n°$last dans "$database" (à conserver autant que possible)" >&2

        url_database=/dev/shm/url_database
        : > "$url_database"
        test $((last % 100)) -ne 0 && last_offset=0
        for offset in $(seq $((last - 100)) -100 ${first:-0} ) $last_offset; do
            wget -qO- "http://www2.assemblee-nationale.fr/scrutins/liste/(offset)/$offset/(legislature)/15/(type)/TOUS/(idDossier)/TOUS" \
                | awk '
                    /<td class="denom">/ {
                        scrutin = gensub(/^.+denom.>([[:digit:]]+).*<.td./,"\\1","1",$0)
                    }
                    /<td class="desc">.+dossier<.a/ {
                        a[scrutin] = gensub(/^.+.<a href="(.+)">dossier<.a>.*$/,"\\1","1",$0)
                    }
                    END {
                        for (i in a)
                            print gensub("*","","1",i) "|" a[i]
                    }' >> "$url_database"
        done
        sort -u "$url_database" > "${url_database}.sorted"
        mv -f "${url_database}.sorted" "$url_database"

        IFS=$'\n'
        begin=$(date +%s)
        for scrutin in $(seq $((${first:-0}+1)) $last); do
            wget -qO- "http://www2.assemblee-nationale.fr/scrutins/detail/(legislature)/15/(num)/$scrutin" \
                |  sed -r '0,/< *div class="titre-bandeau-bleu +to-print" *>/d; /< *script +type="text\/javascript" *>/,$d' > $tempfile

            unset title date adoption url id_url

            title=$(sed -rn '/<h1 class="">Analyse du scrutin n° '$scrutin'/n; s,^.*<h3 class="president-title">(.+).</h3>,\1,p' $tempfile \
                    | sed "s/;//g; s/[ \t][ \t]+/ /g; s/^Scrutin public sur *//; s/^l[ae']s* *//")
            date=$(sed -rn 's,^.*<h1 class="">Analyse du scrutin n° '$scrutin'<br/>(.+) </h1>,\1,p' $tempfile)
            adoption=$(sed -rn 's,^.*<p class="annonce"><span class="annoncevote">(.+).</span></p>.*$,\1,p' $tempfile)
            test -n "$title" -a -n "$date" -a -n "$adoption" || {
                echo "erreur dans la récupération du scrutin $scrutin"
                exit 1
            }
            grep -q 'e a a' <<< "$adoption" && adoption=1 || adoption=0

            url=$(awk -F'|' "/^$scrutin\|/{print \$2}" "$url_database")
            id_url=$(sqlite_request "select id from url where url is '$url'")
            if test -z "$id_url"; then
                sqlite_request "insert into url (url) values ('$url')"
                id_url=$(sqlite_request "select id from url where url is '$url'")
            fi

            sqlite_request "insert into scrutins values ($scrutin, '$date', \"${title//\"}\", $adoption, ${id_url:-0})"

            for v in $(sqlite_request "select * from votes"); do
                for g in $(sqlite_request "select id,nom from groupes"); do
                    for d in $(sed -rn '/<p class="nomgroupe">'${g#*|}' <span class="block topmargin">/,/<div class="TTgroupe topmargin-lg">/p' $tempfile \
                        | sed -rn '/<p class="typevote">'${v#*|}':/,/<.div>/p' \
                        | sed 's,</li>,\n,g' \
                        | sed -rn '/<p class="typevote">/d; s,^\s*<li>\s*,,; s,&nbsp;, ,g; s/^\s*//; s/M(me|\.) //; s/ \(.*$//; s,<b>,,; s,</b>,,p'); do
                        d_id=$(sqlite_request "select id from députés where nom is \"$d\" and groupe is ${g%|*}")
                        if test -z "$d_id"; then
                            sqlite_request "insert into députés (nom, groupe) values (\"$d\", ${g%|*})"
                            d_id=$(sqlite_request "select id from députés where nom is \"$d\" and groupe is ${g%|*}")
                        fi
                        sqlite_request "insert into dépouillement values ($d_id, $scrutin, ${g%|*}, ${v%|*})"
                    done
                done
            done

            if test $(( ($scrutin - $first) * 100 / ( $last - $first ) )) -ne $progress; then
                progress=$(( ($scrutin - $first) * 100 / ( $last - $first ) ))
                if test $(($progress % ${update_progress:-1})) -eq 0; then
                    now=$(date +%s)
                    delta=$(( $now - $begin ))
#                   scrutin = first+1 à la première itération
                    echo $progress%, ETA: $(date +%H:%M:%S -d "$(($delta * ($last - $scrutin) / ($scrutin - $first) )) seconds")
                fi
            fi
        done
        rm -f "$url_database" "$tempfile"
    fi
    first=$first_
}

function write_comparaison () {
    result="comparaisons ${groupe[0]} avec ${groupe_ref:-GDR}${dossier:+ - ${dossier}}"
    content="/dev/shm/$result/content.xml"
    id_cols="Scrutin Date Titre Adoption"
    typevotes=$(sqlite_request "select nom from votes")
    nb_cols=$(( $(wc -w <<< $id_cols) + $(wc -w <<< $typevotes) * ${#groupe[@]} ))
    last_col=$(awk -v n=$nb_cols 'BEGIN{printf("%c%c", n < 27 ? "" : int(n/26) + 64, (n % 26) + (n % 26 == 0 ? 26 : 0) + 64)}' | tr -d '\0')

    echo "génération du fichier $result"

    mkdir -p "/dev/shm/$result/META-INF"

    cat > "/dev/shm/$result/META-INF/manifest.xml" << EOmetainf
<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
 <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="application/vnd.oasis.opendocument.spreadsheet"/>
 <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
EOmetainf

    printf 'application/vnd.oasis.opendocument.spreadsheet' > "/dev/shm/$result/mimetype"

    echo '<?xml version="1.0" encoding="UTF-8"?>' > "$content"

    cat >> "$content" << EOcontent
    <office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0" xmlns:presentation="urn:oasis:names:tc:opendocument:xmlns:presentation:1.0" xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Math/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1.0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" xmlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://openoffice.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" xmlns:dom="http://www.w3.org/2001/xml-events" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rpt="http://openoffice.org/2005/report" xmlns:of="urn:oasis:names:tc:opendocument:xmlns:of:1.2" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:grddl="http://www.w3.org/2003/g/data-view#" xmlns:tableooo="http://openoffice.org/2009/table" xmlns:drawooo="http://openoffice.org/2010/draw" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" xmlns:field="urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0" xmlns:formx="urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0" xmlns:css3t="http://www.w3.org/TR/css3-text/" office:version="1.2">
    <office:scripts/>
    <office:font-face-decls>
    <style:font-face style:name="Liberation Sans" svg:font-family="&apos;Liberation Sans&apos;" style:font-family-generic="swiss" style:font-pitch="variable"/>
    <style:font-face style:name="DejaVu Sans" svg:font-family="&apos;DejaVu Sans&apos;" style:font-family-generic="system" style:font-pitch="variable"/>
    <style:font-face style:name="FreeSans" svg:font-family="FreeSans" style:font-family-generic="system" style:font-pitch="variable"/>
    </office:font-face-decls>
    <office:automatic-styles>
EOcontent

    IFS=$'\n'
    for i in $(seq $nb_cols); do
        cat >> "$content" << EOcontent
            <style:style style:name="co$i" style:family="table-column">
            <style:table-column-properties fo:break-before="auto" style:column-width="30.00mm"/>
            </style:style>
EOcontent
    done

    cat >> "$content" << EOcontent
    <style:style style:name="ro1" style:family="table-row">
    <style:table-row-properties style:row-height="4.52mm" fo:break-before="auto" style:use-optimal-row-height="true"/>
    </style:style>
    <style:style style:name="ta1" style:family="table" style:master-page-name="Default">
    <style:table-properties table:display="true" style:writing-mode="lr-tb"/>
    </style:style>
    <style:style style:name="ce1" style:family="table-cell" style:parent-style-name="Default">
    <style:table-cell-properties fo:background-color="#cccccc"/>
    </style:style>
    </office:automatic-styles>
    <office:body>
    <office:spreadsheet>
    <table:calculation-settings table:automatic-find-labels="false"/>
    <table:table table:name="$result" table:style-name="ta1">
    <office:forms form:automatic-focus="false" form:apply-design-mode="false"/>
    <table:table-column table:style-name="co1" table:number-columns-repeated="$(wc -w <<< $id_cols)" table:default-cell-style-name="Default"/>
EOcontent

    for i in $(seq $(wc -w <<< $typevotes)); do
        cat >> "$content" << EOcontent
        <table:table-column table:style-name="co1" table:default-cell-style-name="ce1"/>
EOcontent
        for (( g = 1; g < ${#groupe[@]}; g++ )); do
            cat >> "$content" << EOcontent
            <table:table-column table:style-name="co1" table:default-cell-style-name="Default"/>
EOcontent
        done
    done
    echo '<table:table-row table:style-name="ro1">' >> "$content"

    IFS=$IFS_
    for colonne in $id_cols; do
        cat >> "$content" << EOcontent
            <table:table-cell office:value-type="string" calcext:value-type="string">
            <text:p>$colonne</text:p>
            </table:table-cell>
EOcontent
    done

    for typevote in $typevotes; do
        for g in "${groupe[@]}"; do
            cat >> "$content" << EOcontent
                <table:table-cell office:value-type="string" calcext:value-type="string">
                <text:p>$typevote - $g</text:p>
                </table:table-cell>
EOcontent
        done
    done

    echo '</table:table-row>' >> "$content"

    progress=0
    begin=$(date +%s)
    line=1
    test -z "$seq" && qty=$(( $last - $first ))
    IFS=$'\n'
    for scrutin in $(eval ${seq:-seq $first $last}); do

        data=$(sqlite_request "select date,intitulé,adoption,url.url from scrutins inner join url on scrutins.url = url.id where num is $scrutin")
        date=$(cut -d'|' -sf 1 <<< $data)
        title=$(cut -d'|' -sf 2 <<< $data)
        adoption=$(cut -d'|' -sf 3 <<< $data)
        url=$(cut -d'|' -sf 4 <<< $data)
        test $adoption -eq 1 && adoption='oui' || adoption='non'

        cat >> "$content" << EOcontent
            <table:table-row table:style-name="ro1">
EOcontent
        if test -n "$url"; then
            cat >> "$content" << EOcontent
                <table:table-cell office:value-type="string" calcext:value-type="string">
                <text:p><text:a xlink:href="$url" xlink:type="simple">$scrutin</text:a></text:p>
                </table:table-cell>
EOcontent
        else
            cat >> "$content" << EOcontent
                <table:table-cell office:value-type="float" office:value="$scrutin" calcext:value-type="float">
                <text:p>$scrutin</text:p>
                </table:table-cell>
EOcontent
        fi
        cat >> "$content" << EOcontent
            <table:table-cell office:value-type="string" calcext:value-type="string">
            <text:p>$date</text:p>
            </table:table-cell>
            <table:table-cell office:value-type="string" calcext:value-type="string">
            <text:p>${title//\'/&apos;}</text:p>
            </table:table-cell>
            <table:table-cell office:value-type="string" calcext:value-type="string">
            <text:p>${adoption}</text:p>
            </table:table-cell>
EOcontent
        for typevote in 0 1 2 3; do
            votes=$(sqlite_request "select
                                        count(député)
                                     from
                                        dépouillement
                                     where
                                        scrutin is $scrutin
                                     and
                                        vote is $typevote
                                     and
                                        groupe is ${groupe_id[0]} ${nom:+ and député is ${nom%|*}}")
            cat >> "$content" << EOcontent
                <table:table-cell office:value-type="float" office:value="$votes" calcext:value-type="float">
                <text:p>$votes</text:p>
                </table:table-cell>
EOcontent
            for (( g = 1; g < ${#groupe_id[@]}; g++ )); do
                votes=$(sqlite_request "select
                                            count(député)
                                         from
                                            dépouillement
                                         where
                                            scrutin is $scrutin
                                         and
                                            vote is $typevote
                                         and
                                            groupe is ${groupe_id[$g]}")
                cat >> "$content" << EOcontent
                    <table:table-cell office:value-type="float" office:value="$votes" calcext:value-type="float">
                    <text:p>$votes</text:p>
                    </table:table-cell>
EOcontent
            done
        done
        echo '</table:table-row>' >> "$content"

        if test $(( ($line * 100) / ${qty:-$last} )) -ne $progress; then
            progress=$(( ($line * 100) / ${qty:-$last} ))
            if test $(( $progress % ${generation_progress:-5} )) -eq 0; then
                now=$(date +%s)
                delta=$(( $now - $begin ))
                echo $progress%, ETA: $(date +%H:%M:%S -d "$(( $delta * (${qty:-$last} - $line) / $line )) seconds")
            fi
        fi

        let line++

    done
    echo

    cat >> "$content" << EOcontent
    </table:table>
    <table:named-expressions/>
    <table:database-ranges>
    <table:database-range table:name="__Anonymous_Sheet_DB__0" table:target-range-address="&apos;$result&apos;.D1:&apos;$result&apos;.$last_col$line" table:display-filter-buttons="true"/>
    </table:database-ranges>
    </office:spreadsheet>
    </office:body>
    </office:document-content>
EOcontent

    ( cd "/dev/shm/$result" && zip -r ../"$result" * > /dev/null 2>&1 && cd .. && rm -fr "$result" )

    mv -f "/dev/shm/$result.zip" "$result.ods"

    echo "$result.ods"
}

function save_database () {
    test -n "$database" -a -n "$in_ram_database" || return
    test -r "$in_ram_database" || return
    if test -r "$database" && md5sum $in_ram_database | sed "s,$in_ram_database,$database," | md5sum --status -c -; then
        rm -f $in_ram_database
    elif test -w "$database"; then
        mv -f $in_ram_database "$database"
    elif ! test -e "$database"; then
        mv $in_ram_database "$database"
    else
        rm -f $in_ram_database
    fi
}

trap save_database EXIT

true_flag=$(mktemp --dry-run XXXXX)

OPTS=$( getopt -l no-db-update,\
                  db-update-only,\
                  cible:,\
                  ref:,\
                  député:,\
                  premier-scrutin:,\
                  dernier-scrutin:,\
                  période:,\
                  liste-dossiers,\
                  liste-députés,\
                  dossiers,\
                  dossier:,\
                  conf:,\
                  database:,\
                  progrès-génération:\
                  progrès-update:,\
                  help \
                  -- "$@" )

eval set --$OPTS

while [[ $# -gt 0 ]]; do
    case "$1" in
        "--no-db-update")
#|ne met pas à jour la base de données
            no_db_update=$true_flag;;
        "--db-update-only")
#|ne génère pas de fichier de résultat
            db_update_only=$true_flag;;
        "--cible")
#<nom court du groupe>|génère un comparatif pour ce groupe. Par défaut LREM
            groupe[0]="${2^^}"
            shift;;
        "--ref")
#<nom court du groupe ou des groupes>|compare avec ce ou ces groupes. Si plusieurs groupes, ils sont séparés par une virgule, sans espace. Par défaut GDR
            groupe_ref="${2^^}"
            shift;;
        "--député")
#<nom>|filtre la cible sur un-e député-e sur le groupe cible (par défaut LREM). <nom> est insensible à la casse. Tout ou partie du nom ou du prénom peut être donné, espace compris. Caractère % utilisé comme caractère joker. Si aucune correspondance n'est trouvée avec un-e député-é, sortie en erreur. Si plusieurs député-e-s correspondent la liste est affichée et sortie en erreur.
            depute=$true_flag
            nom="$2"
            shift;;
        "--premier-scrutin")
#<numéro>|commence la génération du résultat à partir du scrutin <numéro>
            no_db_update=$true_flag
            first="$2"
            shift;;
        "--dernier-scrutin")
#<numéro>|termine la génération du résultat au scrutin <numéro>
            no_db_update=$true_flag
            last="$2"
            shift;;
        "--période")
#<jj/mm/aaaa:JJ/MM/AAAA>|génère un résultat pour les scrutins allant de jj/mm/aaaa à JJ/MM/AAAA
            periode=$true_flag
            no_db_update=$true_flag
            periode_value="$2"
            shift;;
        "--liste-députés-du-groupe")
#<nom court du groupe>|liste les député-e-s du groupe <nom court du groupe> sur la mandature
            liste_deputes=$true_flag
            liste_deputes_value="${2^^}"
            shift;;
        "--liste-députés")
#|liste tou-te-s les député-e-s de la mandature
            liste_deputes=$true_flag;;
        "--liste-dossiers")
#|affiche une liste numérotée des dossiers et sort
            liste_dossiers=$true_flag;;
        "--dossier")
#<numéro>|génère un résultat pour le dossier numéroté <numéro>
            dossier=$true_flag
            dossier_value="$2"
            shift;;
        "--dossiers")
#|sélection interactive du dossier
            dossier=$true_flag;;
        "--conf")
#<fichier>|indique le chemin vers le fichier de configuration. Par défaut "{_}.conf"
            test -r "$2" || {
                echo "config introuvable $2" >&2
                options_error=$true_flag
            }
            config_file="$2"
            shift;;
        "--database")
#<fichier>|indique le chemin vers la base de données SQLite3 contenant les informations. Par défaut "{_}.db"
            test -r "$2" && file -b "$2" | grep -q '^SQLite 3.x database' || {
                echo "erreur sur option database: fichier '$2' introuvable ou pas une base SQLite 3" >&2
                options_error=$true_flag
            }
            database="$2"
            shift;;
        "--progrès-génération")
#<chiffre>|affiche de la progression de la génération du fichier tous les <chiffre>%. Par défaut 5
            generation_progress="$2"
            shift;;
        "--progrès-update")
#<chiffre>|affiche de la progression de la mise à jour de la base de données tous les <chiffre>%. Par défaut 1
            update_progress="$2"
            shift;;
        "--help")
#|affiche cette aide et quitte
            echo "$0 [options]"
            echo "génère un classeur ODS pour comparer les scrutins publics de la 15ème mandature à l'Assemblée Nationale"
            echo
            sed -rn '/^ *"--.+"\)/N; s/^ *"(--.+)"\)\n#(.+)$/\1|\2/p' "$0" \
                | awk -F'|' -v marge='  ' -v prog="$0" '{
                    printf("%s %s\n" marge "%s\n\n", $1, $2, gensub("\\. ", "\\\n" marge, "g", gensub("\\{_\\}", prog, "g", $3)))
                }'
            exit;;
    esac
    shift
done

test "$options_error" = $true_flag && exit 1

test -z "$database" && database="${0}.db"

declare -A groupes
if test -n "$config_file"; then
    source "$config_file"
else
    config_file="${0}.conf"
    if test -r "$config_file"; then
        source "$config_file"
    fi
fi

IFS=',' groupe=(${groupe[0]:-LREM} ${groupe_ref:-GDR})

in_ram_database=$(mktemp --dry-run /dev/shm/XXXXXXXXXXXX)
if test -r "$database"; then
    cp "$database" "$in_ram_database"
else
    create_database
fi

for (( g = 0; g < ${#groupe[@]}; g++ )); do
    groupe_id[$g]=$(sqlite_request "select id from groupes where nom_court is '${groupe[$g]}'")
    if test -z "${groupe_id[$g]}"; then
        echo "groupe ${groupe[$g]} inconnu" >&2
        exit 1
    fi
done

if test "$periode" = $true_flag; then
    first=$(sqlite_request "select num from scrutins where date like '% du ${periode_value%:*}' order by num asc" | head -1)
    last=$(sqlite_request "select num from scrutins where date like '% du ${periode_value#*:}' order by num asc" | tail -1)
    test -z "$first" && echo "date de début inconnue: ${periode_value#*:}" >&2 && rm -f $in_ram_database && exit 1
    test -z "$last" && echo "date de fin inconnue: ${periode_value%:*}" >&2 && rm -f $in_ram_database && exit 1
elif test "$dossier" != $true_flag; then
    test -z "$last" && last=$(wget -qO- 'http://www2.assemblee-nationale.fr/scrutins/liste/(legislature)/15/(type)/TOUS/(idDossier)/TOUS' \
            | sed -rn 's,^.*<td class="denom">(.+)</td>.*$,\1,p' \
            | head -1)

    test -z "$first" && first=1
fi

if test "$liste_dossiers" = $true_flag; then
    sqlite_request "select printf('%s - %s', id, url) from url" | sed 's,https*://.*/dossiers/,,; s/_/ /g; s/.asp$//'
    exit
fi

if test "$db_update_only" = $true_flag; then
    unset first last
    last=$(wget -qO- 'http://www2.assemblee-nationale.fr/scrutins/liste/(legislature)/15/(type)/TOUS/(idDossier)/TOUS' \
            | sed -rn 's,^.*<td class="denom">(.+)</td>.*$,\1,p' \
            | head -1)
    update_database
    exit
fi

if test "$liste_deputes" = $true_flag; then
    if test -n "$liste_deputes_value"; then
        sqlite_request "select printf('%s - %s', députés.nom, groupes.nom_court) from députés inner join groupes on groupes.id = députés.groupe where groupes.nom_court is '$liste_deputes_value'"
    else
        sqlite_request "select printf('%s - %s', députés.nom, groupes.nom_court) from députés inner join groupes on groupes.id = députés.groupe order by groupes.nom_court asc"
    fi
    exit
fi

if test "$depute" = $true_flag; then
    if test -n "$nom"; then
        match=$(sqlite_request "select count(députés.id) from députés inner join groupes on groupes.id = députés.groupe where députés.nom like '%$nom%' and groupes.nom_court is '$groupe' collate nocase")
        if test $match -ne 1; then
            if test $match -eq 0; then
                echo "pas de député correspondant dans le groupe $groupe"
            else 
                echo "plusieurs députés correspondent:"
                sqlite_request "select députés.nom from députés inner join groupes on groupes.id = députés.groupe where députés.nom like '%$nom%' and groupes.nom_court is '$groupe' collate nocase"
            fi
            exit 1
        else
            nom=$(sqlite_request "select députés.id,députés.nom from députés inner join groupes on groupes.id = députés.groupe where députés.nom like '%$nom%' and groupes.nom_court is '$groupe' collate nocase")
            groupe[0]="${nom#*|} (${groupe[0]})"
        fi
    fi
fi

if test "$dossier" = $true_flag; then
    if test -z "$dossier_value"; then
        IFS=$'\n'
        select dossier in $(sqlite_request "select url from url" | sed 's,^.*/dossiers/,,; s/_/ /g; s/.asp$//'); do
            if test -n "$dossier"; then
                seq="sqlite_request \"select num from scrutins inner join url on url.id = scrutins.url where url.url like '%/dossiers/${dossier// /_}%' order by num asc\""
                qty=$(sqlite_request "select count(num) from scrutins inner join url on url.id = scrutins.url where url.url like '%/dossiers/${dossier// /_}%' order by num asc")
                break
            fi
        done
        IFS=$IFS_
    else
        seq="sqlite_request \"select num from scrutins inner join url on url.id = scrutins.url where url.id is $dossier_value order by num asc\""
        qty=$(sqlite_request "select count(num) from scrutins inner join url on url.id = scrutins.url where url.id is $dossier_value order by num asc")
        dossier=$(sqlite_request "select url from url where id is $dossier_value" | sed 's,^.*/dossiers/,,; s/_/ /g; s/.asp$//')
    fi
fi

update_database
write_comparaison