#!/usr/bin/env bash

set -e

echo "==> Aggiornamento APT..."
sudo apt update

echo "==> Installazione dipendenze..."
sudo apt install -y zsh git curl fontconfig python3

echo "==> Installazione Oh My Zsh..."

if [ ! -d "$HOME/.oh-my-zsh" ]; then
    RUNZSH=no CHSH=no KEEP_ZSHRC=yes \
        sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
else
    echo "Oh My Zsh è già installato."
fi

ZSH_CUSTOM="${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}"

echo "==> Installazione zsh-autosuggestions..."

if [ ! -d "$ZSH_CUSTOM/plugins/zsh-autosuggestions" ]; then
    git clone \
        https://github.com/zsh-users/zsh-autosuggestions \
        "$ZSH_CUSTOM/plugins/zsh-autosuggestions"
else
    echo "zsh-autosuggestions è già installato."
fi

echo "==> Installazione zsh-syntax-highlighting..."

if [ ! -d "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting" ]; then
    git clone \
        https://github.com/zsh-users/zsh-syntax-highlighting.git \
        "$ZSH_CUSTOM/plugins/zsh-syntax-highlighting"
else
    echo "zsh-syntax-highlighting è già installato."
fi

echo "==> Installazione Powerlevel10k..."

P10K_DIR="$ZSH_CUSTOM/themes/powerlevel10k"

if [ ! -d "$P10K_DIR" ]; then
    git clone --depth=1 \
        https://github.com/romkatv/powerlevel10k.git \
        "$P10K_DIR"
else
    echo "Powerlevel10k è già installato."
fi

FONT_DIR="$HOME/.local/share/fonts"
mkdir -p "$FONT_DIR"

echo "==> Installazione JetBrainsMono Nerd Font per Agnoster..."

if ! fc-list | grep -qi "JetBrainsMono Nerd Font"; then
    TMP_DIR="$(mktemp -d)"

    curl -fLo "$TMP_DIR/JetBrainsMono.tar.xz" \
        https://github.com/ryanoasis/nerd-fonts/releases/latest/download/JetBrainsMono.tar.xz

    tar -xf "$TMP_DIR/JetBrainsMono.tar.xz" -C "$FONT_DIR"

    rm -rf "$TMP_DIR"
else
    echo "JetBrainsMono Nerd Font è già installato."
fi

echo "==> Installazione MesloLGS NF per Powerlevel10k..."

install_font() {
    local filename="$1"
    local url="$2"

    if [ ! -f "$FONT_DIR/$filename" ]; then
        curl -fLo "$FONT_DIR/$filename" "$url"
    else
        echo "$filename è già installato."
    fi
}

install_font \
    "MesloLGS NF Regular.ttf" \
    "https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Regular.ttf"

install_font \
    "MesloLGS NF Bold.ttf" \
    "https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold.ttf"

install_font \
    "MesloLGS NF Italic.ttf" \
    "https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Italic.ttf"

install_font \
    "MesloLGS NF Bold Italic.ttf" \
    "https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold%20Italic.ttf"

echo "==> Aggiornamento cache font..."
fc-cache -f

ZSHRC="$HOME/.zshrc"

echo "==> Configurazione $ZSHRC..."

touch "$ZSHRC"

python3 - "$ZSHRC" <<'PY'
import re
import sys
from pathlib import Path

zshrc = Path(sys.argv[1])
text = zshrc.read_text()

required_plugins = [
    "git",
    "zsh-autosuggestions",
    "zsh-syntax-highlighting",
]

# --------------------------------------------------
# Tema
# --------------------------------------------------
# Powerlevel10k attivo.
#
# Per tornare ad Agnoster:
# ZSH_THEME="agnoster"
# --------------------------------------------------

theme_re = re.compile(
    r'(?m)^[ \t]*ZSH_THEME\s*=\s*["\'].*?["\'][ \t]*$'
)

if theme_re.search(text):
    text = theme_re.sub(
        'ZSH_THEME="powerlevel10k/powerlevel10k"',
        text,
        count=1,
    )
else:
    text = (
        'ZSH_THEME="powerlevel10k/powerlevel10k"\n'
        + text
    )

# --------------------------------------------------
# Plugins
# --------------------------------------------------

plugins_re = re.compile(
    r'(?ms)^[ \t]*plugins\s*=\s*\((.*?)\)'
)

match = plugins_re.search(text)

