#!/usr/bin/env bash

set -o errexit
set -o nounset
set -o pipefail

trap 'exit -2' INT

# shellcheck source=utils.sh
source ~/.config/yadm/utils.sh

OS_NAME=$(uname -s)

# A "full" bootstrap means to run everything. Otherwise just update vscode extension
# (and maybe fish completions)
: "${YADM_BOOTSTRAP_FULL:=0}"

function setup_macos() {
    if command -q darwin-rebuild &>/dev/null; then
        darwin-rebuild switch
    else
        nix run flake:nix-darwin -- switch --flake ~/.config
    fi

    echo "macOS-specific setup is complete!"
}

function setup_linux() {
    # TBD. Might need separate function each for NixOS / Termux
    echo "Linux-specific setup is complete!"
}

function main() {
    cd ~ || exit 1

    yadm submodule update --init

    # Include "shared" git config in yadm repo
    yadm gitconfig --local include.path ~/.config/yadm/.gitconfig

    # Install pre-commit hook, and tell it to point at custom config location
    yadm enter \
        ~/.config/yadm/hooks/pre-commit.pyz install \
        --config ~/.config/yadm/.pre-commit-config.yaml

    if [[ -z "$(yadm config local.class)" ]]; then
        local class
        read -p "Enter a value for yadm's 'local.class': " -r class
        yadm config local.class "$class"
    fi

    yadm alt

    if [[ $YADM_BOOTSTRAP_FULL -eq 1 ]]; then
        # For now, OS-specific bootstrap is part of "full". Might make sense
        # to break them out separately in the future.
        if [[ "$OS_NAME" == "Darwin" ]]; then
            setup_macos
        elif [[ "$OS_NAME" == "Linux" ]]; then
            setup_linux
        fi

        if false; then
            # Install homebrew and use it to install basic packages/apps
            if ! command -v brew &>/dev/null && \
                confirm "'brew' command not found. Install it? "
            then
                eval "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
                echo
            fi

            if ! brew bundle --global check && \
                confirm "Install packages from Brewfile? "
            then
                brew bundle --global install
                echo
            fi
        fi

        if confirm "Update fish auto-generated completions?"; then
            fish -c 'fish_update_completions'
        fi

        if confirm "Install fisher plugins?"; then
            fish -c 'set -gx fisher_path ~/.config/fish/fisher_install && fisher update'
        fi

        # Load GPG configuration for timeouts
        gpgconf --reload gpg-agent

        if confirm "Decrypt encrypted files?"; then
            yadm git-crypt unlock
        fi
    fi

    if ! check_vscode_exts &>/dev/null && \
        confirm "Install VSCode extensions?"
    then
        install_vscode_exts
    else
        echo "VSCode extensions are up-to-date."
    fi
}

main "$@"
