#!/bin/sh
# -*- mode: sh; fill-column: 75; tab-width: 8; coding: utf-8-unix -*-

# 19 Nov 00:48:20 ntpdate[24018]: step time server 132.163.97.3 offset +4125.279643 sec

prog=`basename $0 .bash`
PREFIX=/usr/local
ROLE=toxcore

[ -f /usr/local/etc/testforge/testforge.bash ] && \
   . /usr/local/etc/testforge/testforge.bash || exit 1


# python3.6 problems on gentoo with gevent not installing
# python3.7 -c 'import gevent'

PYVER=3
PYTHON_MINOR=3.11

PYTHON_EXE_MSYS=python$PYTHON_MINOR.sh
PYTHON_EXE=$PYTHON_EXE_MSYS

PKG=sdwdate
URL=github.com/Whonix/sdwdate
DIR=$PKG

cd $PREFIX/src || exit 2
WD=$PWD

cd $DIR || exit 3

site_packages=$PREFIX/$LIB/python$PYTHON_MINOR/site-packages

if ! [ -d $site_packages/$DIR/ ] ; then
    rsync -vax usr/lib/python3/dist-packages/$DIR/ $site_packages/$DIR/
    sed -e 's@/usr/lib@/usr/local/lib@' -i $site_packages/$DIR/*py
  fi
[ -d $site_packages/$DIR/ ] || exit 4

[ -d $PREFIX/etc/sdwdate.d ] || mkdir $PREFIX/etc/sdwdate.d
[ -f $PREFIX/etc/sdwdate.d/30_default.conf ] || \
    cp -p etc/sdwdate.d/30_default.conf  $PREFIX/etc/sdwdate.d/30_default.conf

if [ ! -f $PREFIX/bin/${PKG}_.py ] ; then
    cp -p usr/bin/${PKG} $PREFIX/bin/${PKG}_.py || exit 5
    patch -b -z .dst $PREFIX/bin/${PKG}_.py < $PREFIX/src/${PKG}_.py,diff
  fi

if ! [ -d /usr/local/lib/helper-scripts ] ; then
    rsync -vax ../helper-scripts/ $PREFIX/lib/helper-scripts/
  fi

# share/sdwdate/onion_tester
if ! [ -d /usr/local/share/sdwdate ] ; then
    rsync -vax usr/share/$DIR/ $PREFIX/share/$DIR/
  fi

if ! [ -d /usr/local/lib/sdwdate ] ; then
    rsync -vax usr/lib/$DIR/ $PREFIX/lib/$DIR/

    ## Compatibility with anon-ws-disable-stacked-tor.
    # addgroup debian-tor 2>/dev/null || true

    # adduser --home /run/sdwdate --no-create-home --quiet --system --group sdwdate || true

    ## Add sdwdate to group debian-tor so it can read
    ## /run/tor/control.authcookie which is required to check if Tor has
    ## already successfully established a circuit before fetching time.
    # addgroup sdwdate debian-tor
    cd /usr/local/lib/$DIR
    [ -x sclockadj ] || \
	gcc sclockadj.c -o sclockadj -ldl -D_GNU_SOURCE -Wdate-time -D_FORTIFY_SOURCE=2 -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wl,-z,relro -Wl,-z,now || exit 7
    cd $WD
fi

if grep -q /usr/lib  /usr/local/lib/sdwdate/* ; then
    sed -e 's@/usr/lib@/usr/local/lib@' -i /usr/local/lib/sdwdate/*
fi
cd $WD

if [ ! -e $PREFIX/bin/${ROLE}_${PKG}.bash ] ; then
    cat > $PREFIX/bin/${ROLE}_${PKG}.bash << EOF
#!/bin/sh
# -*- mode: sh; tab-width: 8; encoding: utf-8-unix -*-

if [ -x /usr/local/bin/proxy_ping_test.bash ] ; then
    sh /usr/local/bin/proxy_ping_test.bash wifi || exit 1
    sh /usr/local/bin/proxy_ping_test.bash 30 || exit 2
  fi
export PYTHONPATH=$site_packages
exec $PYTHON_EXE_MSYS $PREFIX/bin/${PKG}_.py "\$@"
EOF
	chmod 755 $PREFIX/bin/${ROLE}_${PKG}.bash
    fi

exit 0
