scripts / analyse-votes-AN /
ef301ed 2 years ago
3 contributor
780 lines | 37.284kb
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#!/bin/bash

set -e

# on n'autorise qu'une seule exécution à la fois
process_token=$(mktemp --dry-run /dev/shm/XXXXXXXXXXXXXXXX)
token_file="$process_token.${0##*/}"

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

IFS_=$IFS

function sqlite_request () {
    sqlite3 ${2:+-cmd} ${2:+".mode $2"} "$in_ram_database" <<< "$1"
}

function create_database () {
    sqlite_request "create table if not exists dossiers (id integer primary key, titre text, url text)"
    sqlite_request "create table if not exists votes    (id integer primary key, nom text)"
    sqlite_request "create table if not exists députés  (id integer primary key, nom text, groupe integer, date text)"
    sqlite_request "create table if not exists groupes  (id integer primary key, nom text unique, nom_court text)"
    sqlite_request "create table if not exists scrutins (num integer primary key, séance text, date text not null, intitulé text non null, adoption boolean, dossier integer, mise_au_point text)"
    sqlite_request "create table if not exists dépouillements (scrutin integer not null, député integer not null, vote integer not null)"
    sqlite_request "create unique index if not exists 'index_députés'        on députés (nom, groupe)"
    sqlite_request "create unique index if not exists 'index_dossiers'       on dossiers (titre, url)"
    sqlite_request "create unique index if not exists 'index_dépouillements' on dépouillements (député, scrutin)"

    for v in Pour Contre Abstention Non-votant; do
        sqlite_request "insert or ignore into votes (nom) values ('$v')"
    done
}

function update_database () {
    test "$no_db_update" = $true_flag && return
    tempfile="/dev/shm/scrutin.$$"
    progress=0
    for r in "${!acronymes[@]}"; do
        sqlite_request "update groupes set nom_court = \"${acronymes[$r]}\" where nom = \"$r\""
    done
    sqlite_request "create table if not exists dossier_par_scrutin (scrutin integer, url text)"
    echo "récupération des dossiers"
    wget -qO- "https://www.assemblee-nationale.fr/dyn/$mandature/dossiers" \
    | sed -rn 's/<p class="m-0"><a title="Accéder au dossier législatif" href="([^"]+)">([^<]+)<.+$/\1 \2/p' \
    | sed -r "s/^[[:space:]]*//; s/&#039;/'/g" \
    | awk -v dq='"' '{
        printf("insert or ignore into dossiers (titre, url) values (%s, %s);\n", dq gensub($1 " ", "", "1", $0) dq, dq "https://www.assemblee-nationale.fr" $1 dq)
    }' > $tempfile
    sqlite3 "$in_ram_database" < $tempfile
    first_=$first
    first=$(sqlite_request "select max(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

        test $((last % 100)) -ne 0 && last_offset=0
        IFS=$' \t\n'
        for offset in $(seq $((last - 100)) -100 ${first:-0} ) $last_offset; do
            wget -qO- "http://www2.assemblee-nationale.fr/scrutins/liste/(offset)/$offset/(legislature)/$mandature/(type)/TOUS/(idDossier)/TOUS" \
                | awk -v dq='"' '
                    BEGIN {
                    }
                    /<td class="denom">/ {
                        scrutin = gensub(/^.+denom.>([[:digit:]]+)\\*?<.td./,"\\1","1",$0)
                    }
                    /<td class="desc">/ {
                        if (match($0, ">dossier<") > 0)
                            dossier[scrutin] = gensub(/^.+.<a href="([^"]+)">dossier<.a>.*$/,"\\1","1",$0)
                    }
                    END {
                        for (i in dossier) {
                            printf("insert into dossier_par_scrutin (scrutin, url) values (%i, %s);\n", i, dq dossier[i] dq)
                        }
                    }' > $tempfile
            sqlite3 "$in_ram_database" < $tempfile
        done


