#!/bin/bash -e
# Sync ISO files from Julius
#
# © 2015, Multapplied Networks, Inc.
#

if [ "$(whoami)" != "bondingadmin" ] ; then
    sudo -u bondingadmin /usr/sbin/sync-base-isos
    exit $?
fi

# Read the JULIUS variable from settings, remove any quotes, trim off the
# https:// and remove any potentially trailing / in the server name
JULIUS=$(ba print_settings \
    | grep -v _explicit_settings \
    | grep JULIUS_LOCATION \
    | awk '{print $3};' \
    | sed s/\'//g \
    | sed s/\"//g \
    | cut -c 9- \
    | sed 's|\/||g' \
)
REPOSITORY_RELEASE=$(ba get repository_release)


# Get Bonding ISOs
#
BONDING_ISO_SOURCE="rsync://$JULIUS:/oem-iso/$REPOSITORY_RELEASE/"
BONDING_ISO_PATH="/var/lib/bondingadmin/base-isos/"

mkdir -p $BONDING_ISO_PATH
rsync -a $BONDING_ISO_SOURCE $BONDING_ISO_PATH


# Get Laywire ISOs
#
LAYWIRE_RSYNC_BASE="rsync://$JULIUS:/download/laywire"
LAYWIRE_RSYNC_ISO_RELEASE="$LAYWIRE_RSYNC_BASE/release/$REPOSITORY_RELEASE"
LAYWIRE_LOCAL_PATH="/var/lib/bondingadmin/laywire"
LAYWIRE_RELEASE_PATH="$LAYWIRE_LOCAL_PATH/release"
LAYWIRE_ISO_PATH="$LAYWIRE_LOCAL_PATH/iso"
mkdir -p $LAYWIRE_ISO_PATH

rsync $LAYWIRE_RSYNC_ISO_RELEASE $LAYWIRE_RELEASE_PATH
RELEASE_VERSIONS=$(cat <<EOF | python3 - $LAYWIRE_RELEASE_PATH
import json
import sys

for version in json.load(open(sys.argv[1]))["versions"]:
    print(version)
EOF
)

if [ -z "$RELEASE_VERSIONS" ] ; then
    echo "No Laywire releases available"
    exit 1
fi

for existing_version in $(ls -1 $LAYWIRE_ISO_PATH) ; do
    keep="false"
    for version in $RELEASE_VERSIONS ; do
        if [ "$version" = "$existing_version" ] ; then
            keep="true"
            break
        fi
    done

    if [ "$keep" = "false" ] ; then
        rm -rf $LAYWIRE_ISO_PATH/$existing_version/
    fi
done

for version in $RELEASE_VERSIONS; do
    mkdir -p $LAYWIRE_ISO_PATH/$version
    rsync -a $LAYWIRE_RSYNC_BASE/$version/iso/ $LAYWIRE_ISO_PATH/$version/
done
