#!/usr/bin/env bash
# echo "Skipping install. does source only release and the auth fails silently."
# exit 0

# set -x

cd /var/tmp || exit

USER=Exafunction
PROJECT=codeium
SUBPROJECT=termium
LATEST_URL="https://api.github.com/repos/${USER}/${PROJECT}/releases"

RELEASE_TAG=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | jq -r '.[0].tag_name')

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

if [ $? -ne 0 ]; then
	echo "Failed to fetch release tag"
	exit 1
fi
GIT_RELEASE=${RELEASE_TAG##*-}
RELEASE=${GIT_RELEASE#v}

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

cat >./description-pak <<-EOF
	Termium autocomplete - Codeium in the Terminal
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}/${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=${SUBPROJECT} \
		--pkgversion=\${VERSION} \
		--pkgrelease=\${RELEASE} \
		--pkgarch=amd64 \
		--pkggroup=development \
		--pkglicense=MIT \
		--pkgsource=${LATEST_URL} \
		--maintainer=cyteen@ring-zero.co.uk \
		--requires=bash,zsh \
		-D \
		bash ./install.sh
EOF

cat <<-'EOF' | tee ./install.sh >/dev/null
	    #!/bin/sh

	    err() {
	        echo "$1" >&2
	        exit 1
	    }

	    # Loosely adapted from rustup-init.sh (see sh.rustup.rs)
	    get_architecture() {
	        local _ostype _cputype _arch
	        _ostype="$(uname -s)"
	        _cputype="$(uname -m)"

	        if [ "$_ostype" = Darwin ] && [ "$_cputype" = i386 ]; then
	            # Darwin `uname -m` lies
	            if sysctl hw.optional.x86_64 | grep -q ': 1'; then
	                _cputype=x86_64
	            fi
	        fi

	        case "$_ostype" in
	            Linux) _ostype=unknown-linux-gnu;;
	            Darwin) _ostype=apple-darwin;;
	            MINGW* | MSYS* | CYGWIN* | Windows_NT) _ostype=pc-windows-gnu;;
	            *) err "unrecognized OS type: $_ostype";;
	        esac

	        case "$_cputype" in
	            i386 | i486 | i686 | i786 | x86) _cputype=i686;;
	            xscale | arm | armv6l | armv7l | armv8l) _cputype=arm;;
	            aarch64 | arm64) _cputype=aarch64;;
	            x86_64 | x86-64 | x64 | amd64) _cputype=x86_64;;
	            *) err "unknown CPU type: $_cputype";;

	        esac

	        _arch="${_cputype}-${_ostype}"

	        RETVAL="$_arch"
	    }

	    echo_bold() {
	      echo -e "\033[1m$1\033[0m"
	    }

	    downloader() {
	        local _arch="$1"
	        local _bin_name="termium"
	        local _base_url="https://github.com/Exafunction/codeium/releases"
EOF

cat <<-EOF | tee -a ./install.sh >/dev/null
	        local _version='${RELEASE}'
EOF

cat <<-'EOF' | tee -a ./install.sh >/dev/null
	        local _url="${_base_url}/download/${_bin_name}-v${_version}/${_bin_name}_${_arch}"

	        echo "Downloading $_bin_name from $_url"
	        
	        # Download the file directly to /usr/local/bin
	        curl -fLo "/var/tmp/codeium-$_bin_name-v${_version}/$_bin_name" "$_url" || exit 1
	        mv "/var/tmp/codeium-$_bin_name-v${_version}/$_bin_name" "/usr/local/bin/$_bin_name"

	        # Make the downloaded file executable
	        chmod +x "/usr/local/bin/$_bin_name"
	    }

	    main() {
	        get_architecture || return 1
	        local _arch="$RETVAL"

	        case "$_arch" in
	            x86_64-unknown-linux-gnu | aarch64-unknown-linux-gnu | x86_64-apple-darwin | aarch64-apple-darwin)
	                # supported platform
	                downloader $_arch || return 1;;
	            *)
	                err "Unsupported platform: $_arch";;
	        esac

	        echo "Download complete. To finish setup run the following commands:"
	        # Echo the command in bold text.
	        echo_bold "  termium auth"
	        echo_bold "  termium shell-hook install"
	        echo ""
	        echo "You can also run the following to learn more about termium:"
	        echo_bold "  termium --help"
	    }

	    main || exit 1
EOF

bash ./checkinstall_it.sh

# Create a symlink in the user's local bin directory
_termium_dir="$HOME/.codeium/bin/termium"
mkdir -p "$_termium_dir/${RELEASE}"
ln -sf "/usr/local/bin/${SUBPROJECT}" "$_termium_dir/${RELEASE}/${SUBPROJECT}"

mkdir -p "$_termium_dir/latest
ln -sf $_termium_dir/${RELEASE}/${SUBPROJECT}" "$_termium_dir/latest/${SUBPROJECT}"

# undo symlinks
# rm -rf ~/.codeium/bin/termium/
