#!/usr/bin/env bash
set -x

cd /var/tmp || exit

USER=jesseduffield
PROJECT=lazydocker
ARCH=$(dpkg --print-architecture)
# RELEASE=$(lastversion --format="tag" "${GITHUB_USER}/${PROJECT}") #$(lastversion --form "${PROJECT}")
LATEST_URL="https://api.github.com/repos/${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

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

# make a containing directory
mkdir -p /var/tmp/${PROJECT}-"${RELEASE}"
cd /var/tmp/${PROJECT}-"${RELEASE}" || exit

cat >./description-pak <<-EOF
	A simple terminal UI for both docker and docker-compose.
EOF

cat >./checkinstall_it.sh <<-EOF

	echo "ENTERING CHECKINSTALL"

	BASE_URL='https://raw.githubusercontent.com/'
	BASE_USER=${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=MIT

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

	# do your work
	checkinstall -y --fstrans \
		--exclude=/root/.sudo_as_admin_successful \
		--pkgname=\${PROJECT} \
		--pkgversion=\${VERSION}\
		--pkgrelease="\${RELEASE}" \
		--pkgarch=${ARCH} \
		--pkggroup=development \
		--pkglicense=MIT \
		--pkgsource=${LATEST_URL} \
		--maintainer=cyteen@ring-zero.co.uk \
		--requires=vim,git \
		-D \
		bash ./install.sh
EOF

cat >./install.sh <<-EOF
	#!/bin/bash

	# allow specifying different destination directory
	DIR="${DIR:-"$HOME/.local/bin"}"

	# map different architecture variations to the available binaries
	ARCH=$(uname -m)
	case \$ARCH in
		i386|i686) ARCH=x86 ;;
		armv6*) ARCH=armv6 ;;
		armv7*) ARCH=armv7 ;;
		aarch64*) ARCH=arm64 ;;
	esac

	GITHUB_FILE="${PROJECT}_${RELEASE}_$(uname -s)_\${ARCH}.tar.gz"
	GITHUB_URL="https://github.com/${USER}/${PROJECT}/releases/download/${GIT_TAG}/\${GITHUB_FILE}"


	curl -Lo ${PROJECT}.tar.gz \$GITHUB_URL

	tar xf ${PROJECT}.tar.gz ${PROJECT}
	install -Dm 755 ${PROJECT} -t /usr/local/bin
EOF

bash ./checkinstall_it.sh
