#!/usr/bin/env bash

# Where to locally install
install_dir="${HOME}/.local/share/czp.local"

apt_repo='http://pkg.celforyon.fr/pool/main'

# Main program
cfyzshprompt_pkg="cfyzshprompt_3.2.2_bookworm_amd64.deb"

# Extensions
extensions=()
extensions+=("cfyzshprompt-errno_1.6.1_bookworm_amd64.deb")
extensions+=("cfyzshprompt-git_3.3.1_bookworm_amd64.deb")
extensions+=("cfyzshprompt-text_1.0.2_bookworm_amd64.deb")

apt_repo_path_from_pkg() {
	pkg="$1"
	first_letter="$(cut -c1 <<< "${pkg}")"
	pkg_name="$(cut -d_ -f1 <<< "${pkg}")"
	echo "${apt_repo}/${first_letter}/${pkg_name}/${pkg}"
}

# Script
mkdir -p "${install_dir}"

wget -c "$(apt_repo_path_from_pkg "${cfyzshprompt_pkg}")"
dpkg -x "${cfyzshprompt_pkg}" "${install_dir}"
sed -i -e "/^extallpath=\"\/usr/s,/,${install_dir}/," "${install_dir}/usr/bin/cfyze"
sed -i -e "/^czp_executable=/s,'cfyzshprompt',${install_dir}/usr/bin/cfyzshprompt," "${install_dir}/usr/share/zsh/functions/Prompts/prompt_cfy_setup"
sed -i -e "/\"\/etc/s,/etc,${install_dir}/etc," "${install_dir}/usr/share/zsh/functions/Prompts/prompt_cfy_setup"
sed -i -e "/\"\/usr/s,/usr,${install_dir}/usr," "${install_dir}/usr/share/zsh/functions/Prompts/prompt_cfy_setup"
cp "${install_dir}/etc/cfyzshprompt/example.config" "${install_dir}/etc/cfyzshprompt/config"
rm "${cfyzshprompt_pkg}"

for extension in ${extensions[@]}; do
	wget -c "$(apt_repo_path_from_pkg "${extension}")"
	dpkg -x "${extension}" "${install_dir}"
	rm "${extension}"
done

clear
echo '=========================================================================='
echo '== ZSH configuration (~/.zshrc) =========================================='
echo
echo '1. add **before** "autoload -Uz promptinit" this line:'
echo "fpath=(\${fpath} '${install_dir}/usr/share/zsh/functions/Prompts')"
echo
echo '2. remplace "prompt XXX" with (or add **after** "promptinit" if no such line):'
echo 'prompt cfy'
echo
echo '3. update your PATH (anywhere):'
echo "export PATH=\"${PATH}:${install_dir}/usr/bin\""
echo
echo "You can use \`cfyze\` normally."
echo 'Do not forget to "prompt cfy" again the **first time** you enable an extension'
