#!/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"

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

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

SPECS="$PACKAGE_WORKDIR/SPECS"

mkdir -p "$SPECS"

cp watchman/build/package/watchman.spec "$SPECS/watchman.spec"

rpmbuild \
    -bb \
    --define "dist .fc$FEDORA_VERSION" \
    --define "_rpmdir $PACKAGE_WORKDIR/RPMS" \
    --define "version $PACKAGE_VERSION" \
    --define "prefix $PREFIX/" \
    --define "image $BUILT" \
    "$SPECS/watchman.spec"

mkdir -p /_rpms
cp -a "$PACKAGE_WORKDIR"/RPMS/x86_64/*.rpm /_rpms

find /_rpms

for rpm in /_rpms/*.rpm; do
    echo "::set-output name=rpm_path::$rpm"
    echo "::set-output name=rpm_name::$(basename "$rpm")"
    break
done
