#!/bin/sh

set -e

# Make sure we're not working on the root directory
if [ -z "$TARGET" -o "$TARGET" = "/" ]; then
    echo "Invalid target directory '$TARGET', aborting." 1>&2
    exit 1
fi

if [ "$(mountpoint -d /)" = "$(mountpoint -d "$TARGET")" ]; then
    echo "The target directory seems to be the root dir, aborting."  1>&2
    exit 1
fi

# Copy the fixes from /etc/ganeti/instance-p2v-target/fixes to the instance:
mkdir -p "$TARGET/usr/lib/ganeti"
cp -r "/etc/ganeti/instance-p2v-target/fixes" "$TARGET/usr/lib/ganeti"

# Copy the public key from /etc/ganeti/instance-p2v-target/id_dsa.pub to the instance:
if [ ! -f "/etc/ganeti/instance-p2v-target/id_dsa.pub" ]; then
    echo "No public key found, you will not be able to log into the instance."
    echo "Please generate a dsa keypair and place the public key in"
    echo "/etc/ganeti/instance-p2v-target/id_dsa.pub"
    exit 1
fi

mkdir -p "$TARGET/root/.ssh"
cp "/etc/ganeti/instance-p2v-target/id_dsa.pub" "$TARGET/root/.ssh/authorized_keys"

exit 0