#        IFS=$'\n'
        begin=$(date +%s)
        for scrutin in $(seq $((${first:-0}+1)) $last); do
            w3m -cols 512 -dump "http://www2.assemblee-nationale.fr/scrutins/detail/(legislature)/$mandature/(num)/$scrutin" \
            | sed -n '/^Analyse du scrutin n° /,/^Votes des groupes/{/^Navigation/,/^  • Non inscrits/d;/^[[:space:]]*$/d;p}' \
            | awk -v sq="'" -v dq='"' '
                BEGIN { adoption = -1; map = 0 }
                /^Analyse du scrutin/ { scrutin = $NF }
                /séance du [0-3][0-9]\/[01][0-9]\/(19|20)[0-9]+/ { date = $NF; seance = $1 }
                /^Scrutin public sur /            { titre = gensub("^Scrutin public sur l[ae" sq "]s? ?", "", "1") }
                /^L.Assemblée .+ adopté/          { adoption = NF == 3 }
                /^Nombre de votants :/            { votants      = $NF }
                /^Nombre de suffrages exprimés :/ { exprimes     = $NF }
                /^Majorité absolue :/             { majo_absolue = $NF }
                /^Pour l.adoption :/              { pour         = $NF }
                /^Contre :/                       { contre       = $NF }
                /^Groupe /                        { groupe = gensub("^Groupe (.+) \\([1-9].+$", "\\1", "1")
                                                    groupe = gensub("^(la|les|le|l" sq "|du|des|de|de la|d" sq ") ", "", "1", groupe)
                                                  }
                /^Non inscrits/                   { groupe = "Non inscrits" }
                /^(Pour|Abstention|Contre):/      { position = gensub(":", "", "1", $1) }
                /^Non-votants?:/                  {
                                                    position = gensub("s?:", "", "1", $1)
                                                    nvl = ""
                                                    while ($1 != "Groupe" || $0 != "Contenus annexes") {
                                                        getline
                                                        if ($1 == "Groupe" || $0 == "Contenus annexes")
                                                            break
                                                        nvl = nvl $0
                                                    }
                                                    f = split(nvl, nv, "(, | et )")
                                                    for (i=1; i<=f; i++) {
                                                        votes[groupe][position][gensub("(^ +|M\\. |Mme |Mlle | \\(.+)", "", "g", nv[i])]++
                                                    }
                                                    groupe = gensub("^Groupe (.+) \\([1-9].+$", "\\1", "1")
                }
                /^  • /                           { votes[groupe][position][gensub("^[^A-Z]*", "", "1")]++ }
                /^Mises au point/,/^Votes des groupes/ { if ($1 != "(Sous") mises_au_point[map++] = $0 }
                END {
                    if (adoption < 0)
                        adoption = pour >= majo_absolue

                    for (i=1; i<map-1; i++)
                        mise_au_point = sprintf("%s[%s]", mise_au_point, mises_au_point[i])

                    printf("insert into scrutins (num, séance, date, intitulé, adoption, mise_au_point) values (%i, %s, %s, %s, %i, %s);\n",
                            scrutin,
                            sq seance sq,
                            sq date sq,
                            dq gensub(dq, dq dq, "g", titre) dq,
                            adoption,
                            dq gensub(dq, dq dq, "g", mise_au_point) dq,
                            scrutin)
                    printf("update scrutins set dossier = ( select id from dossiers inner join dossier_par_scrutin where dossiers.url = dossier_par_scrutin.url and dossier_par_scrutin.scrutin = %i) where num = %i;\n",
                            scrutin,
                            scrutin)
                    for (groupe in votes) {
                        printf("insert or ignore into groupes (nom) values (%s);\n", dq groupe dq)
                        for (position in votes[groupe]) {
                            for (nom in votes[groupe][position]) {
                                if (nom !~ " \\(.+\\) *$")
                                    printf("insert or ignore into députés (nom, groupe, date) select %s, id, %s from groupes where nom = %s;\n",
                                            dq nom dq,
                                            dq date dq,
                                            dq groupe dq)
                                printf("insert or ignore into dépouillements (scrutin, député, vote) select %i, députés.id, votes.id from députés inner join votes where députés.nom = %s and votes.nom = %s;\n",
                                       scrutin,
                                       dq nom dq,
                                       dq position dq)
                            }
                        }
                    }
                }
            ' > $tempfile
            sqlite3 "$in_ram_database" < $tempfile


            if test $(( ($scrutin - ${first:-0}) * 100 / ( $last - ${first:-0} ) )) -ne ${progress:-0}; then
                progress=$(( ($scrutin - ${first:-0}) * 100 / ( $last - ${first:-0} ) ))
                if test $(($progress % ${update_progress:-1})) -eq 0; then
                    now=$(date +%s)
                    delta=$(( $now - $begin ))
