#!/bin/bash -e
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

cd "$(dirname "$0")"

cd /__w/watchman/watchman

cd "$(git rev-parse --show-toplevel)"

# Why /usr/local? This .deb does not hold to any rigorous packaging
# standards (e.g. Debian), and is intended to replace existing ad hoc
# Watchman installations.
#
# Until we have a reason otherwise, let's remain compatible with
# legacy installation paths.
PREFIX="/usr/local"

# Generated by the prior invocation of ./autogen.sh
BUILT="/__w/watchman/watchman/built"

find "$BUILT"

set -x

# This is an implicit assertion that the `lib` directory is empty.
# We statically link dependencies for packaging purposes.
rmdir "$BUILT/lib"

# TODO: make a debuginfo package
strip "$BUILT/bin/watchman"
strip "$BUILT/bin/watchmanctl"

PACKAGE_VERSION=$("$BUILT/bin/watchman" --version)

PACKAGE_WORKDIR=$(mktemp -d)
trap 'rm -rf -- "$PACKAGE_WORKDIR"' EXIT

mkdir -p "$PACKAGE_WORKDIR$PREFIX"
cp -ar "$BUILT/bin" "$PACKAGE_WORKDIR$PREFIX/bin"

cp -ar /__w/watchman/watchman/watchman/build/package/watchman-deb/DEBIAN "$PACKAGE_WORKDIR"

python3 /__w/watchman/watchman/watchman/build/package/substcontrol.py "$PACKAGE_WORKDIR/DEBIAN/control" "$PACKAGE_VERSION" "$UBUNTU_VERSION"

mkdir -p /_debs

DEB_OUTPUT="/_debs/watchman.deb"

dpkg-deb -b "$PACKAGE_WORKDIR" "$DEB_OUTPUT"
