#!/usr/bin/env bash

scriptdir=$(dirname $(realpath $0))

# ============================================================

. $scriptdir/utils.sh

# ============================================================

update_authorized_keys() {
    [ ! -f ~/.ssh/authorized_keys ] && return

    local public_keys=$(cat $scriptdir/files/authorized_keys)
    while IFS= read -r public_key; do
        [[ $public_key == \#* ]] && continue
        if ! grep -q "$public_key" ~/.ssh/authorized_keys; then
            echo "$public_key" >> ~/.ssh/authorized_keys
            echo "Added public key to authorized_keys: $public_key"
        fi
    done <<< "$public_keys"
}

configure_ssh() {
    [ -f ~/.ssh/authorized_keys ] && return

    if confirm_action "要配置 authorized_keys 吗？" "N"; then
        mkdir -p ~/.ssh
        cp $scriptdir/files/authorized_keys ~/.ssh/authorized_keys
    fi
}

configure_ssh_keygen() {
    [ -f ~/.ssh/id_ed25519.pub ] && return

    if confirm_action "要生成 sshkey 吗？" "N"; then
        mkdir -p ~/.ssh
        read -p "sshkey 的名字: " sshkeyname
        ssh-keygen -t ed25519 -C $sshkeyname
    fi
}

configure_git() {
    [ -f ~/.gitconfig ] && return

    if confirm_action "要配置 git 吗？" "N"; then
        cp $scriptdir/files/.gitconfig ~/.gitconfig
    fi
}

configure_miniconda() {
    [ -d ~/.miniconda3 ] && return

    if confirm_action "要安装 miniconda 吗？" "Y"; then
        wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O $tempdir/miniconda.sh
        bash $tempdir/miniconda.sh -b -p ~/.miniconda3
        rm $tempdir/miniconda.sh
        ~/.miniconda3/bin/conda init zsh
        ~/.miniconda3/bin/conda config --set changeps1 False
        ~/.miniconda3/bin/conda install -c conda-forge mamba
        ~/.miniconda3/bin/mamba init
    fi
}

configure_nodejs() {
    [ -d ~/.nvm/.git ] && return

    if confirm_action "要安装 nvm 和 nodejs 吗？" "Y"; then
        git_clone nvm-sh/nvm ~/.nvm --depth=1
        \. $scriptdir/files/install-nvm.sh
        \. ~/.nvm/nvm.sh
        \. ~/.nvm/bash_completion
        nvm install lts/iron
        nvm alias default lts/iron
        nvm install-latest-npm
    fi
}

# ============================================================

update_file $scriptdir/files/ys-simple.zsh-theme ~/.oh-my-zsh/themes/ys-simple.zsh-theme
update_authorized_keys

if [ $# -ne 0 ]; then
    for func in $@; do
        declare -F configure_$func >/dev/null || continue
        echo "Configuring $func..."
        eval "configure_$func"
    done
    return
fi

configure_ssh
configure_ssh_keygen
configure_git
configure_miniconda
configure_nodejs
