#!/bin/bash

if [ $EUID -eq 0 ]; then
    echo "This script cannot be run as root."
    exit 1
fi

set -ex

export UNDERCLOUD_VM_NAME=${UNDERCLOUD_VM_NAME:-"instack"}

mkdir -p ~/.instack
LOGFILE=~/.instack/virt-setup-${UNDERCLOUD_VM_NAME}.log

exec > >(tee $LOGFILE)
exec 2>&1

export LIBVIRT_DEFAULT_URI="qemu:///system"

if [ ! -d "/usr/share/instack-undercloud" ]; then
    DEVTEST_VARIABLES=/usr/libexec/openstack-tripleo/devtest_variables.sh
    export ANSWERSFILE=$(dirname $0)/../undercloud.conf.sample
    export ELEMENTS_PATH="$(realpath $(dirname $0)/../elements):/usr/share/tripleo-image-elements:/usr/share/diskimage-builder/elements"
else
    DEVTEST_VARIABLES=/usr/libexec/openstack-tripleo/devtest_variables.sh
    export ANSWERSFILE=/usr/share/instack-undercloud/undercloud.conf.sample
    export ELEMENTS_PATH="/usr/share/instack-undercloud:/usr/share/tripleo-image-elements:/usr/share/diskimage-builder/elements"
fi

if $(grep -Eqs 'Red Hat Enterprise Linux' /etc/redhat-release); then
    export NODE_DIST=${NODE_DIST:-rhel7}
    export REG_METHOD=${REG_METHOD:-disable}
    export REG_HALT_UNREGISTER=${REG_HALT_UNREGISTER:-1}
elif $(grep -Eqs 'CentOS' /etc/redhat-release); then
    export NODE_DIST=${NODE_DIST:-centos7}
elif $(grep -Eqs 'Fedora' /etc/redhat-release); then
    export NODE_DIST=${NODE_DIST:-fedora}
else
    echo "Could not detect distribution from /etc/redhat-release!"
    exit 1
fi

source $DEVTEST_VARIABLES
tripleo install-dependencies
# libvirtd group
LIBVIRTD_GROUP='libvirtd'
getent group $LIBVIRTD_GROUP || sudo groupadd $LIBVIRTD_GROUP

if ! grep LIBVIRT_DEFAULT_URI ~/.bashrc; then
    echo 'export LIBVIRT_DEFAULT_URI="qemu:///system"' >> ~/.bashrc;
fi

if ! id | grep -qw $LIBVIRTD_GROUP; then
    echo "adding $USER to group $LIBVIRTD_GROUP"
    sudo usermod -a -G $LIBVIRTD_GROUP $USER
fi

if [ "$TRIPLEO_OS_FAMILY" = "redhat" ]; then
    libvirtd_file=/etc/libvirt/libvirtd.conf
    if ! sudo grep -q "^unix_sock_group" $libvirtd_file; then
        sudo sed -i "s/^#unix_sock_group.*/unix_sock_group = \"$LIBVIRTD_GROUP\"/g" $libvirtd_file
        sudo sed -i 's/^#auth_unix_rw.*/auth_unix_rw = "none"/g' $libvirtd_file
        sudo sed -i 's/^#unix_sock_rw_perms.*/unix_sock_rw_perms = "0770"/g' $libvirtd_file
        sudo service libvirtd restart
    fi
fi

export UNDERCLOUD_BRIDGE=${UNDERCLOUD_BRIDGE:-"brbm"}
# Set REG_MACHINE_NAME to match UNDERCLOUD_VM_NAME if it isn't already defined.
# This will be the name used to register the system to satllite/portal. If
# registration is not in use, this doesn't hurt anything.
export REG_MACHINE_NAME=${REG_MACHINE_NAME:-"$UNDERCLOUD_VM_NAME"}

if sudo virsh list --all --name | grep -q "^$UNDERCLOUD_VM_NAME$"; then
    set +x
    echo "*** Error ***"
    echo "Found existing libvirt domain '$UNDERCLOUD_VM_NAME'."
    echo "This script will not work if the domain already exists."
    echo "Undefine the domain and re-run instack-virt-setup."
    exit 1
fi

# We use $NODE_COUNT here instead of the $NODE_CNT from devtest_variables.sh so
# that it can still be overrideable *after* sourcing devtest_variables.sh
export NODE_COUNT=${NODE_COUNT:-2}
export NODE_CNT=$NODE_COUNT

export NODE_ARCH=x86_64
export NODE_MEM=${NODE_MEM:-5120}
export NODE_CPU=${NODE_CPU:-1}


