#!/bin/bash

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"
RPM_DIR=/opt/rpm.scraperwall.com/centos6


rm -rf $DESTDIR
install -d $DESTDIR/{usr/bin,etc/init.d,etc/default,etc/logrotate.d,usr/share/munchclient}
make

install -v -m 755 $BINARY $DESTDIR/usr/bin/
install -v -m 644 defaults/$DEFAULTS_FILE $DESTDIR/etc/default/
install -v -m 644 logrotate.d/munchclient $DESTDIR/etc/logrotate.d/
install -v -m 644 munchclient.toml $DESTDIR/etc/
install -v -m 644 munchclient.toml $DESTDIR/usr/share/munchclient/
install -v -m 644 ca-chain.cert.pem $DESTDIR/usr/share/munchclient/
install -v -m 644 defaults/$DEFAULTS_FILE $DESTDIR/usr/share/munchclient/$DEFAULTS_FILE.defaults



fpm -s dir -t $PKG_TYPE -C $DESTDIR --name $BINARY \
  --version $VERSION \
  --iteration $ITERATION \
  --description "$DESCR" \
  --config-files "etc/default/$BINARY" \
  --config-files "etc/$CONFIG_FILE" \
  --rpm-init "init.d/$BINARY" \
  --rpm-trigger-after-install "[]munchclient: ./after-install-trigger.sh" \
  --rpm-trigger-before-uninstall "[]munchclient: ./before-uninstall-trigger.sh" \
  -p rpms \
  -d go-daemon \
  --rpm-sign

ok=$?

rm -rf $DESTDIR

exit

rpm_file="munch-$VERSION-$ITERATION.x86_64.rpm"
if [ $ok -eq 0 -a -f "$rpm_file" ]; then
	rm -f "$RPM_DIR/munch-*.rpm"
  cp "$rpm_file" "$RPM_DIR"

	(cd "$RPM_DIR" && \
   createrepo -v . && \
   rsync -av --progress --delete . fender.spyz.org:/srv/http-vhosts/rpm.scraperwall.com/centos6/)
fi
