#!/bin/bash

# variables
GIT_REPO=https://gitea.arsenm.dev/Arsen6331/itd.git
VERSION=${VERSION:-latest}
BUILD=${BUILD:-1}

TAG=gwh
TMP=/tmp/$TAG
CWD=$(pwd)

PRGNAM=$(basename $CWD)
PKG=$TMP/pkg-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

ARCH=${ARCH:-$(uname -m)}

REPOSITORY=${REPOSITORY:-/home/installs/SlackBuilds/_repositories/$PRGNAM}
PREFIX=${PREFIX:-/usr}

# nettoyage préalable
rm -fr $PKG $TMP/$PRGNAM

mkdir -p $PKG

# mise en place
cd $TMP
[ ! -e $REPOSITORY ] && git clone ${GIT_REPO} $REPOSITORY
cd $REPOSITORY
git pull --all

cp -R $REPOSITORY $TMP/
cd $TMP/$PRGNAM
[ "x$VERSION" == "xlatest" ] && VERSION=$(git tag --sort=-taggerdate | head -n1)
[ "x$VERSION" == "x" ] && VERSION=trunk
[ "x$VERSION" == "xtrunk" ] && VERSION="git_r$(git rev-list --count HEAD)_$(git log -1 --format=%h)" || git checkout $VERSION

make

make install PREFIX=/usr DESTDIR=$PKG

go build ./cmd/itgui
cp itgui $PKG/usr/bin/

mkdir -p $PKG/etc/rc.d/
cat <<EOF > $PKG/etc/rc.d/rc.itd
#!/bin/bash
#
# Start/stop/restart $PRGNAM
#

DAEMON_USER=gwh
DAEMON_OPTIONS=""

start() {
  if [ -x /usr/bin/itd ]; then
    echo "Starting itd daemon: /usr/bin/itd "
    mkdir -p /tmp/itd/
    chmod 0777 /tmp/itd/
    sudo -u \$DAEMON_USER /usr/bin/itd \$DAEMON_OPTIONS 2> /dev/null &
  fi
}

stop() {
  killall itd 2> /dev/null
}

restart() {
  stop
  sleep 1
  start
}

case "\$1" in
'start')
  start
  ;;
'stop')
  stop
  ;;
'restart')
  restart
  ;;
*)
  echo "usage \$0 start|stop|restart"
esac

EOF
chmod +x $PKG/etc/rc.d/rc.itd

# mkdir -p $PKG/run/itd/
# chmod 0777 $PKG/run/itd/
# sed -i 's|/tmp/itd/socket|/run/itd/socket|' $PKG/itd.toml

# move doc/ to the appropriate location
mkdir -p $PKG$PREFIX/doc/$PRGNAM
cp LICENSE README.md $PKG$PREFIX/doc/$PRGNAM

# correction
cd $PKG
chown -R root:root *

[ -d $PKG$PREFIX/man ] && find $PKG$PREFIX/man -type f -not -name \*.gz -exec gzip -9 {} \;

# embaumement
mkdir -p $PKG/install

cat <<EOF > $PKG/install/slack-desc
# HOW TO EDIT THIS FILE:
# The "handy ruler" below makes it easier to edit a package description.  Line
# up the first '|' above the ':' following the base package name, and the '|'
# on the right side marks the last column you can put a character in.  You must
# make exactly 11 lines for the formatting to be correct.  It's also
# customary to leave one space after the ':'.

       |-----handy-ruler------------------------------------------------------|
$PRGNAM: $PRGNAM (daemon to interact with InfiniTime.)
$PRGNAM:
$PRGNAM: itd is a daemon that uses my infinitime library to interact with the
$PRGNAM: PineTime smartwatch running InfiniTime.
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM:
$PRGNAM: ${GIT_REPO}
EOF

# empaquetage
rm -f $PKG/{,usr/}lib$(uname -m | grep -o 64)/*.la
/sbin/makepkg --linkadd y --chown n --prepend $OUTPUT/$PRGNAM-$VERSION-$ARCH-$BUILD$TAG.txz