#!/bin/sh

. /lib/functions.sh

migrate_from_lxc_to_oci_config() {
	config_load swmodd

	env_name=$(uci_get swmodd.@execenv[0].name)
	bundle_root=$(uci_get swmodd.globals.root)

	if [ -z "${bundle_root}" ]; then
		return 0
	fi

	if [ -z "${env_name}" ]; then
		return 0
	fi

	if ! command -v crun_create >/dev/null; then
		return 0
	fi

	if [ "${bundle_root: -1}" != '/' ]; then
		bundle_root="${bundle_root}/"
	fi

	lxcpath="${bundle_root}${env_name}"
	touch "${lxcpath}/ocicontainer"
	rm -rf "${lxcpath}/lxccontainer"

	dirs=$(ls -l "${lxcpath}/" 2>/dev/null | grep '^d' | awk '{print $9}')

	for d in ${dirs}; do
		config_file="${lxcpath}/${d}/config"

		if [ -f "${config_file}" ]; then
			crun_create -c -r "${bundle_root}" -e "${env_name}" -n "${d}" --no-reload
		fi
	done
}

migrate_from_lxc_to_oci_config
