#! /bin/bash

# update-item-count updates counts of items listed in mal.rec
# on relevant pages.

# RT #1328973.

# Copyright (C) 2018, 2019 Free Software Foundation, Inc.

# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

# Written by Therese <thg@gnu.org> and Ineiev.

export LC_ALL=C
set -e

# Get the number of items, and approximate it to the nearest 50.
item_count=$(grep -Ec '^Id: 20[0-9]{7}$' mal.rec)
i=$((item_count/50))
i=$((i*50))
d=$((item_count%50))
if [ $d -ge 25 ]; then
  i=$((i+50))
fi

# Get the number of links, and approximate it to the lower 50.
link_count=$(sed "s/href[ \t]*=[ \t]*['\"]http/\n&/g;" mal.rec \
  | grep "^href[ \t]*=[ \t]*['\"]https\?" | awk '{
    s = $0; sub(/href[ \t]*=[ \t]*/, "", s)
    quote = substr(s, 1, 1)
    sub(/.https?:\/\//, "", s); idx = index(s, quote)
    if (idx)
      s = substr(s, 1, idx - 1)
    sub(/\/*$/, "", s)
    print s
  }' | sort -u | wc -l)
# The page says, "more than $l references", so
# when e.g. link_count is exactly 350, l should be 300.
l=$(((link_count - 1)/10))
l=$((l*10))

# Check if the numbers to put in proprietary.html and
# free-software-even-more-important.html changed, update the files
# as needed.
month=$(date +'%B %Y')
if ! grep -q "list around $i\>" ../proprietary.html \
   || ! grep -q "more than $l references" ../proprietary.html; then
  sed -i "
  s|As of .*, the pages in this directory list .*$|As of $month, the pages in this directory list around $i|
  s|functionalities (with .* references|functionalities (with more than $l references|
  " ../proprietary.html
  if ! grep -q "list around $i\>" ../proprietary.html \
     || ! grep -q "more than $l references" ../proprietary.html; then
     echo 1>&2 "Malware count update failed in proprietary.html."
     exit 1
  fi
  echo "Malware count was updated in proprietary.html."
fi
f=../../philosophy/free-software-even-more-important.html
if ! grep -q "lists around $i different" $f; then
  sed -i "
  s|That directory lists around .* different|That directory lists around $i different|
  s|malicious functionalities (as of .*),|malicious functionalities (as of $month),|
  " $f
  if ! grep -q "lists around $i different" $f \
     || ! grep -q "malicious functionalities (as of $month)," $f; then
     echo 1>&2 "Malware count update failed in ${f#../../}."
     exit 1
  fi
  echo "Malware count was updated in ${f#../../}."
fi
