#!/bin/bash

set -x

DESTDIR=./dist
VERSION=$(git describe --tag | sed 's/^v//')
ITERATION=1
BINARY=munchclient
DEFAULTS_FILE="$BINARY"
CONFIG_FILE="$BINARY.toml"
SERVICE_FILE="$BINARY.service"
PKG_TYPE=rpm
DESCR="ScraperWall traffic collector"
OUTDIR=./rpms-centos7
RPM_DIR=$PWD/rpm.scraperwall.com/centos7
DOCKER_IMAGE=registry.scw.systems/centos7-build:latest



rm -rf $DESTDIR
install -d $DESTDIR/{usr/bin,etc/systemd/system,etc/default,etc/munchclient,usr/share/$BINARY}
make

install -v -m 755 $BINARY $DESTDIR/usr/bin/
install -v -m 644 defaults/$DEFAULTS_FILE $DESTDIR/etc/default/
install -v -m 644 defaults/$DEFAULTS_FILE $DESTDIR/usr/share/$BINARY/$DEFAULTS_FILE.defaults
install -v -m 644 $SERVICE_FILE $DESTDIR/etc/systemd/system
install -v -m 644 $BINARY.toml $DESTDIR/etc/$BINARY/
install -v -m 644 $BINARY.toml $DESTDIR/usr/share/$BINARY/
# install -v -m 644 ca-chain.cert.pem $DESTDIR/etc/$BINARY/



docker run --rm -i -t -v $PWD:/scw -v $PWD/rpmmacros:/root/.rpmmacros -w /scw $DOCKER_IMAGE \
  fpm -s dir -t $PKG_TYPE -C $DESTDIR --name $BINARY \
    --version $VERSION \
    --iteration $ITERATION \
    --description "$DESCR" \
    --config-files "etc/default/$BINARY" \
    --config-files "etc/$BINARY/$CONFIG_FILE" \
    --rpm-trigger-after-install "[]$BINARY: ./after-install-trigger-centos7.sh" \
    --rpm-trigger-before-uninstall "[]$BINARY: ./before-uninstall-trigger-centos7.sh" \
    -p $OUTDIR

rpm_file="$OUTDIR/$BINARY-$VERSION-$ITERATION.x86_64.rpm"

docker run --rm -i -t -v $PWD:/scw -v $PWD/rpmmacros:/root/.rpmmacros -w /scw $DOCKER_IMAGE \
  /usr/bin/rpm --define "_gpg_name <tobias@scraperwall.com>" --addsign $rpm_file

ok=$?

rm -rf $DESTDIR

if [ $ok -eq 0 -a -f "$rpm_file" ]; then
	# rm -f "$RPM_DIR/$BINARY-*.rpm"
  cp "$rpm_file" "$RPM_DIR"

	docker run --rm -i -t -v $RPM_DIR:/rpms -w /rpms $DOCKER_IMAGE \
    createrepo -v . 

  ok2=$?

  if [ $ok2 -eq 0 ]; then
   	(cd "$RPM_DIR" && \
     rsync -av --progress --delete . fender.spyz.org:/srv/http-vhosts/rpm.scraperwall.com/centos7/)
  fi
fi
