#!/bin/bash
set -e
. /etc/url-shortener/url-shortener.conf.sh
action=$1
shift
base=${URL_SHORTENER_CACHE_BASE}/$1
shift
[[ ! -f $base/.cachefile ]] && echo Wrong dir $base && exit 1
cd $base
if [[ "$action" = "count-files" ]]; then
    ls logs | wc -l
elif [[ "$action" = "get-visits" ]]; then
    wc -l logs/$1 | sed 's/ .*$//'
elif [[ "$action" = "list-visits" ]]; then
    cd logs
    find . -type f -size +0c -exec wc -l --total=never {} + | sort -r
elif [[ "$action" = "sort-cache" ]]; then
    sort -r .cachefile > .cachefile.tmp
    mv .cachefile.tmp .cachefile
    chown www-data:www-data .cachefile
    chmod 666 .cachefile
elif [[ "$action" = "update-cache" ]]; then
    chown root:root .cachefile
    chmod 600 .cachefile
    tar czf .cachefile.tar.gz .cachefile
    find logs -type f -size +0c -exec wc -l --total=never {} + | sed '/^ *0/d;s!^ *\([0-9]*\) \./\(.*\)!sed "s/^[0-9]* \2 /\1 \2 /q" .cachefile!' | bash
    bash $0 sort-cache
elif [[ "$action" = "update-cron" ]]; then
    cd logs
    wc -l ${@} | sed 's/^[^0-9]*\([0-9]*\)[\t ]*\([^\t ]*\).*$/sed -i '"'"'s!^[0-9]* \2 !\1 \2 !'"'"' ../.cachefile;' | bash
    cd $base/update.d
    rm -f ${@}
elif [[ "$action" = 'nginx-cron' ]]; then
  if [[ -f /var/cache/url-shortener/.restart_nginx ]]; then
    nginx -t && systemctl reload nginx && rm -f /var/cache/url-shortener/.restart_nginx
  fi
else
    echo "$0 <hostname> [<get-visits> HASH] [<list-visits>] [<update-cache>] [<count-files>] [<update-single> HASH]"
fi