#                   scrutin = {first:-0}+1 à la première itération
                    printf "\r%d%%, ETA %s" $progress $(date +%H:%M:%S -d "$(($delta * ($last - $scrutin) / ($scrutin - ${first:-0}) )) seconds")
                fi
            fi
        done
        sqlite_request 'drop table dossier_par_scrutin'

        echo -e "\r\033[KTerminé: $(($scrutin - ${first:-0} - 1)) scrutins ajoutés"
        rm -f "$tempfile"
    fi
    first=$first_
}

function write_comparaison () {
    result="scrutins ($(sum <<< "${groupe[@]}" | cut -b1-5))${dossier:+ - ${dossier}}"
    if test "$envoi_par_mail" = $true_flag; then
        result="scrutins"
    fi
    content="/dev/shm/$result/content.xml"
    id_cols=(Scrutin Date Séance Titre Adoption Dossier)
    eval $(sqlite_request 'select printf("typevotes[%i]=%s;", id, nom) from votes')
    nb_cols=$(( ${#id_cols[@]} + ${#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')
    colors=($(awk -v n=${#groupe[@]} -v from=${from_color:-2A0636} -v to=${to_color:-D09B8A} '
        function rgbL (p) {
            r = rgb_from[1] + p * (rgb_to[1] - rgb_from[1])
            g = rgb_from[2] + p * (rgb_to[2] - rgb_from[2])
            b = rgb_from[3] + p * (rgb_to[3] - rgb_from[3])
            L = r * 0.299 + g * 0.587 + b * 0.114
            printf("%02x%02x%02x:%s\n", int(r), int(g), int(b), L > 185 ? "000000" : "ffffff")
        }
        BEGIN {
            for (i = split(gensub("(..)(..)(..)", "\\1,\\2,\\3", "1", from), rgb_from, ","); i > 0; i--)
                rgb_from[i] = strtonum(sprintf("%d", strtonum("0x" rgb_from[i])))
            for (i = split(gensub("(..)(..)(..)", "\\1,\\2,\\3", "1", to), rgb_to, ","); i > 0; i--)
                rgb_to[i] = strtonum(sprintf("%d", strtonum("0x" rgb_to[i])))

            print "pour_bash_array_qui_commence_a_index_0"
            rgbL(0)
            for (i = 1; i < n-1; i++) {
                rgbL(i/n)
            }
            if (n > 1) rgbL(1)
        }
    '))
    function write_cell () {
        case $1 in
            url)
                cell='<table:table-cell office:value-type="string" calcext:value-type="string">'
                cell+="<text:p><text:a xlink:href=$2 xlink:type=\"simple\">$3</text:a></text:p>"
                ;;
            texte)
                cell='<table:table-cell office:value-type="string" calcext:value-type="string">'
                cell+="<text:p>$2</text:p>"
                ;;
            nombre)
                cell="<table:table-cell office:value-type=\"float\" office:value=\"$2\" calcext:value-type=\"float\">"
                cell+="<text:p>$2</text:p>"
                ;;
            *)
                return 1;;
        esac
        cell+='</table:table-cell>'
        echo $cell >> "$content"
    }

    if test -z "$envoi_par_mail"; then
        echo "génération du fichier $result"
    fi

    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>
EOcontent

    for i in $(seq ${#groupe[@]}); do
        cat >> "$content" << EOcontent
        <style:style style:name="ce$i" style:family="table-cell" style:parent-style-name="Default">
        <style:table-cell-properties fo:wrap-option="wrap" style:vertical-align="middle" fo:background-color="#${colors[$i]%:*}"/>
        <style:text-properties fo:hyphenate="false" fo:color="#${colors[$i]}"/>
        </style:style>
EOcontent
    done

    cat >> "$content" << EOcontent
    </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="${#id_cols[@]}" table:default-cell-style-name="Default"/>
EOcontent

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

    IFS=$IFS_
    for colonne in ${id_cols[@]}; do
        write_cell texte $colonne
    done

    for typevote in ${typevotes[@]}; do
        for g in "${groupe[@]}"; do
            write_cell texte "$typevote - $g"
        done
    done

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

    progress=0
    begin=$(date +%s)
    line=1
    test -z "$seq" && qty=$(( $last - $first ))
    IFS=$'\n'
    scrutin_base_url="https://www2.assemblee-nationale.fr/scrutins/detail/(legislature)/$mandature/(num)/"
    for scrutin in $(eval ${seq:-seq $first $last}); do

        data=$(sqlite_request "select date,séance,intitulé,adoption,dossiers.url,dossiers.titre from scrutins left join dossiers on scrutins.dossier = dossiers.id where num is $scrutin" json)
        date=$(jq -r '.[].date' <<< $data)
        seance=$(jq -r '.[]."séance"' <<< $data)
        title=$(jq -r '.[]."intitulé" | @html' <<< $data)
        adoption=$(jq '.[].adoption' <<< $data)
        dossier_url=$(jq '.[].url' <<< $data)
        dossier_texte=$(jq -r '.[].titre | @html' <<< $data)
        test $adoption -eq 1 && adoption='oui' || adoption='non'

        echo '<table:table-row table:style-name="ro1">' >> "$content"

        write_cell url   "\"$scrutin_base_url$scrutin\"" $scrutin
        write_cell texte "$date"
        write_cell texte "$seance"
        write_cell texte "$title"
        write_cell texte "$adoption"
        write_cell url   "${dossier_url/#null/\"\"}" "${dossier_texte/#null}"

        unset votes
        for typevote in $(seq ${#typevotes[@]}); do
            for (( g = 0; g < ${#groupe[@]}; g++ )); do
                votes[${#votes[@]}]=$(sqlite_request "select
                                            count(député)
                                         from
                                            dépouillements
                                         inner join
                                            députés, groupes
                                         on
                                            députés.groupe = groupes.id and dépouillements.député = députés.id
                                         where
                                            scrutin is $scrutin
                                         and
                                            vote is $typevote
                                         and
                                            ${id_groupe[$g]%:*}.nom = '${groupe[$g]//\'/\'\'}'")
            done
        done
        for ((j = 0; j < ${#groupe[@]}; j++)); do
            presence=1 # `let presence+=0` sort en erreur si variable est unset ou égale à 0
            for ((i = $j; i < ${#votes[@]}; i += ${#groupe[@]})); do
                let presence+=${votes[$i]}
            done
            if test $presence -eq 1; then
                for ((i = $j; i < ${#votes[@]}; i += ${#groupe[@]})); do
                    votes[$i]=-1
                done
            fi
        done
        for ((i = 0; i < ${#votes[@]}; i ++)); do
            write_cell nombre ${votes[$i]}
        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 ))
                printf "\r%d%%, ETA %s" $progress $(date +%H:%M:%S -d "$(( $delta * (${qty:-$last} - $line) / $line )) seconds")
            fi
        fi

        let line++

    done

    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" "${destination_path:+$destination_path/}$result.ods"

    if test -z "$envoi_par_mail"; then
        echo -e "\r\033[KTerminé : ${destination_path:+$destination_path/}$result.ods"
    fi
}

function save_database () {
    rm -f  "$token_file"
    test -n "$result" -a -d "/dev/shm/$result" && rm -fr "/dev/shm/$result"
    test -n "$database" -a -n "$in_ram_database" || return
    if test "$envoi_par_mail" = $true_flag; then
        if test -n "$mailconfig_file" && test -r "$mailconfig_file"; then
            source "$mailconfig_file"
        elif test -r "/usr/local/etc/${0##*/}.mail.conf"; then
            source "/usr/local/etc/${0##*/}.mail.conf"
        fi
        stat -Lc "(date de mise à jour de la base: %x)" $database
        cat > $process_token.headers << EOC
From: ${from_mail:?}
To: $destinataire
Subject: les scrutins demandés
EOC
        curl_opt=(
                --url smtp://${smtp_address:?}:${smtp_port:?}
                --mail-rcpt $destinataire
                -H @$process_token.headers
                -F "=(;type=multipart/alternative"
                -F "=<$process_token.txt;encoder=quoted-printable"
                -F "=<$process_token.html;encoder=quoted-printable"
                -F "=)"
        )
        if test -r "${destination_path:+$destination_path/}$result.ods"; then
            curl_opt[${#curl_opt[@]}]="-F"
            curl_opt[${#curl_opt[@]}]="=@${destination_path:+$destination_path/}$result.ods;encoder=base64"
        fi
        exec 1>&-
        aha -f $process_token.mail -t "envoi automatisé" > $process_token.html
        w3m -dump $process_token.html > $process_token.txt
        curl ${curl_opt[@]}
        rm -f "${destination_path:+$destination_path/}$result.ods" $process_token*
    elif test -r "$database" && sqldiff=$(sqldiff $in_ram_database $database) && test -z "$sqldiff"; then
        echo "pas de modification"
    elif test -w "$database"; then
        rm -f "$database"
        sqlite_request '.dump' | sqlite3 "$database"
        echo "base de données $database mise à jour"
    elif test ! -e "$database" -a -w ${database%/*}; then
        sqlite_request '.dump' | sqlite3 "$database"
        echo "base de données $database créée"
    else
        echo "je ne peux rien faire avec $database !"
    fi
    rm -f "$in_ram_database" "$tempfile"
}

function dernier_scrutin_public () {
    wget -qO- "http://www2.assemblee-nationale.fr/scrutins/liste/(legislature)/$mandature/(type)/TOUS/(idDossier)/TOUS" \
            | sed -rn 's/^.*<td class="denom">([0-9]+)[^0-9].*$/\1/p' \
            | head -1
}

trap save_database EXIT

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

declare -A acronymes
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

true_flag=$(mktemp --dry-run XXXXX)
echo "$0 $@" > $token_file

while [[ $# -gt 0 ]]; do
    case "$1" in
        "--no-db-update")
#|ne met pas à jour la base de données
            if test ${db_update_only:-OK} = $true_flag; then
                echo "option incompatible avec --db-update-only"
                exit 1
            fi
            no_db_update=$true_flag;;
        "--db-update-only")
#|ne génère pas de fichier de résultat
            if test ${no_db_update:-OK} = $true_flag; then
                echo "option incompatible avec --no-db-update"
                exit 1
            fi
            db_update_only=$true_flag;;
        "--cible"|"-c")
#<nom court du groupe>|ajoute les scrutins de ce groupe, de ce ou cette députée, les colonnes seront dans l'ordre
            _groupe[${#_groupe[@]}]="${2//\'/\'\'}"
            shift;;
        "--couleurs")
#<nombre hexadécimal>:<nombre hexadécimal>|colore les colonnes en dégradé entre les deux couleurs comprises
            if grep -iq '[^0-9A-F:]' <<< ${2:-ERROR}; then
                echo "$1 ${2:-ERROR}: format attendu <nombre>:<nombre>"
                exit 1
            elif egrep -iq '[0-9A-F]{6}:[0-9A-F]{6}' <<< ${2:-ERROR}; then
                from_color=${2%:*}
                to_color=${2#*:}
            else
                echo erreur $2: couleur RGB au format hexadécimal demandé
            fi
            shift;;
        "--mandature")
           mandature="$2"
           ;;
        "--scrutin")
#<nombre>[:<nombre>]|commence la génération du résultat pour le scrutin <nombre>, ou entre les deux nombres donnés
            if grep -q '[^0-9:]' <<< ${2:-ERROR}; then
                echo "$1 ${2:-ERROR}: format attendu <nombre>[:<nombre>]"
                exit 1
            elif egrep -q '[1-9][0-9]*(:[1-9][0-9]*)?' <<< ${2:-ERROR}; then
                first=${2%:*}
                last=${2#*:}
                if test $first -gt $last; then
                    last+=:$first
                    first=${last%:*}
                    last=${last#*:}
                fi
            else
                echo "$1 ${2:-ERROR}: <nombre> ne doit pas commencer par 0"
                exit 1
            fi
            shift;;
        "--premier-scrutin")
#<numéro>|commence la génération du résultat à partir du scrutin <numéro>
            first="$2"
            shift;;
        "--dernier-scrutin")
#<numéro>|termine la génération du résultat au scrutin <numéro>
            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
            periode_value="$2"
            shift;;
        "--liste-députés-du-groupe")
#<groupe>|liste les député·e·s du groupe <groupe>
            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;;
        "--mailconf")
#<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
            }
            mailconfig_file="$2"
            shift;;
        "--dest")
#<répertoire>|génère le fichier dans le répertoire spécifié. Par défaut $PWD
            if test -n "$2" && test -d "$2" -a -r "$2"; then
                destination_path="$2"
                shift
            else
                echo "$2 n'est pas un répertoire ou n'est pas autorisé en écriture" >&2
                exit 1
            fi;;
        "--database")
#<fichier>|indique le chemin vers la base de données SQLite3 contenant les informations. Par défaut "{_}.db"
            if test -r "$2" && file -Lb "$2" | grep -q '^SQLite 3.x database'; then
                :
            else
                echo "erreur sur option database: fichier '$2' introuvable ou pas une base SQLite 3" >&2
                options_error=$true_flag
            fi
            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;;
        "--mail")
            envoi_par_mail=$true_flag
            destinataire="$2"
            no_db_update=$true_flag
            destination_path=/dev/shm
            generation_progress=1000
            exec > $process_token.mail 2>&1
            shift;;
        "--help")
#|affiche cette aide et quitte
            echo "$0 [options]"
            echo "génère un classeur ODS pour comparer les scrutins publics de la 16è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

while true; do
    if ls -1rt /dev/shm/*."${0##*/}" | head -1 | grep -q "^$token_file$"; then
        # c'est notre tour
        break
    else
        sleep 5
    fi
done

in_ram_database=$process_token.db
if test -r "$database"; then
    cp "$database" "$in_ram_database"
else
    create_database
fi

if test "$periode" = $true_flag; then
    function get_date () {
        sqlite_request "select distinct(date) from scrutins order by num asc" | awk -v d="$1" -v comp=$2 '
            function norm_date (date) {
                split(date, a, "/")
                return sprintf("%s%s%s",
                    length(a[3]) == 4 ? a[3] : length(a[3]) == 2 ? "20" a[3] : strftime("%Y", systime()),
                    length(a[2]) == 2 ? a[2] : "0" a[2],
                    length(a[1]) == 2 ? a[1] : "0" a[1])
            }
            function output (date) {
                print date
                found = 1
                exit
            }
            BEGIN { d = norm_date(d) }
            {
                s = norm_date($1)
                if (NR == 1 && s > d && comp == "first") output($1)
                if (s >= d && comp == "first") output($1)
                if (s == d && comp == "last")  output($1)
                if (s >  d && comp == "last")  output(previous)
                previous = $1
            }
            END {
                if (!found) print previous
            }'
    }
    first=$(sqlite_request "select min(num) from scrutins where date = '$(get_date ${periode_value%:*} first)'")
    last=$(sqlite_request "select max(num) from scrutins where date = '$(get_date ${periode_value#*:} last)'")
    if test "$envoi_par_mail" = $true_flag; then
        texte_periode="du $(get_date ${periode_value%:*} first) (scrutin n°$first) au $(get_date ${periode_value#*:} last) (scrutin n°$last)"
    fi
elif test "$dossier" != $true_flag; then
    test -z "$last" && last=$(dernier_scrutin_public)
    test -z "$first" && first=1
fi

if test "$liste_dossiers" = $true_flag; then
    if test "$envoi_par_mail" = $true_flag; then
        echo "Voici la liste des dossiers actuellement à l'étude"
    fi
    sqlite_request "select printf('• %s (%s)', titre, url) from dossiers"
    exit
fi

if test "$db_update_only" = $true_flag; then
    unset first last
    last=$(dernier_scrutin_public)
    update_database
    exit
fi

if test "$liste_deputes" = $true_flag; then
    if test -n "$liste_deputes_value"; then
        if test "$envoi_par_mail" = $true_flag; then
            echo "Voici la liste des député·e·s du groupe dont le nom correspond au critère $liste_deputes_value"
        fi
        sqlite_request "select printf('%s - %s%s',
                                      députés.nom,
                                      groupes.nom,
                                      iif(groupes.nom_court is not null, ' [' || groupes.nom_court || ']', ''))
                        from députés
                        inner join groupes on groupes.id = députés.groupe
                        where
                            groupes.nom like '%$liste_deputes_value%'
                        or
                            groupes.nom_court = '$liste_deputes_value'"
    else
        if test "$envoi_par_mail" = $true_flag; then
            echo "Voici la liste des député·e·s"
        fi
        sqlite_request "select printf('%s - %s%s',
                                      députés.nom,
                                      groupes.nom,
                                      iif(groupes.nom_court is not null, ' [' || groupes.nom_court || ']', ''))
                        from députés
                        inner join groupes on groupes.id = députés.groupe
                        order by groupes.nom asc"
    fi
    exit
fi

for (( g = 0; g < ${#_groupe[@]}; g++ )); do
    # on vérifie si c'est un ou une député
    depute_count=$(sqlite_request "select count(distinct nom) from députés where nom like '%${_groupe[$g]}%'")
    groupe_count=$(sqlite_request "select count(distinct nom) from groupes where nom like \"%${_groupe[$g]}%\" or nom_court is '${_groupe[$g]}'")
    if test $depute_count -eq 1 -a $groupe_count -ne 1; then
        groupe[$g]=$(sqlite_request "select distinct nom from députés where nom like '%${_groupe[$g]}%'")
        id_groupe[$g]=députés:$(sqlite_request "select group_concat(id) from députés where nom is '${groupe[$g]//\'/\'\'}'")
    elif test $groupe_count -eq 1 -a $depute_count -ne 1; then
        groupe[$g]=$(sqlite_request "select distinct nom from groupes where nom like \"%${_groupe[$g]}%\" or nom_court is '${_groupe[$g]}'")
        id_groupe[$g]=groupes:$(sqlite_request "select id from groupes where nom is '${groupe[$g]//\'/\'\'}'")
    elif test $groupe_count -eq 1 -a $depute_count -eq 1; then
        echo "dénomination ambigüe pour « ${_groupe[$g]} »"
        sqlite_request "select printf('député·e: %s', distinct nom) from députés where nom like '%${_groupe[$g]}%'" | grep --color=always -i "${_groupe[$g]}"
        sqlite_request "select printf('groupe  : %s', distinct nom) from groupes where nom like \"%${_groupe[$g]}%\" or nom_court is '${_groupe[$g]}'" | grep --color=always -i "${_groupe[$g]}"
        echo
    elif test $depute_count -gt 1; then
        echo "plusieurs député·e·s trouvé·e·s correspondant à « ${_groupe[$g]} »"
        sqlite_request "select distinct nom from députés where nom like '%${_groupe[$g]}%'" | grep --color=always -i "${_groupe[$g]}"
        echo
    elif test $groupe_count -gt 1; then
        echo "plusieurs groupes trouvés correspondant à « ${_groupe[$g]} »"
        sqlite_request "select distinct nom from groupes where nom like \"%${_groupe[$g]}%\" or nom_court is '${_groupe[$g]}'" | grep --color=always -i "${_groupe[$g]}"
        echo
    else
        echo "aucun·e député·e ou groupe ne correspond au critère « ${_groupe[$g]} »"
        echo
    fi
done

if test -s $process_token.mail; then
    exit 1
fi

update_database
write_comparaison

if test "$envoi_par_mail" = $true_flag; then
    echo Vous pourrez trouver en pièce-jointe les résultats demandés avec ces critères:
    if test ${#groupe[@]} -gt 0; then
        echo "votes des groupes et député·e·s suivant·e·s:"
        printf " • %s\n" "${groupe[@]}"
    fi
    if test "$periode" = $true_flag; then
        echo sur la période allant $texte_periode
    fi
fi