# Nushell Environment Config File
#
# version = "0.86.0"

def create_left_prompt [] {
    let home =  $nu.home-path

    # Perform tilde substitution on dir
    # To determine if the prefix of the path matches the home dir, we split the current path into
    # segments, and compare those with the segments of the home dir. In cases where the current dir
    # is a parent of the home dir (e.g. `/home`, homedir is `/home/user`), this comparison will
    # also evaluate to true. Inside the condition, we attempt to str replace `$home` with `~`.
    # Inside the condition, either:
    # 1. The home prefix will be replaced
    # 2. The current dir is a parent of the home dir, so it will be uneffected by the str replace
    let dir = (
        if ($env.PWD | path split | zip ($home | path split) | all { $in.0 == $in.1 }) {
            ($env.PWD | str replace $home "~")
        } else {
            $env.PWD
        }
    )

    # Arrow of prompt
    let arrow_color = if "SSH_CLIENT" in $env {
        ansi green_bold
    } else {
        ansi magenta_bold
    }

    let first_line_arrow = "┌──"
    let second_line_arrow = "└▷"

    # Time
    let time_color = ansi magenta_bold
    let time_segment = date now | format date ' [%H:%M] '

    # Name of the current user
    let username_color = ansi magenta_bold
    let username = $env.USER

    # Delimiter between user and hostname, then hostname and cwd
    let delimiter_color = ansi yellow_bold
    let first_delimiter = "@"
    let second_delimiter = "::"

    # Hostname
    let hostname_color = ansi green_bold
    let hostname = (sys).host.hostname

    # Current director
    let dir_color = ansi blue_bold
    let reset_ansi = ansi reset

    # Current git branch, with * if things are not commited
    let git_color = [(ansi reset), (ansi yellow)] | str join
    let git_branch = do { git rev-parse --abbrev-ref HEAD }
      | complete
      | update stdout ($in.stdout | str trim -c "\n")

    let git_status = do { git status -s } | complete | get stdout | str trim -c "\n"

    let git_changed = if $git_status == "" {
        ""
    } else {
        "*"
    }

    let git_branch_content = if $git_branch.exit_code == 0 {
        [$git_color, " ‹", $git_branch.stdout, $git_changed, "›"] | str join
    } else {
        ""
    }

    # Current kube
    let kube_color = ansi cyan_bold

    let kube = if ("KUBECONFIG" in $env) {
        let kube_name = $env.KUBECONFIG | path dirname | path basename
        [$kube_color, " ‹", $kube_name, "›"] | str join

    } else {
        ""
    }

    let sudo_compromised = if not (which ^sudo | get path.0) == "/usr/bin/sudo" {
        (ansi red_bold) + " ‹sudo compromised›" + (ansi reset)
    } else {
        ""
    }

    let fudo_running = if (do { systemctl status fudo } | complete | get exit_code) == 0 {
        (ansi red_bold) + " ‹fudo running›" + (ansi reset)
    } else {
        ""
    }

    [
        $arrow_color
        $first_line_arrow
        $time_color
        $time_segment
        $username_color
        $username
        $delimiter_color
        $first_delimiter
        $hostname_color
        $hostname
        $delimiter_color
        $second_delimiter
        $dir_color
        $dir
        $git_branch_content
        $kube
        $sudo_compromised
        $fudo_running
        "\n"
        $reset_ansi
        $arrow_color
        $second_line_arrow
    ] | str join
}

def create_right_prompt [] {
    let last_exit_code = if ($env.LAST_EXIT_CODE != 0) {([
        "\e[B"
        (ansi red_bold)
        ($env.LAST_EXIT_CODE)
        " ↵ "
    ] | str join)
    } else {([
        "\e[B"
        (ansi green_bold)
        ($env.LAST_EXIT_CODE)
        " ↵ "
    ] | str join)
    }

    ([$last_exit_code] | str join)
}

# Use nushell functions to define your right and left prompt
$env.PROMPT_COMMAND = {|| create_left_prompt }
# FIXME: This default is not implemented in rust code as of 2023-09-08.
$env.PROMPT_COMMAND_RIGHT = {|| create_right_prompt }

# The prompt indicators are environmental variables that represent
# the state of the prompt
$env.PROMPT_INDICATOR = {|| "  " }
$env.PROMPT_INDICATOR_VI_INSERT = {|| ": " }
$env.PROMPT_INDICATOR_VI_NORMAL = {|| "> " }
$env.PROMPT_MULTILINE_INDICATOR = {|| "::: " }