# Check if virbr0 is already defined, and if it is, check if the libvirt
# default net is inactive. If it is inactive, we need to delete the existing
# virbr0.
# This is a case that shouldn't be encountered, but several people have run
# into it, so we have this workaround.
if ip link show | grep ' virbr0:'; then
    default_net=$(sudo virsh net-list --all --persistent | grep default | awk 'BEGIN{OFS=":";} {print $2,$3}')
    state=${default_net%%:*}
    autostart=${default_net##*:}

    if [ "$state" = "inactive" ]; then
        # We're in a bad state, somehow virbr0 exists but the default net is
        # not active.
        # Delete virbr0
        sudo ip link set dev virbr0 down
        sudo brctl delbr virbr0
    fi
fi

export TE_DATAFILE=instackenv.json
eval "sudo -H -E tripleo devtest_testenv.sh ${TESTENV_ARGS} $TE_DATAFILE"
sudo mv /root/.ssh/id_rsa_virt_power $HOME/.ssh/
sudo mv /root/.ssh/id_rsa_virt_power.pub $HOME/.ssh/
sudo chown -R $USER: ~/.ssh

sudo virsh undefine --remove-all-storage seed

if [ -n "${ATTACH_EXTRA_DISKS:-}" ]; then
    # Save number of overcloud VMs to make the following for loop flexible
    VM_LAST_NUMBER=$((NODE_COUNT-1))

    # Attach disks for os-disk-config testing
    for i in $(seq 0 $VM_LAST_NUMBER); do
        qcow_file=/var/lib/libvirt/images/baremetal_extra_${i}.qcow2
        sudo rm -f $qcow_file
        sudo qemu-img create $qcow_file 10G
        sudo virsh attach-disk baremetal_$i $qcow_file vda --type disk --persistent
    done
fi

export UNDERCLOUD_INSTALL=${UNDERCLOUD_INSTALL:-1}

if [ "$UNDERCLOUD_INSTALL" = "1" ]; then

    cp $ANSWERSFILE /tmp/instack.answers

    disk-image-create \
        --image-size 30 \
        -a amd64 \
        $NODE_DIST instack-vm \
        -o $UNDERCLOUD_VM_NAME

    sudo cp $UNDERCLOUD_VM_NAME.qcow2 /var/lib/libvirt/images/$UNDERCLOUD_VM_NAME.qcow2
else
    sudo qemu-img create -f qcow2 /var/lib/libvirt/images/$UNDERCLOUD_VM_NAME.qcow2 30G
fi

export UNDERCLOUD_NODE_ARCH=x86_64
export UNDERCLOUD_NODE_MEM=${UNDERCLOUD_NODE_MEM:-6144}
export UNDERCLOUD_NODE_CPU=${UNDERCLOUD_NODE_CPU:-2}

UNDERCLOUD_NODE_EXTRAOPTS=
if [[ ${DIB_COMMON_ELEMENTS:-} == *enable-serial-console* ]]; then
    UNDERCLOUD_NODE_EXTRAOPTS="--enable-serial-console"
fi

sudo tripleo configure-vm $UNDERCLOUD_NODE_EXTRAOPTS \
    --name $UNDERCLOUD_VM_NAME \
    --image /var/lib/libvirt/images/$UNDERCLOUD_VM_NAME.qcow2 \
    --baremetal-interface $UNDERCLOUD_BRIDGE \
    --seed \
    --libvirt-nic-driver virtio \
    --arch $UNDERCLOUD_NODE_ARCH \
    --memory $((1024 * $UNDERCLOUD_NODE_MEM)) \
    --cpus $UNDERCLOUD_NODE_CPU

sudo virsh start $UNDERCLOUD_VM_NAME

timeout_seconds=180
elapsed_seconds=0
while true; do
    IP=$(ip n | grep $(tripleo get-vm-mac " $UNDERCLOUD_VM_NAME ") | awk '{print $1;}')
    if [ -n "$IP" ]; then
        set +x
        echo "$UNDERCLOUD_VM_NAME vm IP address is $IP"
        echo "You can connect by running:"
        echo "ssh root@$IP"
        echo "And then su to the stack user:"
        echo "su - stack"
        break
    fi
    sleep 3
    (( elapsed_seconds += 3 ))
    if [ $elapsed_seconds -ge $timeout_seconds ]; then
        set +x
        echo "$UNDERCLOUD_VM_NAME never got an IP address from the libvirt default network."
    fi
done
