#!/bin/bash

# set -x

snapshot_dir="$(dirname "$1")"

new_snapshot=$1

rm -f $snapshot_dir/latest
ln -sf $new_snapshot $snapshot_dir/latest

tar cf $new_snapshot.tar -C $snapshot_dir $(basename $new_snapshot)
ln -sf $new_snapshot.tar $snapshot_dir/latest.tar

base_snapshot_url=http://intertub.es/${1#/var/www/intertub.es/html/}
zsyncmake $new_snapshot.tar -z -u $base_snapshot_url.tar.gz -U $base_snapshot_url.tar  -o $new_snapshot.tar.zsync
ln -sf $new_snapshot.tar.zsync $snapshot_dir/latest.tar.zsync
ln -sf $new_snapshot.tar.gz $snapshot_dir/latest.tar.gz

#rzip $new_snapshot.tar
#ln -sf $new_snapshot.tar.rz $snapshot_dir/latest.tar.rz

#lrzip $new_snapshot.tar
#ln -sf $new_snapshot.tar.lrz $snapshot_dir/latest.tar.lrz

touch $new_snapshot/upload_has_completed

clean_old() {
  ls "$snapshot_dir" -r | fgrep -v latest | tail -n +21 | while read i; do
      rm -r $snapshot_dir/$i
  done
}

pigmap_dir=$HOME/pigmap
pigmap=$pigmap_dir/pigmap
pigmap_state_file="$HOME/state/pigmap_last_snapshot"
pigmap_last_snapshot=$(cat $pigmap_state_file)

update_pigmap() {
    updated_regions_file=$(mktemp)
    diff -qrN $pigmap_last_snapshot $new_snapshot | \
        fgrep /region/ | \
         perl -ne 'print $1,"\n" if /^Files .* and (.*) differ$/' > $updated_regions_file
    $pigmap -i $new_snapshot/world -o /var/www/intertub.es/html/minecraft/pigmap -r $updated_regions_file -h 1 -x -g $pigmap_dir -m $pigmap_dir > $new_snapshot/pigmap-log
    rm -f $updated_regions_file
    echo $new_snapshot > $pigmap_state_file
}

clean_old
# update_pigmap

