#!/usr/bin/env bash

set -e

XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
NIX_CONF="$XDG_CONFIG_HOME/nix/nix.conf"

if test -e "$NIX_CONF"; then
    echo "Nix config already found at $NIX_CONF"
    echo "Please make sure it contains the following settings:"
    echo
    cat $(dirname $0)/nix.conf
    echo
else
    echo "Installing nix config at $NIX_CONF"
    mkdir -p "$XDG_CONFIG_HOME/nix/"
    cp --verbose $(dirname $0)/nix.conf "$NIX_CONF"
fi

if nix --version &> /dev/null; then
    echo "Nix already installed, exiting."
    exit 1
fi

if apt-get --version &> /dev/null; then
    set -x
    sudo apt-get update -y
    sudo apt-get install -y nix
    sudo usermod -aG nix-users $USER
    # Spawn new shell with updated group membership
    newgrp nix-users
elif pacman --version &> /dev/null; then
    set -x
    sudo pacman -S nix
elif dnf --version &> /dev/null; then
    set -x
    sudo dnf install nix nix-daemon -y
else
    echo "Failed to detect package manager. Please install nix manually."
    echo "We recommend using the official nix installer: https://nixos.org/download/"
    exit 2
fi

sudo systemctl enable --now nix-daemon
