#!/bin/bash
set -e

die() {
        echo >&2 "$@"
        usage
        exit 1
}

usage () {
  echo >&2 "Usage: $0  [-d <device> | -f <size>] -t <back-end type> [-4 <bridge IPv4 CIDR>] [-6 <bridge IPv6 CIDR>]
       where,
          <device>   - device name for containers storage. For example, /dev/sdb2}
          <size> - size of the file in GiB that will be used for containers storage.
          <back-end type> - storage back-end type (zfs or lvm)
          <bridge IPv4 CIDR> - IPv4 for the lxdbr0 (auto, none, CIDR). Default: auto
          <bridge IPv6 CIDR> - IPv6 for the lxdbr0 (auto, none, CIDR). Default: none
"
}

while getopts "hd:f:t:4:6:" opt; do
	case "$opt" in
	d) DEV=$OPTARG;;
	t) TYPE=$OPTARG;;
	f) SIZE=$OPTARG;;
	4) IPv4=$OPTARG;;
	6) IPv6=$OPTARG;;
	h|*) usage;;
	esac
done

[ -z "$DEV" ] && [ -z "$SIZE" ] && die "E: Either -d or -f option must be used."
[ -n "$DEV" ] && [ -n "$SIZE" ] && die "E: It is not possible to define -d and -f options at the same time."
[ -z "$TYPE" ] && die "E: A backend type must be defined."
if [[ ${TYPE} != "zfs" && ${TYPE} != "lvm" ]]; then
  die "E: wrong storage back-end type."
fi

if [ "${TYPE}" == "lvm" ]; then
  if  ! dpkg -s thin-provisioning-tools > /dev/null 2>&1 ; then
    die "E: thin-provisioning-tools package must be installed for LVM storage back-end type."
  fi
fi

[ -z "$IPv4" ] && IPv4=auto
[ -z "$IPv6" ] && IPv6=none
echo "I: LXD initializing..."
echo_lxd_conf() {
cat <<EOF
config:
  images.auto_update_interval: "0"
  core.https_address: 127.0.0.1
cluster: null
networks:
- config:
    ipv4.address: ${IPv4}
    ipv6.address: ${IPv6}
    ipv4.firewall: false
    ipv4.nat: true
    ipv4.dhcp.expiry: infinite
  description: ""
  name: lxdbr0
  type: ""
storage_pools:
- config:
EOF
if [ -n "$DEV" ]; then
  cat << EOF
    source: ${DEV}
EOF
fi
if [ -n "$SIZE" ]; then
  cat << EOF
    size: ${SIZE}GB
EOF
fi
cat <<EOF
  description: ""
  name: default
  driver: ${TYPE}
profiles:
- config: {}
  description: ""
  devices:
    eth0:
      name: eth0
      nictype: bridged
      parent: lxdbr0
      type: nic
    root:
      path: /
      pool: default
      type: disk
  name: default
EOF
}

echo_lxd_conf | lxd init --preseed

if [ "${TYPE}" = "zfs" ]; then
  echo "I: Enable extended attributed on the ZFS system attributes base..."
  zfs set acltype=posixacl xattr=sa default
fi
if [ -f /sys/fs/cgroup/cgroup.controllers ];then
  lxc profile set default raw.lxc "lxc.cgroup2.memory.swap.max = max"
fi
lxc profile set default security.nesting true
echo "I: LXD initializing completed!" 

