#!/bin/bash
set -e

base=/var/cache/url-shortener

[[ -f /etc/url-shortener/conf.sh ]] && . /etc/url-shortener/conf.sh
[[ -z "$URL_SHORTENER_CACHE_BASE" ]] && base=$URL_SHORTENER_CACHE_BASE

mkdir -p /var/log/url-shortener
chmod 777 /var/log/url-shortener

# look for installed sites
if [[ -z "$(find $base -maxdepth 2 -type f -name 'server.conf')" ]]; then
    read -p "$(echo -e "\e[0;31mInstall a Default Site? [Y,n]: \e[0m")" defgen
    if [[ ! "$defgen" =~ n|N ]]; then
        /usr/bin/url-shortener create-host default
    fi
fi

installdir=/usr/share/url-shortener
py=./venv/bin/python3
pip="$py -mpip"

cd $installdir
if [[ ! -f $py ]]; then
    rm -rf venv
    python3 -mvenv venv
    cd -
fi
if ! $pip freeze | grep -qi flask; then
    $pip install -r requirements.txt
fi
cd -
systemctl daemon-reload
systemctl enable url-shortener-gui.service
systemctl restart url-shortener-gui.service || echo "Could not restart"
nginx -t && systemctl restart nginx
exit 0

