#!/usr/bin/env bash
#Config
STEPS=15
PAD_LEN=4

BASE_PACKAGES="gnupg curl wget git"
ACT_PACKAGES="ripgrep unzip htop fzf bat gawk jq nnn tmux mc nethogs ngrep mtr gcc"

#Colors
Green='\033[0;32m'        # Green
Blue='\033[0;34m'        # Blue
Yello='\033[0;33m'        # Blue
Gray='\033[38;5;7m'       # Light Gray
NC='\033[0m'              # No Color

#short-term hack for kitty in early OSes
if [ "$TERM" == "xterm-kitty" ];then
export TERM="xterm-256color"
fi

#Setup
TERM_WIDTH_BASE=$(tput cols)
LINES=$(tput lines)
USER=$(whoami)
STEP=1
cd


echo -e "

$Green""###############################################################################
##                                                                           ##
## Ready to install Anton Volnuhin's env                                     ##
##                                                                           ##
## Press $Yello""Enter"$Green" to continue, $Yello""Ctrl-C"$Green" to abort                                  ##
## email: anton@volnuhin.com                                                 ##
##                                                                           ##
###############################################################################$NC

"
read


get_line ()
{
    IFS='[;' read -p $'\e[6n' -d R -a pos -rs || echo "failed with error: $? ; ${pos[*]}"
    echo ${pos[1]}
}

print_block ()
{
    local ln=$(get_line)
    if [[ "$ln" -lt "$(($LINES - $STEPS))" ]];then
    tput cup $(($LINES - $STEPS - 2)) 0
    else
	    ln=$(($LINES - $STEPS - 1))
    fi
    echo "..........................................................."
    for i in $(seq 1 $STEPS)
    do
	    echo -n "  >"
	    tput el
	    echo
    done
    tput cup $(($ln - 3)) 0
}

new_line () {
	# move cursor to current step's line
    local ln=$(get_line)
	tput csr 0 $LINES
	tput cup $(($LINES - $STEPS - 2 + $STEP)) 0

	echo -e "==> "$Green$1$NC
    
    STEP=$(($STEP + 1))

	tput csr 0 $(($LINES - $STEPS - 3))
	tput cup $(($ln - 1)) 0
	echo -e "\n--> "$Blue$1$NC
	tput el
}

pad() {
    local PADDING=$(printf "%${PAD_LEN}s") # 4 spaces of padding
	local TERM_WIDTH=$(($TERM_WIDTH_BASE - $PAD_LEN))
	while IFS= read -r line; do
		echo -e $Gray$line$NC | fold -s -w $TERM_WIDTH | sed "s/^/$PADDING/"
	done
}


print_block

new_line "Update caches and upgrade packages"

{{ if eq .chezmoi.os "darwin" -}}
    if ! type brew;	then
	  bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 2>&1|pad
	fi
    brew update 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "fedora" "almalinux" -}}
    sudo dnf update -y 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "debian" "ubuntu" -}}
    sudo apt-get update 2>&1|pad
	sudo DEBIAN_FRONTEND=noninteractive apt-get -o "Dpkg::Options::=--force-confold" -o "Dpkg::Options::=--force-confdef" upgrade -y  --allow-downgrades --allow-remove-essential --allow-change-held-packages 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "arch" "archarm" -}}
    sudo pacman -Syu --noconfirm 2>&1|pad

{{ end -}}


new_line "Install base packages"

{{ if eq .chezmoi.os "darwin" -}}
  brew install -q $BASE_PACKAGES python pipx 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "fedora" -}}
    sudo dnf install $BASE_PACKAGES direnv kitty-terminfo util-linux-user python3-pipx -y 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "almalinux" -}}
    sudo dnf install epel-release -y 2>&1|pad
    sudo dnf install $BASE_PACKAGES kitty-terminfo util-linux-user pipx -y 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "debian" "ubuntu" -}}
    sudo apt-get install $BASE_PACKAGES kitty-terminfo direnv pipx python3-venv -y 2>&1|pad
    sudo apt-get install software-properties-common -y 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "arch" "archarm" -}}
    sudo pacman -Sy --noconfirm $BASE_PACKAGES kitty-terminfo python-pipx 2>&1|pad

{{ end -}}


