#!/usr/bin/env bash

set -euxo pipefail

help_info() {
  echo "
Usage: ${0##*/} [options]
Build zed.snap from the tarball produced by script/bundle-linux
(target/release/zed-linux-<arch>.tar.gz), for the channel in
crates/zed/RELEASE_CHANNEL.

Options:
  -h, --help  Display this help and exit.
  --publish   Upload the snap to the Snap Store channel matching the release
              channel.
  "
}

publish=false

while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--help)
            help_info
            exit 0
            ;;
        --publish)
            publish=true
            shift
            ;;
        *)
            help_info
            exit 1
            ;;
    esac
done

channel=$(<crates/zed/RELEASE_CHANNEL)
version="$(script/get-crate-version zed)"

arch="$(uname -m)"
export ARCH_TRIPLET="$arch-linux-gnu"
export ZED_TARBALL="target/release/zed-linux-$arch.tar.gz"
if [[ ! -f "$ZED_TARBALL" ]]; then
  echo "Missing $ZED_TARBALL, run script/bundle-linux first"
  exit 1
fi

export SNAP_GRADE="stable"
store_channel=""
case "$channel" in
  stable)
    export APP_ID="dev.zed.Zed"
    export RELEASE_VERSION="$version"
    store_channel="latest/stable"
    ;;
  preview)
    export APP_ID="dev.zed.Zed-Preview"
    export RELEASE_VERSION="$version-pre"
    store_channel="latest/beta"
    ;;
  nightly)
    export APP_ID="dev.zed.Zed-Nightly"
    # Snap versions are limited to 32 characters, so this uses a short sha
    # rather than the full one in the version script/upload-nightly publishes.
    export RELEASE_VERSION="$version+nightly.$(git rev-parse --short=7 HEAD)"
    # The Snap Store only accepts grade `devel` on the edge and beta channels.
    export SNAP_GRADE="devel"
    store_channel="latest/edge"
    ;;
  dev)
    export APP_ID="dev.zed.Zed-Dev"
    export RELEASE_VERSION="$version+dev.$(git rev-parse --short=7 HEAD)"
    export SNAP_GRADE="devel"
    ;;
  *)
    echo "Unknown release channel: $channel"
    exit 1
    ;;
esac

if [[ "$publish" == "true" && -z "$store_channel" ]]; then
  echo "The $channel channel is not published to the Snap Store"
  exit 1
fi

mkdir -p snap

# Only these variables are substituted, so that references the snap resolves at
# runtime (such as $SNAP) survive.
# shellcheck disable=SC2016
envsubst '$RELEASE_VERSION $SNAP_GRADE $ZED_TARBALL $APP_ID $ARCH_TRIPLET' < crates/zed/resources/snap/snapcraft.yaml.in > snap/snapcraft.yaml

# Clean seems to be needed to actually check that the snapcraft.yaml
# works.  For example, when a `stage-package` is removed, it will
# still remain on rebuild.
snapcraft clean

snapcraft pack --output zed.snap

if [[ "$publish" == "true" ]]; then
  snapcraft upload --release="$store_channel" zed.snap
fi
