#!/usr/bin/env bash

# nvims Safely experiment with multiple Neovim configurations.

# Checkinstall to produce a deb package
cd /var/tmp || exit

DEST=${1:-/etc/skel}
GITHUB_USER=traap
PROJECT=nvims
ARCH=$(dpkg --print-architecture)
# RELEASE=$(lastversion --format="tag" "${GITHUB_USER}/${PROJECT}") #$(lastversion --form "${PROJECT}")
LATEST_URL="https://api.github.com/repos/${GITHUB_USER}/${PROJECT}/releases/latest"
# RELEASE=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | grep -Po '"tag_name": "v\K[^"]*')
# GIT_TAG=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | jq -r .tag_name)
# DOWNLOAD_DIR=/tmp
RELEASE=git

RSS_FEED="https://github.com/${GIT_USER}/${PROJECT}/releases.atom"
# xdg-open ${RSS_FEED}
echo ${RSS_FEED}

# make a containing directory
mkdir -p /var/tmp/${PROJECT}-"${RELEASE}"
echo "git clone --depth 1 https://github.com/${GITHUB_USER}/${PROJECT} /var/tmp/${PROJECT}-${RELEASE}"
git clone --depth 1 https://github.com/${GITHUB_USER}/${PROJECT} /var/tmp/${PROJECT}-"${RELEASE}"
cd /var/tmp/${PROJECT}-"${RELEASE}" || exit

cat <<-EOF | tee ./description-pak
	Safely experiment with multiple Neovim configurations.
EOF

cat <<-EOF | tee ./checkinstall_it.sh

	echo "ENTERING CHECKINSTALL"

	BASE_URL='https://raw.githubusercontent.com/'
	BASE_USER=${GITHUB_USER}
	BASE_REPO=${PROJECT}
	LICENSE_URL="\${BASE_URL}/\${BASE_USER}/\${BASE_REPO}"/master/LICENSE
	# wget -c \${LICENSE_URL}

	VERSION=\$(date +%Y-%m-%d_)git
	# VERSION=${RELEASE}
	RELEASE="1"
	LICENSE=bsd

	# make a new temporary directory for this use
	BASE_TMP_DIR=~/tmptmp/checkinstall_tmp
	mkdir -p \${BASE_TMP_DIR}

	# do your work
	sudo checkinstall -y --fstrans \
	  --exclude=/home/${USER}/.sudo_as_admin_successful \
	  --pkgname=neovim-\${BASE_REPO} \
	  --pkgversion=\${VERSION}\
	  --pkgrelease="\${RELEASE}" \
	  --pkgarch=\${ARCH} \
	  --pkggroup=development \
	  --pkglicense=\$LICENSE \
	  --pkgsource=${LATEST_URL} \
	  --maintainer=cyteen@ring-zero.co.uk \
	  --requires=fzf,git \
	  -D \
	  bash ./install_it.sh
EOF

cat <<-EOF | tee ./install_it.sh
	# Copy files to their production locations.
	sudo cp -v nvims /usr/local/bin/.
	sudo chmod -v +x /usr/local/bin/nvims
EOF

# Create config directory and copy files there.
sudo -u ${USER} bash -c "mkdir -p "${DEST}"/.config/nvims"
sudo -u ${USER} bash -c "cp -v neovim_distros "${DEST}"/.config/nvims/."

# Each install of an nvim has an alias appended to nvim-appname so we
# sources it in our environment.
cat <<-EOF | tee ${HOME}/.zshrc.d/008_nvims_appnames.zsh
	if [[ -f "${HOME}/.config/nvims/nvim_appnames" ]]; then
	  source "${HOME}/.config/nvims/nvim_appnames"
	fi
EOF

bash ./checkinstall_it.sh