if match:
    content = match.group(1)

    content = re.sub(r'#.*', '', content)

    plugins = re.findall(
        r'[A-Za-z0-9_.-]+',
        content,
    )

    seen = set()
    clean_plugins = []

    for plugin in plugins:
        if plugin not in seen:
            seen.add(plugin)
            clean_plugins.append(plugin)

    for plugin in required_plugins:
        if plugin not in clean_plugins:
            clean_plugins.append(plugin)

    replacement = (
        "plugins=(\n"
        + "".join(
            f"  {plugin}\n"
            for plugin in clean_plugins
        )
        + ")"
    )

    text = (
        text[:match.start()]
        + replacement
        + text[match.end():]
    )

else:
    replacement = (
        "plugins=(\n"
        "  git\n"
        "  zsh-autosuggestions\n"
        "  zsh-syntax-highlighting\n"
        ")\n\n"
    )

    source_re = re.compile(
        r'(?m)^[ \t]*source\s+\$ZSH/oh-my-zsh\.sh'
    )

    source_match = source_re.search(text)

    if source_match:
        text = (
            text[:source_match.start()]
            + replacement
            + text[source_match.start():]
        )
    else:
        text += "\n" + replacement

# --------------------------------------------------
# Opzioni Oh My Zsh
# --------------------------------------------------

settings = [
    (
        re.compile(
            r'''(?m)^[ \t]*#?[ \t]*zstyle\s+['"]:omz:update['"]\s+mode\s+auto.*$'''
        ),
        "zstyle ':omz:update' mode auto      # update automatically without asking"
    ),

    (
        re.compile(
            r'(?m)^[ \t]*#?[ \t]*CASE_SENSITIVE\s*=\s*"true".*$'
        ),
        'CASE_SENSITIVE="true"'
    ),

    (
        re.compile(
            r'(?m)^[ \t]*#?[ \t]*ENABLE_CORRECTION\s*=\s*"true".*$'
        ),
        'ENABLE_CORRECTION="true"'
    ),
]

source_re = re.compile(
    r'(?m)^[ \t]*source\s+\$ZSH/oh-my-zsh\.sh'
)

for regex, replacement in settings:
    if regex.search(text):
        text = regex.sub(
            replacement,
            text,
            count=1,
        )
    else:
        source_match = source_re.search(text)

        if source_match:
            text = (
                text[:source_match.start()]
                + replacement
                + "\n"
                + text[source_match.start():]
            )
        else:
            text += "\n" + replacement + "\n"

# --------------------------------------------------
# Powerlevel10k config
# --------------------------------------------------

p10k_line = '[[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh'

if p10k_line not in text:
    text += (
        "\n"
        "# Powerlevel10k configuration.\n"
        "# Run `p10k configure` to customize the prompt.\n"
        + p10k_line
        + "\n"
    )

zshrc.write_text(text)
PY

echo "==> Impostazione zsh come shell predefinita..."

ZSH_PATH="$(command -v zsh)"
CURRENT_USER="$(id -un)"

if ! grep -qxF "$ZSH_PATH" /etc/shells; then
    echo "$ZSH_PATH" | sudo tee -a /etc/shells >/dev/null
fi

CURRENT_SHELL="$(getent passwd "$CURRENT_USER" | cut -d: -f7)"

if [ "$CURRENT_SHELL" != "$ZSH_PATH" ]; then
    sudo chsh -s "$ZSH_PATH" "$CURRENT_USER"
    echo "zsh impostato come shell predefinita per $CURRENT_USER."
else
    echo "zsh è già la shell predefinita per $CURRENT_USER."
fi

echo
echo "========================================"
echo " Installazione completata"
echo "========================================"
echo
echo "Installato:"
echo "  - zsh"
echo "  - git"
echo "  - curl"
echo "  - Oh My Zsh"
echo "  - Powerlevel10k"
echo "  - zsh-autosuggestions"
echo "  - zsh-syntax-highlighting"
echo "  - MesloLGS NF"
echo "  - JetBrainsMono Nerd Font"
echo
echo "Configurazione:"
echo "  - Tema attivo: Powerlevel10k"
echo "  - Agnoster resta disponibile"
echo "  - Auto update Oh My Zsh: attivo"
echo "  - CASE_SENSITIVE=true"
echo "  - ENABLE_CORRECTION=true"
echo
echo "Plugin:"
echo "  - git"
echo "  - zsh-autosuggestions"
echo "  - zsh-syntax-highlighting"
echo
echo "Shell predefinita:"
echo "  $ZSH_PATH"
echo
echo "Per Powerlevel10k usa come font:"
echo "  MesloLGS NF"
echo
echo "Poi esegui:"
echo "  exec zsh"
echo "  p10k configure"
echo
echo "Per tornare ad Agnoster:"
echo '  cambia ZSH_THEME="powerlevel10k/powerlevel10k"'
echo '  in ZSH_THEME="agnoster"'
echo
echo "Con Agnoster puoi usare:"
echo "  JetBrainsMono Nerd Font"
