#!/bin/sh

set -e

SUDO="sudo"
SUDO_U="sudo -u"

if [ "$(whoami)" = "root" ]; then
    SUDO=""
    SUDO_U="runuser -u"
fi

APT_OPTIONS=""
if [ "$NON_INTERACTIVE" = "1" ]; then
    APT_OPTIONS="-y"
fi

usage() {
    cat <<EOF
Usage: bin/quick-setup.sh [action]

Run with no arguments to perform all actions.

Actions:
  create_directories    Create directories required by debusine.
  install_packages      Ensure that required packages are installed.
  setup_settings        Install a configuration file.
  setup_database        Configure a PostgreSQL database.
EOF
}

verify_minimum_package_version() {
    package_name="$1"
    minimum_version="$2"

    installed_version=$(dpkg-query -W -f'${Version}' "$package_name")

    if dpkg --compare-versions "$installed_version" lt "$minimum_version"; then
        echo "ERROR: you need $package_name >= $minimum_version" >&2
        exit 1
    else
        echo "INFO: you have $package_name $installed_version >= $minimum_version"
    fi
}

sanity_checks() {
    if [ -e debusine/project/settings/local.py ]; then
        echo "ERROR: You already have a configuration file (debusine/project/settings/local.py)" >&2
        exit 1
    fi

    if [ -e data/debusine.sqlite ]; then
        echo "ERROR: You already have a database file (data/debusine.sqlite)" >&2
        exit 1
    fi
}

install_packages() {
    echo ">>> Ensuring we have the required packages"
    packages="$(sed -Ene 's/.*# deb: (\S*).*/\1/p' setup.cfg)"

    # shellcheck disable=SC2086
    $SUDO apt-get $APT_OPTIONS install $packages

    for package in $packages; do
        minver=$(sed -Ene "s/.*# deb: $package >= //p" setup.cfg)
        if [ -n "$minver" ]; then
            verify_minimum_package_version "$package" "$minver"
        fi
    done
}

setup_settings() {
    echo ">>> Installing a configuration file"
    cp debusine/project/settings/local.py.sample debusine/project/settings/local.py
}

setup_database() {
    echo ">>> Configuring postgresql user and databases"
    $SUDO_U postgres -- createuser -d "$USER" || true
    if ! $SUDO_U postgres -- psql -A -l | grep -q '^debusine|'; then
        $SUDO_U postgres -- createdb -O "$USER" -E UTF8 debusine
    fi
}

create_directories() {
    echo ">>>> creating directories required by debusine"
    mkdir -p "data/uploads" "data/store" "data/cache" "data/logs" "data/media" "data/static" "data/templates"
}

if [ ! -e debusine/project/settings/local.py.sample ]; then
    echo "ERROR: are you at the root of the debusine repository?" >&2
    usage >&2
    exit 1
fi

case "$1" in
    "")
        sanity_checks
        install_packages
        setup_settings
        setup_database
        create_directories
        ;;
    -h|--help)
        usage
        ;;
    create_directories)
        create_directories
        ;;
    install_packages)
        install_packages
        ;;
    setup_settings)
        setup_settings
        ;;
    setup_database)
        setup_database
        ;;
esac

