#!/bin/bash -e
HOST_NAME=$1
IMAGE_NAME=$2
MACHINE=$3
exit 0
. config.sh
. config_machine.sh
if [ -z "$MACHINE" ]; then
    echo "usage: $0 name pkg dns_name"
    exit 1
fi
if [ ! -f "$MACHINE_NAME_NSPAWN_LOCAL" ]; then
    echo "PAS DE CONFIG NSPAWN $MACHINE_NAME_NSPAWN_LOCAL"
    exit 0
fi

if [ ! -f "$IMAGE_NAME_RISOTTO_IMAGE_NAME" ]; then
    echo "PAS D'IMAGE $IMAGE_NAME_RISOTTO_IMAGE_NAME"
    exit 1
fi
NEW_IMAGE=false
NEW_CONF=false
if [ -L "$MACHINE_MACHINES_DIR" ] || [ -d "$MACHINE_MACHINES_DIR" ]; then
    # is the base image divergent?
    diff -q "$IMAGE_NAME_RISOTTO_IMAGE_NAME".sha "$SHA_MACHINE" || NEW_IMAGE=true
    # is the configuration divergent?
    diff -q --no-dereference -Nru "$MACHINE_RISOTTO_CONFIG_DIR" "$MACHINE_RISOTTO_CONFIG_DIR_LOCAL" || NEW_CONF=true
fi
if [ "$NEW_IMAGE" = true ] || [ "$NEW_CONF" = true ]; then
    echo "  - stop $IMAGE_NAME"
    machinectl stop "$MACHINE" 2> /dev/null || true
    while true; do
        machinectl status "$MACHINE" > /dev/null 2>&1 || break
        sleep 1
    done
fi
if [ "$NEW_IMAGE" = true ]; then
    echo "  - delete old image"
    rm -rf "$MACHINE_MACHINES_DIR"
fi
if [ "$NEW_CONF" = true ]; then
    echo "  - delete old settings"
    ./diff.py "$MACHINE" "$MACHINE_RISOTTO_CONFIG_DIR" "$MACHINE_RISOTTO_CONFIG_DIR_LOCAL" > "$MACHINE_RISOTTO_CONFIG_DIR"_changelog.md
#    rm -rf "$MACHINE_RISOTTO_CONFIG_DIR"
fi

#cp -a "$MACHINE_NAME_NSPAWN_LOCAL" "$MACHINE_NAME_NSPAWN"
#cp -a "$MACHINE_NAME_SCRIPT_LOCAL" "$MACHINE_NAME_SCRIPT"
#if [ ! -d "$MACHINE_RISOTTO_CONFIG_DIR" ]; then
#    cp -a "$MACHINE_RISOTTO_CONFIG_DIR_LOCAL" "$MACHINE_RISOTTO_CONFIG_DIR"
#fi
#if [ ! -d "$MACHINE_RISOTTO_SRV_DIR" ] && [ -d "$MACHINE_RISOTTO_SRV_DIR_LOCAL" ]; then
#    mkdir -p "$MACHINE_RISOTTO_SRV_DIR"
#fi
#mkdir -p "$RISOTTO_JOURNALD_DIR"
if [ ! -d "$MACHINE_MACHINES_DIR" ]; then
    cd "$MACHINES_DIR"
    mkdir "$IMAGE_NAME"
    cd "$IMAGE_NAME"
    tar xf "$IMAGE_NAME_RISOTTO_IMAGE_NAME"
    mkdir -p "$SHA_MACHINE_DIR"
    cp -a "$IMAGE_NAME_RISOTTO_IMAGE_NAME".sha "$SHA_MACHINE"
    cd - > /dev/null
fi

echo "  => OK"
exit 0
