#!/bin/bash -e
# Setup the repository and local system for development

cd "$(dirname "$0")/.."

setup_deps()
{
    OS=$1
    read -p  "Install build dependencies? (y/n) " question
    if [ "$question" = "y" ]; then
        DEPS=$(./contrib/ci/generate_dependencies.py)
        if [ "$OS" = "debian" ] || [ "$OS" = "ubuntu" ]; then
            if ! python3 -c "import venv"; then
                DEPS="python3-venv"
            fi
            sudo apt install $DEPS
        elif [ "$OS" = "fedora" ]; then
            sudo dnf install $DEPS
        elif [ "$OS" = "arch" ]; then
            pacman -Syu --noconfirm --needed $DEPS
        elif [ "$OS" = "void" ]; then
            xbps-install -Syu $DEPS
        fi
    fi
}

setup_run_dev()
{
    read -p "Set up dbus activated daemon and PolicyKit actions from /usr/local? (y/n) " question
    if [ "$question" = "y" ]; then
        ./contrib/prepare-system /usr/local install
    fi
}

setup_vscode()
{
    # Add default vscode settings if not existing
    SETTINGS_FILE=./.vscode/settings.json
    SETTINGS_TEMPLATE_FILE=./contrib/vscode/settings.json
    if [ ! -f "$SETTINGS_FILE" ]; then
        mkdir ./.vscode
        echo "Copy $SETTINGS_TEMPLATE_FILE to $SETTINGS_FILE."
        cp "$SETTINGS_TEMPLATE_FILE" "$SETTINGS_FILE"
    fi
}

setup_precommit()
{
    echo "Configuring pre-commit hooks"
    python3 -m venv venv
    source venv/bin/activate

    python3 -m pip install pre-commit
    pre-commit install
}

#if interactive install build deps and prepare environment
if [ -t 2 ]; then
    OS=$(python3 -c "import distro; print(distro.linux_distribution()[0].split()[0].lower())")
    case $OS in
        debian|ubuntu|arch|fedora)
            setup_deps $OS
            setup_run_dev
            ;;
        void)
            setup_deps $OS
            ;;
    esac
    setup_vscode
fi

#always setup pre-commit
setup_precommit
