#!/usr/bin/env bash

# Usage:       ./build_static_rsync
#                or
#              bash build_static_rsync
# Description: Download newest stable rsync release and
#                compiles a static binary
# Author:      Patrick Neumann (patrick@neumannsland.de)
# Platform:    Debian or Raspbian GNU/Linux (tested: 9.5)
# Version:     1.0
# Date:        06.07.2018
# License:     GPL3
# Warranty:    This program is distributed WITHOUT ANY WARRANTY

# autodetect arch:
ARCH="$( /bin/uname --machine )"

# autodetect release or do it manualy:
RELEASE="$( /usr/bin/curl -s https://rsync.samba.org/ \
            | /bin/grep -E "Rsync version [[:digit:]]\.[[:digit:]]{1,2}\.[[:digit:]]{1,2} released" \
            | /usr/bin/head -n 1 \
            | /bin/grep -o -E "[[:digit:]]\.[[:digit:]]{1,2}\.[[:digit:]]{1,2}" )"
#VERSION="3.1.3"
/usr/bin/test -n "${RELEASE}" || ( echo "Release detection failed - please edit script manually" ; exit 1 )

# dependencies (static libs):
if [ ! -f /usr/share/build-essential/list ] ; then /usr/bin/sudo /usr/bin/apt install build-essential --assume-yes ; fi
if [ ! -f /usr/lib/*-linux-gnu*/libc.a ] ; then /usr/bin/sudo /usr/bin/apt install libc6-dev --assume-yes ; fi
if [ ! -f /usr/lib/*-linux-gnu*/libpopt.a ] ; then /usr/bin/sudo /usr/bin/apt install libpopt-dev --assume-yes ; fi
if [ ! -f /usr/bin/yodl2man ] ; then /usr/bin/sudo /usr/bin/apt install yodl --assume-yes ; fi

# downloading...
/usr/bin/wget https://download.samba.org/pub/rsync/rsync-${RELEASE}.tar.gz

# extracting...
/bin/tar xzf rsync-${RELEASE}.tar.gz 

# compiling and stripping...
cd rsync-${RELEASE}/
./configure
/usr/bin/make CFLAGS="-I./popt -I./zlib -static" EXEEXT="-${ARCH}-${RELEASE}"
/usr/bin/strip rsync-${ARCH}-${RELEASE}

# final instructions:
echo
echo "Ready to copy:"
echo
echo "  cp $PWD/rsync-${ARCH}-${RELEASE} /media/POLICE/"
echo

exit 0