packer {
  required_plugins {
    ansible = {
      source  = "github.com/hashicorp/ansible"
      version = "~> 1"
    }
    lxd = {
      source  = "github.com/hashicorp/lxd"
      version = "~> 1"
    }
    qemu = {
      source  = "github.com/hashicorp/qemu"
      version = "~> 1"
    }
  }
}

variable "image_name" {
  type    = string
  default = env("LAYEROPS_IMAGE_NAME")
}

variable "image_version" {
  type    = string
  default = env("LAYEROPS_IMAGE_VERSION")
}

variable "source_image" {
  type = string
  default = "ubuntu-minimal:jammy"
}

variable "layerops_data_path" {
  type = string
  default = "/data/layerops"
}

variable "playbook_root_dir" {
  type = string
  default = env("LAYEROPS_PLAYBOOK_ROOTDIR")
}

variable "playbook_file" {
  type = string
  default = env("LAYEROPS_PLAYBOOK_FILE")
}

variable "playbook_destination_path" {
  type = string
  default = "/tmp/layerops"
}

variable "image_destination_dir" {
  type = string
  default = env("LAYEROPS_IMAGE_DEST")
}

source "lxd" "lxd" {
  image = "${var.source_image}"
  output_image = "${var.image_name}"
}

build {
  sources = ["source.lxd.lxd"]

  provisioner "shell" {
    inline = [
      "df -h /",
      "apt-get update && apt-get install -y ansible python3 unattended-upgrades",
      "df -h /",
      "mkdir -p ${var.playbook_destination_path}"
    ]
  }

  provisioner "file" {
    source = "${var.playbook_root_dir}/"
    destination = "${var.playbook_destination_path}/"
  }

  provisioner "shell" {
    inline = [
      "cd ${var.playbook_destination_path}",
      "ansible-playbook --connection=local -i inventory --extra-vars \"ansible_python_interpreter=/usr/bin/python3 layerops_data_path=${var.layerops_data_path} layerops_image_version=${var.image_version}\" ${var.playbook_file}"
    ]
  }

  provisioner "shell" {
    inline = [
      "rm -rf ${var.playbook_destination_path}",
      "apt-get autoclean",
      "apt-get remove -y ansible && apt-get autoremove -y",
      "apt-get clean",
      "rm -rf ~/.bash_history /var/cache/*"
    ]
  }

  post-processor "shell-local" {
    inline = [
      "lxc image export ${var.image_name} lxc/${var.image_name}",
      "lxc image delete ${var.image_name}",
      "cd lxc",
      "./inject-metadata.sh ${var.image_name}"
    ]
  }
}
