#!/bin/bash
set -eu

# Script run by Jenkins (Automatic Cloud Builds of Castle Game Engine projects) on
# https://michalis.ii.uni.wroc.pl/jenkins/ to update PasDoc snapshots
# visible on http://michalis.ii.uni.wroc.pl/pasdoc-snapshots/ .
# Parts of this script are really specific to the Jenkins
# and michalis.ii.uni.wroc.pl server configuration.

. /usr/local/fpclazarus/bin/setup.sh default

OUTPUT_BASE_PATH=/var/www/pasdoc-snapshots/
OUTPUT_PATH="${OUTPUT_BASE_PATH}"`date +%F`/
mkdir -p "$OUTPUT_PATH"

PASDOC_VERSION=`make version`

# build snapshots
# make dist-src # useless, checks out the stable version
make dist-linux-x86
make dist-win32 FPC_DEFAULT='fpc -Twin32' LAZBUILD_OPTIONS='--operating-system=win32 --widgetset=win32'

echo '---- Snapshots build OK.'

# Move archives to output dir
mv -f pasdoc-"$PASDOC_VERSION"-linux-x86.tar.gz \
      pasdoc-"$PASDOC_VERSION"-win32.zip \
      "$OUTPUT_PATH"

# Create "latest" link, comfortable for users.
rm -f "${OUTPUT_BASE_PATH}"latest
ln -s `date +%F` "${OUTPUT_BASE_PATH}"latest

# Clean old snapshots, to conserve disk space.
# Keep only snapshots from last couple of days.
pushd .
cd "${OUTPUT_BASE_PATH}"
set +e
find . -mindepth 1 -maxdepth 1 \
  -type d -and \
  -name '????-??-??' -and \
  '(' -not -iname `date +%F` ')' -and \
  '(' -not -iname `date --date='-1 day' +%F` ')' -and \
  '(' -not -iname `date --date='-2 day' +%F` ')' -and \
  '(' -not -iname `date --date='-3 day' +%F` ')' -and \
  '(' -not -iname `date --date='-4 day' +%F` ')' -and \
  '(' -not -iname `date --date='-5 day' +%F` ')' -and \
  '(' -not -iname `date --date='-6 day' +%F` ')' -and \
  '(' -not -iname `date --date='-7 day' +%F` ')' -and \
  -exec rm -Rf '{}' ';'
set -e
popd

echo '---------------------------------------------------------------'
echo 'Setting snapshots permissions:'

chmod a+rX "${OUTPUT_BASE_PATH}"

echo '---------------------------------------------------------------'
echo 'Building for current platform, to be used by dependent Jenkins jobs'

make clean default build-tools

echo '---- The end, everything finished Ok.'
