#!/bin/bash

#
# Copyright 2012 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
# 
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

# Initial cut - no functions, JFDI.

if [ -z "$1" ]; then
    echo "No host supplied" >&2
    exit 1
fi
if [ -z "$2" ]; then
    echo "No image id supplied" >&2
    exit 1
fi
#ref image=481ddf40-8f9c-4175-a993-c11b070d6653
# NOT SAFE against /etc races.
commands="sudo su -
apt-get -y install python-pip qemu-utils
pip install python-glanceclient
rm /tmp/image.qcow2
http_proxy= /usr/local/bin/glance -v --os-username demo --os-password nomoresecrete --os-tenant-name demo --os-auth-url http://glance.tripleo.org:5000/v2.0 --os-image-url http://glance.tripleo.org:9292/ image-download $2 --file /tmp/image.qcow2
ls -lh /tmp/
modprobe nbd max_part=16
rmdir /tmp/newimage
mkdir -p /tmp/newimage
qemu-nbd -c /dev/nbd1 /tmp/image.qcow2
mount /dev/nbd1 /tmp/newimage
rm -rf /tmp/recover
mkdir -p /tmp/recover/ssh
cp -ta /tmp/recover /etc/mtab /etc/hosts
cp -a /etc/ssh/ssh_host_*key* /tmp/recover/ssh/
[ -e "/tmp/newimage/boot" ] && rsync -axHAXv /tmp/newimage/ / --exclude=/tmp --delete-after | tee -a /tmp/rsync.log
cp -at /etc /tmp/recover/*
# Rewrites e.g. /dev/nbd0 -> a FS UUID from the taken over system
# XXX: TODO: Relabel the taken over system rootfs label to match root=LABEL=cloudimg-rootfs
# XXX: TODO: make the built images use the label, not the device.
update-grub
grub-install /dev/vda
reboot -n
"
# Rewrites e.g. /dev/nbd0 -> a FS UUID from the taken over system
echo "$commands" | ssh ubuntu@$1
# TODO:
# permit either:
#   reboot -n
# or (staying online)
#   retrigger cloud-init
#   then free up the device....
#   apt-get install qemu-utils
#   sudo umount /tmp/newimage
#   sudo qemu-nbd -d /dev/nbd1
#
#ssh stack@host / ubuntu@host?
# for the bootstrap image:
# Add eth1 via modprobe dummy && dummy0 - edit localrc and /etc/network/interfaces
#sudo ifup dummy0
#tripleo-incubator/scripts/demo
#$profit