################################################################################
################################################################################
{{ if eq .chezmoi.os "linux" -}}
if ! type nix &> /dev/null
then
  new_line "Install nix packet manager (single user)"
  bash <(curl --silent -L https://nixos.org/nix/install) --no-daemon  2>&1|pad
  source ~/.nix-profile/etc/profile.d/nix.sh
fi


################################################################################
################################################################################

{{ if eq .chezmoi.osRelease.id "debian" "ubuntu" -}}


  {{ if eq .chezmoi.osRelease.id "debian" -}}

new_line "Subscribe to PPA for fish"
      ## Setup fish repo in debian
      VERS={{ .chezmoi.osRelease.versionID }}
      echo "deb http://download.opensuse.org/repositories/shells:/fish:/release:/3/Debian_$VERS/ /" | sudo tee /etc/apt/sources.list.d/shells:fish:release:3.list 2>/dev/null
      curl -fsSL "https://download.opensuse.org/repositories/shells:fish:release:3/Debian_$VERS/Release.key" | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/shells_fish_release_3.gpg > /dev/null

  {{ else -}}
new_line "Subscribe to PPA for fish"
    ## Setup fish repo in ubuntu
    sudo apt-add-repository ppa:fish-shell/release-3 -y 2>&1|pad

new_line "Subscribe to PPA for neovim"
	## Neovim ppa
	sudo add-apt-repository ppa:neovim-ppa/unstable -y 2>&1|pad

 {{ end -}}
sudo apt-get update 2>&1|pad
{{ end -}}

{{ end -}}



new_line "Install neovim, fish, atuin, jump and the rest"
{{ if eq .chezmoi.os "darwin" -}}
    brew install -q fish neovim $ACT_PACKAGES atuin jump fd sk dust lazygit 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "fedora"  -}}
    sudo dnf install neovim fish $ACT_PACKAGES fd-find skim pam_ssh_agent_auth -y  2>&1|pad
new_line "via NIX"
	nix-env -iA nixpkgs.atuin nixpkgs.jump nixpkgs.du-dust nixpkgs.lazygit 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "almalinux"  -}}
    sudo dnf install neovim fish $ACT_PACKAGES fd-find pam_ssh_agent_auth -y  2>&1|pad
new_line "via NIX"
	nix-env -iA nixpkgs.fish nixpkgs.direnv nixpkgs.atuin nixpkgs.jump nixpkgs.du-dust nixpkgs.lazygit 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "arch" "archarm" -}}
    sudo pacman -Sy --noconfirm neovim fish atuin $ACT_PACKAGES fd skim lazygit 2>&1|pad
new_line "via NIX"
	nix-env -iA nixpkgs.jump nixpkgs.du-dust 2>&1|pad

{{ else if eq .chezmoi.osRelease.id "debian" "ubuntu" -}}
    sudo apt-get install fish -y 2>&1|pad
	sudo apt-get install neovim -y 2>&1|pad
	sudo apt-get install $ACT_PACKAGES libpam-ssh-agent-auth -y 2>&1|pad

new_line "via NIX"
	nix-env -iA nixpkgs.neovim nixpkgs.lazygit nixpkgs.jump nixpkgs.skim nixpkgs.du-dust nixpkgs.atuin 2>&1|pad

{{ end -}}

new_line "Installing my authorized_keys"

mkdir ~/.ssh 2>/dev/null || true
cp ~/.ssh/authorized_keys ~/.ssh/authorized_keys.old 2>/dev/null || true

##print only unique lines
cat ~/.ssh/authorized_keys.old <(echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPdqIDeRKDOh7NQDcqnmLH/6M0ys7Wt/SEnF6ZYqroiH") 2>/dev/null | awk '!seen[$1]++' > ~/.ssh/authorized_keys

new_line "Executing neovim :Lazy sync..."
timeout 50s nvim --headless "+Lazy! sync" +qa 2>&1|pad
timeout 30s nvim --headless ":MasonUpdate" +qa 2>&1|pad

{{ if eq .chezmoi.os "linux" -}}
    new_line "Setting timezone to Moscow"
    sudo timedatectl set-timezone Europe/Moscow
{{ end -}}

new_line "Installing shell-gpt"
pipx install shell-gpt  2>&1|pad

new_line "Install fisher plugin manager for fish"
## Install fisher plugin manager for fish, so that we may update in after plugin list sync by chezmoi
if ! fish -c fisher &>/dev/null
then
  fish -c "curl -sL https://raw.githubusercontent.com/jorgebucaran/fisher/main/functions/fisher.fish | source && fisher update" 2>&1|pad
fi

new_line "Configuring tide prompt for fish"
fish -c "tide configure --auto --style=Classic --prompt_colors='True color' --classic_prompt_color=Dark --show_time='24-hour format' --classic_prompt_separators=Slanted --powerline_prompt_heads=Slanted --powerline_prompt_tails=Round --powerline_prompt_style='Two lines, frame' --prompt_connection=Disconnected --powerline_right_prompt_frame=No --prompt_connection_andor_frame_color=Darkest --prompt_spacing=Sparse --icons='Few icons' --transient=No" >/dev/null
fish -c "set -Ux tide_context_always_display true"



new_line "Change default shell to fish for user $USER"
## Change default shell to fish
if [ "$(basename $SHELL)" != "fish" ]
then
  sudo chsh -s $(command -v fish) $USER
fi

tput csr 0 $LINES
tput cup $LINES 0
echo
