#!/usr/bin/env bash

if [ "$(uname -s)" == "Linux" ]; then
    FONT_DIR="$HOME/.local/share/fonts"
    NF_DL_DIR="$HOME/.cache/fzf/nf-dl"
elif [ "$(uname -s)" == "Darwin" ]; then
    FONT_DIR="/Applications/Fonts"
    NF_DL_DIR="/Library/Caches/fzf/nf-dl"
fi

blu=$(tput setaf 4) cyn=$(tput setaf 6) bld=$(tput bold) rst=$(tput sgr0)

get_nf_links() {
    curl --silent https://www.nerdfonts.com/font-downloads | grep '/download/' | cut -d'"' -f 2 | sort -u
}

set_nf_name() {
    get_nf_links | \
        awk -v blu="${blu}" -v cyn="${cyn}" -v bld="${bld}" -v rst="${rst}" \
         -F'/' '
        {
            print blu bld $9 rst "&& - " cyn $0
        }' \
        | sed 's/\.zip//' | column -ts '&&'
}

if [ ! -d "$NF_DL_DIR" ]; then
    mkdir -p "$NF_DL_DIR"
    set_nf_name > "$NF_DL_DIR"/nf-dl_url
fi

declare tmp_file ls_installed_font
tmp_file="$(mktemp)";   echo 'install' > "$tmp_file";   trap 'rm -f $tmp_file' EXIT
ls_installed_font="find \"${FONT_DIR}\" -mindepth 1 -type d -printf \"${bld}${blu}%f\n\""

cat < "$NF_DL_DIR/nf-dl_url"  | \
    fzf --ansi +x \
    --tiebreak=begin \
    --layout=reverse \
    --prompt="  nf-dl > " \
    --preview-window=hidden \
    --header='<M-i>:nstall | <M-u>:ninstall | <Del>:ete cache ' \
    --bind="alt-u:reload($ls_installed_font)+execute-silent(echo 'remove' > $tmp_file)" \
    --bind="alt-i:reload(cat < \"$NF_DL_DIR/nf-dl_url\")+execute-silent(echo 'install' > $tmp_file)" \
    --bind="del:execute(rm -rf $NF_DL_DIR;)" \
    --bind="enter:execute(
    if grep -q 'install' $tmp_file ; then
        echo -e '${bld}${blu}Downloading ${cyn}{1} Nerd Font...${rst}\n';wget {3}
        [ -d ${FONT_DIR} ] || mkdir -p ${FONT_DIR}/{1}
        unzip {1} -d ${FONT_DIR}/{1}
        fc-cache -f ${FONT_DIR} && [ -e ${FONT_DIR}/{1} ] && echo \"\n${bld}${cyn}Nerd Font: ${blu}{1} ${rst}has been installed\n\"
        echo -e \"${bld}${cyn}Would you like to delete or keep ${blu}{1}.zip${rst} (y/n):\" && rm -i {1}.zip
        echo -e '\n${blu}${bld}Press any key to continue...${rst}' && read -rsk1
    else 
        echo -e \"${bld}${blu}Uninstall/Remove ${cyn}Nerd Font: {1} ${rst}(y/n):\" 
        [ -d ${FONT_DIR}/{1} ] && rm -IR ${FONT_DIR}/{1}; echo 'remove' > $tmp_file
        fc-cache -f -v && echo \"\n${bld}${cyn}Nerd Font: ${blu}{1} ${rst}has been uninstalled\"
        echo -e '\n${blu}${bld}Press any key to continue...${rst}' && read -rsk1
    fi
    )+reload(
    if grep -q 'remove' $tmp_file; then
        $ls_installed_font
    else cat < \"$NF_DL_DIR/nf-dl_url\"
    fi)" 
# to add if possible or if i can
# - preview? 
# - indicator ([x] [ ] installed or not) #maybe not
# - windows? idk this shit
