#!/usr/bin/env bash

set -euxo pipefail
source script/lib/blob-store.sh

# Function for displaying help info
help_info() {
  echo "
Usage: ${0##*/} [options]
Build a release .tar.gz for Linux.

Options:
  -h, --help        Display this help and exit.
  --flatpak         Set ZED_BUNDLE_TYPE=flatpak so that this can be included in system info
  --require-sentry  Require Sentry credentials, CLI, and successful symbol upload (official releases).
  --skip-sentry     Skip symbol upload for local packaging; incompatible with --require-sentry.
  "
}

require_sentry=false
skip_sentry=false

# Parse all arguments manually
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            help_info
            exit 0
            ;;
        --flatpak)
            export ZED_BUNDLE_TYPE=flatpak
            shift
            ;;
        --require-sentry)
            require_sentry=true
            shift
            ;;
        --skip-sentry)
            skip_sentry=true
            shift
            ;;
        --)
            shift
            break
            ;;
        -*)
            echo "Unknown option: $1" >&2
            help_info
            exit 1
            ;;
        *)
            echo "Error: Unexpected argument: $1" >&2
            help_info
            exit 1
            ;;
    esac
done

if [[ -n "${RUSTFLAGS+x}" || -n "${CARGO_ENCODED_RUSTFLAGS+x}" ]]; then
    echo "Unset RUSTFLAGS and CARGO_ENCODED_RUSTFLAGS; put extra flags in target rustflags in .cargo/config.toml so bundle flags are preserved." >&2
    exit 1
fi

if "$require_sentry" && "$skip_sentry"; then
    echo "--require-sentry and --skip-sentry cannot be used together." >&2
    exit 1
fi

if "$skip_sentry"; then
    echo "Skipping Sentry upload for local packaging."
elif ! command -v sentry-cli >/dev/null 2>&1; then
    if "$require_sentry"; then
        echo "Official Linux releases require sentry-cli for symbol upload." >&2
        exit 1
    fi
    echo "sentry-cli not found. skipping sentry upload."
    echo "install with: 'curl -sL https://sentry.io/get-cli | bash'"
    skip_sentry=true
elif [[ -z "${SENTRY_AUTH_TOKEN:+set}" ]]; then
    if "$require_sentry"; then
        echo "Official Linux releases require SENTRY_AUTH_TOKEN for symbol upload." >&2
        exit 1
    fi
    echo "missing SENTRY_AUTH_TOKEN. skipping sentry upload."
    skip_sentry=true
fi

export ZED_BUNDLE=true

channel=$(<crates/zed/RELEASE_CHANNEL)
target_dir="${CARGO_TARGET_DIR:-target}"

version="$(script/get-crate-version zed)"
# Set RELEASE_VERSION so it's compiled into GPUI and it knows about the version.
export RELEASE_VERSION="${version}"

commit=$(git rev-parse HEAD | cut -c 1-7)

