#!/usr/bin/env bash
# .sh/bin/setup-lxd 20170519 - 20201018
# Copyright (C) 1995-2020 Mark Constable <markc@renta.net> (AGPL-3.0)

[[ $1 =~ '-h' ]] &&
    echo "Usage: setup-lxd [pool size (25) GB] [passwd] [IP]" && exit 1

[[ $(id -u) -gt 0 ]] && echo "ERROR: must be root (use sudo -i)" && exit 2

LSTOR=zfs # btrfs, zfs, lvm, dir

PSIZE=${1:-'30'}
APASS=${2:-$(newpw)}
IP4_0=${3:-$(hostname -i | cut -d ' ' -f -1)}

if [[ -e /snap/bin/lxd ]]; then
    echo "Warning: lxd already installed"
else
    echo "Install packages for basic lxd, install criu manually if needed"
    if [[ -f /etc/pacman.conf ]]; then
        pacman -Syu --noconfirm >/dev/null
        pacman -S --noconfirm --needed bridge-utils btrfs-progs zfs-utils >/dev/null
        if [[ ! -L /snap ]]; then
            pacman -S snapd
        fi
        snap install lxd >/dev/null
        systemctl start snapd >/dev/null
        systemctl enable snapd >/dev/null
    else
        apt-get -qq update >/dev/null
        # criu requires python so leave out until actually needed
        DEBIAN_FRONTEND=noninteractive \
            apt-get -yqq install --no-install-recommends \
            lxd lxd-client bridge-utils btrfs-progs btrfs-tools zfsutils-linux >/dev/null
    fi
fi

lxc storage list | grep lxd-pool >/dev/null

if [[ $? -eq 0 ]]; then
    echo "Warning: lxd-pool already installed"
else
    echo "Install lxd with $PSIZE GB $LSTOR lxd-pool at $IP4_0 with pw $APASS"
    TMP=$([[ $LSTOR != dir ]] && echo "--storage-create-loop $PSIZE --storage-pool lxd-pool")
    lxd init --auto \
        --network-address $IP4_0 \
        --network-port 8443 \
        --storage-backend $LSTOR $TMP \
        --trust-password $APASS
fi

systemd-cat -t hlog echo "$(whoami) $(basename $0) $*"