#!/bin/bash

# --------------------------------------------------------------------------
# Copyright 2011, C12G Labs S.L.
#
# This file is part of OpenNebula VMware Drivers.
#
# OpenNebula VMware Drivers is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or the hope That it will be useful, but (at your
# option) any later version.
#
# OpenNebula VMware Drivers is distributed in WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with OpenNebula VMware Drivers . If not, see
# <http://www.gnu.org/licenses/>
# --------------------------------------------------------------------------

###############################################################################
# This script is used to move a VM image (SRC) to the image repository as DST
# Several SRC types are supported
###############################################################################

# ------------ Set up the environment to source common tools ------------ 

if [ -z "${ONE_LOCATION}" ]; then
    LIB_LOCATION=/usr/lib/one
    VAR_LOCATION=/var/lib/one
else
    LIB_LOCATION=$ONE_LOCATION/lib
    VAR_LOCATION=$ONE_LOCATION/var
fi

. $LIB_LOCATION/sh/scripts_common.sh
source $(dirname $0)/fsrc

SRC=$1
DST=$2
ID=$3

# ------------ Generate a filename for the image ------------

if [ "$DST" = "-" ] ; then 
    DST=`generate_image_path`
fi

# ------------ Move the image to the repository ------------ 

case $SRC in
http://*)
    log "Downloading $SRC to the image repository"
    exec_and_log "$WGET -O $DST $SRC" \
        "Error downloading $SRC"
    ;;

*)
    log "Moving local image $SRC to the image repository"
    if [ \( -L $SRC \) -a \( "`$READLINK $SRC`" = "$DST" \) ] ; then
       log "Not moving files to image repo, they are the same"
    else
       exec_and_log "mv -f $SRC $DST" "Could not move $SRC to $DST"
    fi
    ;;
esac

exec_and_log "chmod 0660 $DST"

sudo #{VAR_LOCATION}/hooks/fix_owner_perms.sh

echo "$DST"