# If you want previously entered commands to have a different prompt from the usual one,
# you can uncomment one or more of the following lines.
# This can be useful if you have a 2-line prompt and it's taking up a lot of space
# because every command entered takes up 2 lines instead of 1. You can then uncomment
# the line below so that previously entered commands show with a single `🚀`.
# $env.TRANSIENT_PROMPT_COMMAND = {|| "🚀 " }
# $env.TRANSIENT_PROMPT_INDICATOR = {|| "" }
# $env.TRANSIENT_PROMPT_INDICATOR_VI_INSERT = {|| "" }
# $env.TRANSIENT_PROMPT_INDICATOR_VI_NORMAL = {|| "" }
# $env.TRANSIENT_PROMPT_MULTILINE_INDICATOR = {|| "" }
# $env.TRANSIENT_PROMPT_COMMAND_RIGHT = {|| "" }

# Specifies how environment variables are:
# - converted from a string to a value on Nushell startup (from_string)
# - converted from a value back to a string when running external commands (to_string)
# Note: The conversions happen *after* config.nu is loaded
$env.ENV_CONVERSIONS = {
    "PATH": {
        from_string: { |s| $s | split row (char esep) | path expand --no-symlink }
        to_string: { |v| $v | path expand --no-symlink | str join (char esep) }
    }
    "Path": {
        from_string: { |s| $s | split row (char esep) | path expand --no-symlink }
        to_string: { |v| $v | path expand --no-symlink | str join (char esep) }
    }
}

# Directories to search for scripts when calling source or use
$env.NU_LIB_DIRS = [
    # FIXME: This default is not implemented in rust code as of 2023-09-06.
    ($nu.default-config-dir | path join 'scripts') # add <nushell-config-dir>/scripts
]

# Directories to search for plugin binaries when calling register
$env.NU_PLUGIN_DIRS = [
    # FIXME: This default is not implemented in rust code as of 2023-09-06.
    ($nu.default-config-dir | path join 'plugins') # add <nushell-config-dir>/plugins
]

# LS_COLORS so that ls mimics the colors of exa
$env.LS_COLORS = ([
    # File types
    "ex=1;32"            # Executables
    "di=1;34"            # Directories
    "ln=36"              # Links
    "or=31"              # Orphan

    # Media types
    "*.pdf=32"           # PDF files

    # Images
    "*.webp=35"          # Webp image
    "*.png=35"           # PNG image
    "*.jpg=35"           # JPG image

    # Music
    "*.ogg=36"           # OGG sound
    "*.mp3=36"           # MP3 sound

    # Videos
    "*.mp4=1;35"         # MP4 video
    "*.avi=1;35"         # AVI video
    "*.webm=1;35"        # WebM video

    # Bold yellow: source code
    "*.c=1;33"           # C source
    "*.h=1;33"           # C header
    "*.cpp=1;33"         # C++ source
    "*.hpp=1;33"         # C++ header
    "*.inl=1;33"         # C++ include
    "*.cxx=1;33"         # C++ include
    "*.py=1;33"          # Python
    "*.js=1;33"          # JavaScript
    "*.ts=1;33"          # TypeScript
    "*.rs=1;33"          # Rust
    "*.elm=1;33"         # Elm
    "*.nu=1;33"          # Nushell

    # Build / doc files
    "*Makefile=1;4;33"   # Makefile
    "*Dockerfile=1;4;33" # Dockerfile
    "*.md=1;4;33"        # Markdown
    "*.toml=1;4;33"      # Toml
] | str join ":")

# French by default
$env.LANG = fr_FR.UTF-8

# Gnome Keyring Daemon
$env.GNOME_KEYRING_DAEMON = '/run/user/1000/keyring'

# Text file editor
$env.EDITOR = nvim

# Backtrace for rust
$env.RUST_BACKTRACE = full

# Gclone env
$env.GCLONE_PATH = $env.HOME + '/git'
$env.GCLONE_FORCE_SSH = true

# Python virtual env
$env.VIRTUAL_ENV = $env.HOME + '/.venv'

# Don't put ugly go directory in my home
$env.GOPATH = $env.HOME + '/.go'

# To add entries to PATH (on Windows you might use Path), you can use the following pattern:
# $env.PATH = ($env.PATH | split row (char esep) | prepend '/some/path')
$env.PATH = ($env.PATH
    | split row (char esep)
    | prepend ($env.HOME + '/.config/polymny/bin')
    | prepend ($env.HOME + '/.config/dotfiles/bin')
    | prepend ($env.HOME + '/.config/dotfiles/bin-extra')
    | prepend ($env.HOME + '/.cargo/bin')
    | prepend ($env.HOME + '/.npmbin/bin')
    | prepend ($env.HOME + '/.venv/bin')
)