#!/bin/sh

#
# Copyright (C) 2007-2009 Canonical, Ltd.
# Author: Jamie Strandboge <jamie@canonical.com>
# License: GPLv3
#

ustconf="$HOME/.uqt-vm-tools.conf"
if [ -s "$ustconf" ]; then
    . "$ustconf"
else
    echo "Could not find '$ustconf'"
    exit 1
fi

. $UQT_VM_TOOLS/libvm.sh
abort_if_root

help() {
    echo "Usage: vm-repo -e|-d -r release <machine>"
    echo "Usage: vm-repo -e|-d -p PREFIX [-a arch]"
    echo " -d             disable the local repo"
    echo " -e             enable the local repo"
    echo " -p PREFIX      use PREFIX when constructing hostname"
    echo " -a ARCH        use ARCH when constructing hostname"
    echo " -r RELEASE     add RELEASE repo (ignored with '-p')"
    echo ""
    echo "Eg:"
    echo "$ vm-repo -e -p sec"
    echo ""
    echo "This will add the following to /etc/apt/sources.list.d/ust-vm-repo.list:"
    echo "deb $vm_repo_url <release>/"
    echo "deb-src $vm_repo_url <release>/"
    echo ""
    echo "where <release> is one of '$vm_release_list'"
}

if [ -z "$1" ] || [ "$1" = "help" ]; then
    help
    exit 1
fi

update_machine() {
    host=`vm_ping $1`
    if [ -z "$host" ]; then
        return
    fi
    sources="/etc/apt/sources.list.d/ust-vm-repo.list"
    if [ "$3" = "yes" ]; then
        echo "Enabling $vm_repo_url for $1"
        ssh -t root@${host} "bash -c 'echo -e \"deb $vm_repo_url $2/\ndeb-src $vm_repo_url $2/\" > $sources'"
    else
        echo "Disabling $vm_repo_url for $1"
        ssh -t root@${host} rm -f $sources
    fi
    ssh -t root@${host} apt-get update
}

arch=
prefix=
enable=
release=
while getopts "dea:p:r:" opt
do
    case "$opt" in
        a) arch="$OPTARG";;
        d) enable="no";;
        e) enable="yes";;
        p) prefix="$OPTARG";;
        r) release="$OPTARG";;
        ?) help
           exit 1
           ;;
    esac
done
shift $(($OPTIND - 1))

if [ -z "$prefix" ]; then
    if [ -z "$1" ]; then
        help
        exit 1
    fi

    for i in "$@" ; do
        update_machine "$i" "$release" $enable
    done
else
    archs="$vm_archs"
    if [ ! -z "$arch" ]; then
        archs="$arch"
    fi

    for a in $archs ; do
        for m in `vm_get_machines_by_prefix "${prefix}" "$a"` ; do
            release=`vm_get_release_by_machine_name "$m"`
            if [ -z "$release" ]; then
                echo "Skipping '$m' (couldn't determine release)"
                continue
            fi
            update_machine "$m" $release $enable
        done
    done
fi

