#!/bin/bash
. /etc/url-shortener/conf.sh
action=$1
shift
hostname=$1
shift
base=${URL_SHORTENER_CACHE_BASE}/$hostname
HASH=$1

set -e

case $action in 
    count-files)
        cd $base
        ls logs | wc -l
        ;;
    get-visits)
        cd $base
        wc -l logs/$HASH | sed 's/ .*$//'
        ;;
    list-visits)
        cd $base/logs
        find . -type f -size +0c -exec wc -l --total=never {} + | sort -r
        ;;
    sort-cache)
        cd $base
        sort -r .cachefile > .cachefile.tmp
        mv .cachefile.tmp .cachefile
        chown www-data:www-data .cachefile
        chmod 666 .cachefile
        ;;
    update-cache)
        cd $base
        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
        ;;
    update-cron)
        cd $base/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 ${@}
        ;;
    nginx-cron)
        if [[ -f /var/cache/url-shortener/.restart_nginx ]]; then
            nginx -t > /dev/null 2>&1 && systemctl reload nginx > /dev/null 2>&1 && rm -f /var/cache/url-shortener/.restart_nginx
        fi
        ;;
    unlink-location)
        rm -v -f $base/locations.d/$HASH
        ;;
    link-location)
        [[ ! -e $base/locations.d/$HASH ]] && ln -v -s $base/nginx/$HASH $base/locations.d/
	;;
    create-host)
        mkdir -v -p $base/{nginx,logs,locations.d};
        chmod 777 $base/{nginx,logs,locations.d};
        cfgfile=$base/server.conf
	if [[ ! -f $cfgfile ]]; then
            sed "s/{DOMAINNAME}/$hostname/g;s/server_name  *default/server_name _/" \
		    /usr/share/url-shortener/url-shortener-server.conf.tmpl > $cfgfile
	fi
        touch $base/.cachefile
        if [[ ! $(whoami) = "www-data" ]]; then
            sudo chown -v -R www-data:www-data $base
        fi 
        ;;
    *)
        echo "$0 COMMAND"
        echo "Where COMMAND can be"
        echo "  * count-files <HOSTNAME>"
        echo "  * get-visits <HOSTNAME> <HASH>"
        echo "  * list-visits <HOSTNAME>"
        echo "  * sort-cache <HOSTNAME>"
        echo "  * update-cache <HOSTNAME>"
        echo "  * update-cron <HOSTNAME>"
        echo "  * nginx-cron"
        echo "  * create-host <HOSTNAME>"
        ;;
esac

