#!/usr/bin/env bash
# geoul-ftpsync -- a glue layer for using the Debian ftpsync script from Geoul
# 
# This script must be invoked from a Geoul package dir which must contain an
# ftpsync.conf.  A copy of archvsync must exist on the same directory to this
# script.
#
# Created: 2010-09-08
# 
# Written by Jaeho Shin <netj@sparcs.org>.
# (C) 2010, Geoul Project. (http://ftp.kaist.ac.kr/geoul)
set -eu

Source=$1; shift

Self=`readlink -f "${BASH_SOURCE[0]}"`
Base=`dirname "$Self"`
export BASEDIR="$Base"/archvsync

# prepare environment
hostpath=${Source#rsync://}
export RSYNC_HOST=${hostpath%%/*}
export RSYNC_PATH=${hostpath#$RSYNC_HOST/}
export TO=$PWD/data
export INFO_MAINTAINER="KAIST SPARCS GEOUL <geoul@sparcs.org>"

name=`basename "$PWD"`
suffix=${name#debian}
ARCHIVE=${suffix#-}
export ARCHIVE

# install configuration
conf="ftpsync$suffix.conf"
confpath="$BASEDIR/etc/$conf"
[ -e "$confpath" ] || ln -sfn "$PWD"/ftpsync.conf "$confpath"

# final check before take-off
[ -e ftpsync.conf ]
[ -d "$TO" ]

## prepare sync as in /mirror/lib/sync.sh
export triggered timepast failures
. /mirror/lib/pkg.sh
. /mirror/lib/sync-steps.sh
prepare-sync


## let Debian's ftpsync handle the actual sync
"$BASEDIR"/bin/ftpsync &
pid=$!

## and watch its log
# + set don't exit when tail dies
set +e

tail -F --quiet --pid=$pid >>$log 2>/dev/null \
    "$BASEDIR"/log/ftpsync$suffix.log \
    "$BASEDIR"/log/rsync-ftpsync$suffix.{log,error} \
    "$BASEDIR"/log/runmirrors$suffix.log \
    #

set -e

## finish sync as in /mirror/lib/sync.sh
# look for errors
#  from ftpsync
exitcode=`
sed <$log \
    -n '/ERROR:/ s/.*errorcode \([0-9]*\).*/\1/p' |
    tail -n 1
`
#  or from rsync
[ -n "$exitcode" ] || exitcode=`
sed <$log \
    -n '/rsync error:/ s/.*(code \([0-9]*\)).*/\1/p' |
    head -n 1
`
: ${exitcode:=0}
echo "+ exitcode=$exitcode" >>$log
finish-sync
