#!/usr/bin/env bash

set -eu
if [[ $# -eq 0 ]] || [[ "$1" == "--help" ]]; then
  echo "Usage: $(basename $0) <path_to_ips_file_or_json>"
  echo "This script symbolicates the provided .ips file or .json panic report using the appropriate debug symbols from DigitalOcean"
  echo ""
  exit 1
fi

input_file=$1;

if [[ "$input_file" == *.json ]]; then
    version=$(cat $input_file | jq -r .panic.app_version)
    channel=$(cat $input_file | jq -r .panic.release_channel)
    target_triple=$(cat $input_file | jq -r .panic.target)

    which llvm-symbolizer rustfilt >/dev/null || (echo Need to install llvm-symbolizer and rustfilt && exit 1)

    echo $channel;

    mkdir -p target/dsyms/$channel

    if [[ "$version" == "remote-server-"* ]]; then
        version="${version#remote-server-}"
        dsym="$channel/remote_server-$version-$target_triple.dbg"
    else
        dsym="$channel/zed-$version-$target_triple.dbg"
    fi
    if [[ ! -f target/dsyms/$dsym ]]; then
        echo "Downloading $dsym..."
        curl -o target/dsyms/$dsym.gz "https://zed-debug-symbols.nyc3.digitaloceanspaces.com/$dsym.gz"
        gunzip  target/dsyms/$dsym.gz
    fi

    cat $input_file | jq -r .panic.backtrace[] | sed s'/.*+//' | llvm-symbolizer --no-demangle --obj=target/dsyms/$dsym | rustfilt

else # ips file

    version=$(cat $input_file | head -n 1 | jq -r .app_version)
    bundle_id=$(cat $input_file | head -n 1 | jq -r .bundleID)
    cpu_type=$(cat $input_file | tail -n+2 | jq -r .cpuType)

    which symbolicate >/dev/null || cargo install symbolicate

    arch="x86_64-apple-darwin"
    if [[ "$cpu_type" == *ARM-64* ]]; then
        arch="aarch64-apple-darwin"
    fi
    echo $bundle_id;

    channel="stable"
    if [[ "$bundle_id" == *Nightly* ]]; then
        channel="nightly"
    elif [[ "$bundle_id" == *Preview* ]]; then
        channel="preview"
    fi

    mkdir -p target/dsyms/$channel

    # NOTE: if you see "no such file --uuid", you need to update your symbolicate
    uuid=$(symbolicate $input_file --uuid || true)
    if [[ $? -ne 0 ]]; then
        echo "You need to update your symbolicate: cargo install symbolicate"
        exit 1
    fi
    dsym="$uuid.dwarf"
    if [[ ! -f target/dsyms/$dsym ]]; then
        echo "Downloading $dsym..."
        curl -f -o target/dsyms/$dsym.gz "https://zed-debug-symbols.nyc3.digitaloceanspaces.com/by-uuid/${uuid}.dwarf.gz" ||
            curl -f -o target/dsyms/$dsym.gz "https://zed-debug-symbols.nyc3.digitaloceanspaces.com/$channel/Zed-$version-$arch.dwarf.gz"
        gunzip  target/dsyms/$dsym.gz
    fi

    symbolicate $input_file target/dsyms/$dsym

fi
