#!/bin/sh

set -e

old="$1"
new="$2"

svn_root=$(svn info | awk '/Working Copy Root Path/ { print $5 }')
alias lua_to_json="$svn_root/balancer/production/x/lua_to_json/bin/lua_to_json"

if [ -z "$old" -o -z "$new" ]; then
    echo "Usage: $0 old_tgz_rbtorrent new_tgz_rbtorrent" >&2
    echo "rbtorrent to a BALANCER_GENCFG_CONFIGS_L7_TGZ resource should do" >&2
    exit 1
fi

fresh_dir() {
    rm -rf "$1"
    mkdir -p "$1"
}

for c in "old!$old" "new!$new"; do
    result_dir="${c%!*}"
    rbtorrent="${c#*!}"
    fresh_dir tmp
    cd tmp
    sky get -u "$rbtorrent"
    tar xzf balancer_configs_l7.tgz
    cd generated/l7-balancer
    for f in *.cfg; do
        lua_to_json --pretty $f > $f.json && echo "$result_dir/$f.json" &
    done
    wait
    fresh_dir "../../../$result_dir"
    mv * "../../../$result_dir"
    cd ../../../
    rm -rf tmp
done