version_info=$(rustc --version --verbose)
host_line=$(echo "$version_info" | grep host)
target_triple=${host_line#*: }
musl_triple=${target_triple%-gnu}-musl
remote_server_triple=${REMOTE_SERVER_TARGET:-"${musl_triple}"}
rustup_installed=false
if command -v rustup >/dev/null 2>&1; then
    rustup_installed=true
fi

# Generate the licenses first, so they can be baked into the binaries
script/generate-licenses

if "$rustup_installed"; then
    rustup target add "$remote_server_triple"
fi

export CC=${CC:-$(which clang)}
lld=${LLD:-$("$CC" -print-prog-name=ld.lld)}
if [[ "$lld" != /* || ! -x "$lld" ]]; then
    echo "Bundling requires an absolute executable linker path; set LLD (e.g. LLD=/usr/bin/ld.lld-18)." >&2
    exit 1
fi
lld_version=$("$lld" --version)
if [[ ! "$lld_version" =~ LLD\ ([0-9]+)\. ]] || (( BASH_REMATCH[1] < 12 )); then
    echo "Bundling requires LLD 12 or newer for safe ICF; set LLD to a supported linker (e.g. LLD=/usr/bin/ld.lld-18)." >&2
    exit 1
fi

# Build binary in release mode
cargo --config .cargo/bundle-config.toml rustc --release --target "${target_triple}" --package zed --bin zed -- -C linker="$CC" -C llvm-args=-addrsig -C link-arg=-fuse-ld=lld -C link-arg=--ld-path="$lld" -C link-arg=-Wl,--icf=safe
cargo --config .cargo/bundle-config.toml build --release --target "${target_triple}" --package cli
# Build remote_server in separate invocation to prevent feature unification from other crates
# from influencing dynamic libraries required by it.
if [[ "$remote_server_triple" == "$musl_triple" ]]; then
    musl_cc_var="CC_$(echo "$remote_server_triple" | tr '-' '_')"
    export "$musl_cc_var"=musl-gcc
fi
cargo --config .cargo/bundle-config.toml build --release --target "${remote_server_triple}" --package remote_server

if ! "$skip_sentry"; then
    echo "Uploading zed debug symbols to sentry..."
    # Sentry needs the full ELF for .eh_frame unwinding, not just the debug
    # companion. See https://github.com/getsentry/symbolic/issues/783.
    for attempt in 1 2 3; do
        echo "Attempting sentry upload (attempt $attempt/3)..."
        if sentry-cli debug-files upload --include-sources --wait -p zed -o zed-dev \
            "${target_dir}/${target_triple}"/release/zed \
            "${target_dir}/${remote_server_triple}"/release/remote_server; then
            echo "Sentry upload successful on attempt $attempt"
            break
        fi
        echo "Sentry upload failed on attempt $attempt" >&2
        if [ "$attempt" -eq 3 ]; then
            echo "All sentry upload attempts failed; refusing to package binaries without uploaded symbols." >&2
            exit 1
        fi
    done
fi

# Split debug symbols into local .dbg files, then strip debug info and local
# symbols from the shipped binaries. Sentry receives the full unstripped
# binaries above; the .dbg files keep symbols recoverable when that upload
# is skipped.
# We use llvm-objcopy because GNU objcopy on older distros (e.g. Ubuntu 20.04)
# doesn't understand CREL sections produced by newer LLVM.
llvm-objcopy --only-keep-debug "${target_dir}/${target_triple}/release/zed" "${target_dir}/${target_triple}/release/zed.dbg"
llvm-objcopy --only-keep-debug "${target_dir}/${remote_server_triple}/release/remote_server" "${target_dir}/${remote_server_triple}/release/remote_server.dbg"

# Ensure that remote_server does not depend on libssl nor libcrypto, as we got rid of these deps.
if ldd "${target_dir}/${remote_server_triple}/release/remote_server" | grep -q 'libcrypto\|libssl'; then
    if [[ "$remote_server_triple" == *-musl ]]; then
        echo "Error: remote_server still depends on libssl or libcrypto" && exit 1
    else
        echo "Info: Using non-musl remote-server build."
    fi
fi

suffix=""
if [ "$channel" != "stable" ]; then
  suffix="-$channel"
fi

# Move everything that should end up in the final package
# into a temp directory.
temp_dir=$(mktemp -d)
trap 'rm -rf "$temp_dir"' EXIT
zed_dir="${temp_dir}/zed$suffix.app"

# Cargo may reuse its outputs on the next invocation. Strip packaging copies
# so reruns still upload full ELFs and extract complete debug companions.
mkdir -p "${zed_dir}/bin" "${zed_dir}/libexec"
llvm-objcopy --strip-unneeded "${target_dir}/${target_triple}/release/zed" "${zed_dir}/libexec/zed-editor"
llvm-objcopy --strip-debug --discard-all "${target_dir}/${target_triple}/release/cli" "${zed_dir}/bin/zed"
llvm-objcopy --strip-debug --discard-all "${target_dir}/${remote_server_triple}/release/remote_server" "${temp_dir}/remote_server"

# Libs
# Bundle libstdc++ so older supported systems can run binaries built with our
# toolchain even when their system libstdc++.so.6 lacks required GLIBCXX symbols.
#
# Never bundle the GLib family or its private dependencies: host libraries that
# get dlopen'd are built against the system GLib, and resolving them against an
# older bundled copy fails with missing symbols.
find_libs() {
    ldd ${target_dir}/${target_triple}/release/zed |\
        cut -d' ' -f3 |\
        grep -v '\<\(libc.so\|libgcc_s.so\|libm.so\|libpthread.so\|libdl.so\|libasound.so\)' |\
        grep -v '\<\(libglib-2.0.so\|libgobject-2.0.so\|libgio-2.0.so\|libgmodule-2.0.so\|libpcre.so\|libpcre2-8.so\|libmount.so\|libblkid.so\|libselinux.so\|libffi.so\|libresolv.so\|libz.so\)'
}

mkdir -p "${zed_dir}/lib"
rm -rf "${zed_dir}/lib/*"
cp $(find_libs) "${zed_dir}/lib"

# Icons
mkdir -p "${zed_dir}/share/icons/hicolor/512x512/apps"
cp "crates/zed/resources/app-icon$suffix.png" "${zed_dir}/share/icons/hicolor/512x512/apps/zed.png"
mkdir -p "${zed_dir}/share/icons/hicolor/1024x1024/apps"
cp "crates/zed/resources/app-icon$suffix@2x.png" "${zed_dir}/share/icons/hicolor/1024x1024/apps/zed.png"

# .desktop
export DO_STARTUP_NOTIFY="true"
export APP_CLI="zed"
export APP_ICON="zed"
export APP_ARGS="%U"
if [[ "$channel" == "preview" ]]; then
  export APP_NAME="Zed Preview"
  APP_ID="dev.zed.Zed-Preview"
elif [[ "$channel" == "nightly" ]]; then
  export APP_NAME="Zed Nightly"
  APP_ID="dev.zed.Zed-Nightly"
elif [[ "$channel" == "dev" ]]; then
  export APP_NAME="Zed Devel"
  APP_ID="dev.zed.Zed-Dev"
else
  export APP_NAME="Zed"
  APP_ID="dev.zed.Zed"
fi

mkdir -p "${zed_dir}/share/applications"
envsubst < "crates/zed/resources/zed.desktop.in" > "${zed_dir}/share/applications/$APP_ID.desktop"
chmod +x "${zed_dir}/share/applications/$APP_ID.desktop"

# Copy generated licenses so they'll end up in archive too
cp "assets/licenses.md" "${zed_dir}/licenses.md"

# Create archive out of everything that's in the temp directory
arch=$(uname -m)
archive="zed-linux-${arch}.tar.gz"

rm -rf "${archive}"
remove_match="zed(-[a-zA-Z0-9]+)?-linux-$(uname -m)\.tar\.gz"
ls "${target_dir}/release" | grep -E ${remove_match} | xargs -d "\n" -I {} rm -f "${target_dir}/release/{}" || true
tar -czvf "${target_dir}/release/$archive" -C ${temp_dir} "zed$suffix.app"

gzip -f --stdout --best "${temp_dir}/remote_server" > "${target_dir}/zed-remote-server-linux-${arch}.gz"
