#!/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 '.[0].name | sub("^bun-v"; "")')
GIT_TAG=$(curl -L -s -H 'Accept: application/json' "${LATEST_URL}" | jq -r '.[0].name')

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
    A fast JavaScript runtime 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

    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

    # Install to /usr/local/bun
    DIR="/usr/local/bun"
    BIN_DIR="/usr/local/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 "\${DIR}"
    rm bun.zip

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

    # Clean up
    rm -rf "\${DIR}/bun-\$(uname -s)-\$(uname -m)" "bun.zip"

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

    # Add to PATH
    echo "export PATH=\"/usr/local/bin:\$PATH\"" >> /etc/profile.d/bun.sh
    chmod +x /etc/profile.d/bun.sh
EOF

bash ./checkinstall_it.sh
