#!/bin/bash

function printHeader {
  echo "# $1"
  echo '| ID | Type | Blog | Solutions | Timus |'
  echo '|:----:|:----:|:-------:|:----:|:----:|'
}

function trim {
  local trimmed="$1"
  # Strip leading space.
  trimmed="${trimmed## }"
  # Strip trailing space.
  trimmed="${trimmed%% }"
  # Strip tailling spaces.
  trimmed=${trimmed%%[[:space:]]}
  echo "$trimmed"
}

count_algorithms=0

function process {
  local id=`echo $1 | awk '{print substr($1, 0, length($1)-1);}'`
  local type=Algorithms
  count_algorithms=$((count_algorithms+1))
  local question=$(echo $1 | awk '{for (i=2; i<=NF; i++) printf ("%s ",$i);}' )
  question=$(trim "$question")
  local sc=$(ls -1q "$1"/ | wc -l)
  local urlencoded=$(echo "$1" | sed -e 's/ /%20/g')
  local solutions="[$sc](https://github.com/DoctorLai/ACM/tree/master/timus/$urlencoded)"
  local ext=$(ls -1 "$1" | sed 's/.*\.//' | sort -u | tr "\n" " ")
  local first=$(ls -1q "$1"/ | head -1)
  local timusurl=$(cat "$1/$first" | grep timus | awk '{print $2}')
  local blog=$(cat "$1/$first" | grep helloacm | awk '{print $2}')
  blog=$(trim $blog)
  timusurl=$(trim $timusurl)
  if [ ! -z "$blog" ]; then
    question="[$question]($blog)"
  fi   
  local timus=" N/A "
  if [ ! -z "$timusurl" ]; then
    timus="[timus]($timusurl)"
  fi
  echo "| $id | $type | $question | $solutions<br/>$ext | $timus |"
}                                               

# Process for Algorithms
printHeader "Algorithms (http://acm.timus.ru)"
for i in *; do
  if [ -d "$i" ]; then
    process "$i"
  fi    
done

echo
echo Total \*$count_algorithms\* Algorithms.
echo 
echo '*Index generated by [script](https://github.com/DoctorLai/ACM/blob/master/timus/GenerateIndex.sh)* at '$(date)
