#!/bin/sh
#
# This file should archive the numerous independent build targets for
# the Broadway platform.  This includes but is not limited to
#   P2P, ECSHOP, ECDK, and WIISHOP

# $1 is generally 'hourly', but possibly 'nightly'
# $2 is generally the current date, but any type of unique identifier will do

# ecshop and ecdk not incoporated into this script yet; 
# they are built in GBA/sw/tools/ecdk and GBA/sw/tools/ecshop respectively
SDKS="p2p wiishop"

if [[ xx"$1" == xx"" || yy"$2" == yy"" ]]; then 
    echo "Usage: $0 build curdate";
    echo "";
    exit 1
else
    echo "Archiving $SDKS";
    echo "";
fi

build_type=$1
build_date=$2

function archive_p2p() {
    BUILD_ROOT=$HOME/bw/p2p_root;
    ARCHIVE_ROOT=$HOME/bw/p2p_archives/$build_type;
    
    mkdir -p $ARCHIVE_ROOT
    echo "Archive $BUILD_ROOT for p2p $build_type build for date $build_date"

    #
    # Create a tar archive of $ROOT
    #
    cd $BUILD_ROOT
    tar czf $ARCHIVE_ROOT/p2p_root_$build_date.tgz .

    #
    # Reset "latest" symlink to point to the new archive
    #
    cd $ARCHIVE_ROOT
    rm -f latest
    ln -s p2p_root_$build_date.tgz latest

    #
    # Expand the archive into a mountable tree
    #
    cd ..
    mv latest latest.prev
    mkdir latest
    cd latest
    tar xzf ../$build_type/latest
    echo "Expanded BW ROOT from $build_type build dated $build_date" > README
}

function archive_wiishop() {
    if [ -z "$BW_SRC_ROOT" ]; then
        echo "Please define BW_SRC_ROOT to the SW directory of your GBA tree";
        echo "  i.e.:  export BW_SRC_ROOT=$HOME/gba/sw";
        exit 1;
    fi

    WIISHOP_DIR=$BW_SRC_ROOT/bw/build/tests/wiishop
    WIISHOP_ARCHIVE=$HOME/bw/exports/wiishop
#    IPL_ROOT=$HOME/Nintendo_SDK/wiishop/ipl

    if [ ! -d "$WIISHOP_DIR" -o ! -e "$WIISHOP_DIR/*.wad" ]; then
        echo "Either $WIISHOP_DIR is non-existent or it lacks any wad file.";
        echo "  Please check that 'BW_SRC_ROOT' ($BW_SRC_ROOT) is set properly";
        exit 1;
    fi

    shop_list="shoppingDebug.wad shoppingRelease.wad shoppingFinal.wad"

    mkdir -p $WIISHOP_ARCHIVE;
    cd $WIISHOP_ARCHIVE;
    mkdir -p current;
    cd current;
    
    for wad in $shop_list; do
        cp -f $WIISHOP_DIR/$wad ./;
    done;

    echo "shopping wads, archived on $build_date" > README;

    tar czf ../wiishop_$build_date.tgz ./*.wad README;
    cd ../
    rm -rf latest/* current;
    mkdir -p latest;
    cd latest;
    tar xzf ../wiishop_$build_date.tgz
}

for target in $SDKS; do
    archive_$target;
done
