#! /usr/bin/env bash

set -e

BASE_0=${BASE_0:-$0}
BASE_SHELL=$(basename "$SHELL")

_update-nvim() {
    local LatestURL="$(get-github-release.sh \
        neovim/neovim latest appimage \
        | grep appimage\$
    )"
    local appDir="${HOME}/.local/bin"
    if [ "$USER" = "root" ]; then
        appDir="${HOME}/usr-local-bin"
        while umount --types overlay /usr/local/bin 2>/dev/null; do
            :
        done
        mkdir -pm 755 "$appDir" \
            && mount -t overlay overlay -o "lowerdir=$appDir:/usr/local/bin" /usr/local/bin
        update-alternatives --remove vim.tiny /usr/bin/vim.tiny
    fi
    local appPath="${appDir}/nvim.AppImage"

    rm "${appDir}/"{nvim.AppImage,nvim,vi,vim,vim.tiny,vimdiff} 2>/dev/null || true

    printf 'Downloading from %s... ' "${LatestURL#*/download/}"
    curl -sLo "$appPath" "$LatestURL" && printf 'Done'
    printf '\n'
    chmod +x "$appPath"

    ln -rs "$appPath" "${appDir}/nvim"
    ln -rs "$appPath" "${appDir}/vi"
    ln -rs "$appPath" "${appDir}/vim"
    ln -rs "$appPath" "${appDir}/vim.tiny"
    ln -rs "$appPath" "${appDir}/vimdiff"

    if [ "$USER" = "root" ]; then
        update-alternatives --install /usr/bin/editor editor "$appPath" 110
        update-alternatives --install /usr/bin/edit edit "$appPath" 110
        update-alternatives --install /usr/bin/ex ex "$appPath" 110
        update-alternatives --install /usr/bin/vi vi "$appPath" 110
        update-alternatives --install /usr/bin/view view "$appPath" 110
        update-alternatives --install /usr/bin/vim vim "$appPath" 110
        update-alternatives --install /usr/bin/vimdiff vimdiff "$appPath" 110
        update-alternatives --set editor "$appPath"
        update-alternatives --set edit "$appPath"
        update-alternatives --set ex "$appPath"
        update-alternatives --set vi "$appPath"
        update-alternatives --set view "$appPath"
        update-alternatives --set vim "$appPath"
        update-alternatives --set vimdiff "$appPath"

    fi
}

_update-nvim "${@}"