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

cd /var/tmp || exit

USER=oven-sh
PROJECT=bun
ARCH=$(dpkg --print-architecture)

LATEST_URL="https://github.com/${USER}/${PROJECT}/releases/latest"
RELEASE=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | jq -r '.tag_name | sub("^bun-v"; "")')
GIT_TAG=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | jq -r .tag_name)

# Verify we got a valid release version
if [ -z "$RELEASE" ]; then
  echo "Error: Could not fetch release version from GitHub"
  exit 1
fi

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

mkdir -p /var/tmp/${PROJECT}-"${RELEASE}"
cd /var/tmp/${PROJECT}-"${RELEASE}" || exit

cat >./description-pak <<-EOF
	Bun is a JavaScript runtime, bundler, transpiler and package manager.
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

	# Use the full tag name as version (e.g., v1.2.23)
	VERSION="${RELEASE}"
	RELEASE="1"
	LICENSE=MIT

	BASE_TMP_DIR=~/tmptmp/checkinstall_tmp
	mkdir -p \${BASE_TMP_DIR}

	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=unzip \
		-D \
		bash ./install.sh
EOF

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

	DIR="\$HOME/.local/bun"
	BIN_DIR="\$DIR/bin"
	EXE="\$BIN_DIR/bun"

	# Create installation directory
	mkdir -p "\$BIN_DIR" || true

	# Download binary based on architecture
	case \$(uname -m) in
		x86_64) URL="https://github.com/${USER}/${PROJECT}/releases/download/${GIT_TAG}/bun-linux-x64.zip" ;;
		aarch64) URL="https://github.com/${USER}/${PROJECT}/releases/download/${GIT_TAG}/bun-linux-aarch64.zip" ;;
		*) echo "Unsupported architecture"; exit 1 ;;
	esac

	# Download and extract bun
	# curl -Lo bun.zip "\$URL"
	# unzip -q bun.zip -d "\$BIN_DIR"
	# rm bun.zip

	# Install binary
	# install -Dm 755 "\$BIN_DIR/bun-\$(uname -s)-\$(uname -m)/bun" "\$EXE"

	# Clean up
	# rm -rf "\$BIN_DIR/bun-\$(uname -s)-\$(uname -m)" "\$EXE.zip"

    npm install -g bun

	# Install shell completions
	if command -v bun >/dev/null; then
		IS_BUN_AUTO_UPDATE=true \$EXE completions &>/dev/null || :
	fi

	# Add to PATH
	case \$(basename "\$SHELL") in
		bash)
			echo "export BUN_INSTALL=\$DIR" | tee \$HOME/.bashrc.d/003_bun.sh  
			echo "export PATH=\$BIN_DIR:\$PATH" | tee -a \$HOME/.bashrc.d/003_bun.sh
			echo "source \$HOME/.bashrc.d/003_bun.sh"
			;;
		zsh)
			echo "export BUN_INSTALL=\$DIR" | tee \$HOME/.zshrc.d/003_bun.zsh
			echo "export PATH=\$BIN_DIR:\$PATH" | tee -a \$HOME/.zshrc.d/003_bun.zsh
			echo "exec \$SHELL"
			;;
	esac
EOF

sudo bash ./checkinstall_it.sh
