#!/usr/bin/env bash

# LICENSE
#   Copyright 2022 Jeffrey Serio <hyperreal@fedoraproject.org>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <https://www.gnu.org/licenses/>.

set -eu
set -o pipefail
set -o posix

# Check for dependencies: curl and gum.
if ! test -x "$(command -v curl)"; then
    echo "Missing dependencies: please install curl."
    exit 1
fi

if ! test -x "$(command -v gum)"; then
    echo "Missing dependencies: please install the gum command."
    echo "See https://github.com/charmbracelet/gum"
    exit 1
fi

# Define variables
NF_BASE_URL="https://github.com/ryanoasis/nerd-fonts/releases/download"
NF_VERSION=$(curl -sL https://github.com/ryanoasis/nerd-fonts/releases/latest | grep "<title>Release" | awk '{ print $2 }')
NF_URL="${NF_BASE_URL}/${NF_VERSION}"
LOCAL_FONT_DIR="${HOME}/.local/share/fonts"

# Fancy error output message.
gum_error() {
    gum style \
        --foreground 3 \
        --border-foreground 203 \
        --border rounded \
        --align center \
        --width 50 \
        --margin "1 2" \
        "ERROR" \
        "" \
        "$1"
    exit 1
}

# Array of nerd font names.
nf_array=(
    3270
    Agave
    AnonymousPro
    Arimo
    AurulentSansMono
    BigBlueTerminal
    BitstreamVeraSansMono
    CascadiaCode
    CodeNewRoman
    Cousine
    DaddyTimeMono
    DejaVuSansMono
    DroidSansMono
    EnvyCodeR
    FantasqueSansMono
    FiraCode
    FiraMono
    Go-Mono
    Gohu
    Hack
    Hasklig
    HeavyData
    Hermit
    iA-Writer
    IBMPlexMono
    Inconsolata
    InconsolataGo
    InconsolataLGC
    IntelOneMono
    Iosevka
    JetBrainsMono
    Lekton
    LiberationMono
    Lilex
    Meslo
    Monofur
    Monoid
    Mononoki
    MPlus
    Noto
    OpenDyslexic
    Overpass
    ProFont
    ProggyClean
    RobotoMono
    ShareTechMono
    SourceCodePro
    SpaceMono
    Terminus
    Tinos
    Ubuntu
    UbuntuMono
    VictorMono
)

# Print the startup message.
message=$(echo "Nerd font installer :nerd_face:" | gum format -t emoji)
gum style \
    --foreground 212 \
    --border-foreground 57 \
    --border rounded \
    --align center \
    --width 50 \
    --margin "1 2" \
    "$message"

# Print the `nf_array` line by line and pipe to `gum choose --no-limit`.
# Create `selection` array from the output of `gum choose --no-limit`.
# It will contain only the items that were selected by the user.
selection=($(printf "%s\n" "${nf_array[@]}" | gum choose --no-limit))

# Prompt for user confirmation and proceed with installation of nerd fonts.
#
# For each nerd font selected, print a status message while downloading and
# installing the nerd font. Else print an error message if any of it fails.
#
# If user declines to proceed with installation, print a cancel message.
if gum confirm "Proceed with installation?"; then
    for item in "${selection[@]}"; do
        if ! gum spin --spinner dot --title "Downloading $item..." \
            -- curl --create-dirs -f -sL -o "${LOCAL_FONT_DIR}/$item.zip" "${NF_URL}/$item.zip"; then
            gum_error "Failed to download nerd font archive $item"
        fi
        if ! gum spin --spinner dot --title "Installing $item..." \
            -- unzip -uo "${LOCAL_FONT_DIR}/$item.zip" -d "${LOCAL_FONT_DIR}"; then
            gum_error "Failed to install nerd font archive $item"
        fi
    done
else
    gum style \
        --foreground 212 \
        --border-foreground 57 \
        --border rounded \
        --align center \
        --width 50 \
        --margin "1 2" \
        "Nerd font installation cancelled"
fi

# Clean up local font directory. Removes everything besides fonts.
if ! gum spin --spinner dot --title "Cleaning up local font directory..." \
    -- find "${LOCAL_FONT_DIR}" -mindepth 1 \
        -not -name "*.otf" \
        -not -name "*.ttf" \
        -not -name "static" \
        -exec rm -rf {} \; ; then
    gum_error "Failed to clean up local font directory. Try doing it manually."
fi

# Update font cache
if ! gum spin --spinner dot --title "Updating font cache..." \
    -- fc-cache -f; then
    gum_error "Failed to update font cache."
fi

# Print a message stating which nerd fonts were installed.
gum format -t markdown -- \
    "# Successfully installed" \
    "$(printf "* %s\n" "${selection[@]}")"