Tags
#!/bin/bash
# Script Version: 02
# Description: Automate migration of a single LXC container to Incus and push it to remote project

# Set variables
# ========
LXCHOSTNAME="$1"
REMOTE_NAME="at1"
TARGET_PROJECT="raid1"
DEBUG=1

# Safety checks
# ========
if [ -z "$LXCHOSTNAME" ]; then
  echo "[ERROR] Usage: $0 <LXCHOSTNAME>"
  exit 1
fi

# Functions
# ========
stop_lxc_container() {
  echo "[DEBUG] Stopping LXC container $LXCHOSTNAME"
  if lxc-info -n "$LXCHOSTNAME" &>/dev/null; then
    lxc-stop -n "$LXCHOSTNAME" 2>/dev/null || true
  else
    echo "[WARN] LXC container $LXCHOSTNAME not found, skipping LXC stop"
  fi
}

fix_lxc_config() {
  local CFG="/var/lib/lxc/$LXCHOSTNAME/config"
  if [ -f "$CFG" ]; then
    echo "[DEBUG] Cleaning unsupported keys in $CFG"
    # Remove lxc.apparmor.allow_nesting lines
    sed -i '/^lxc.apparmor.allow_nesting/d' "$CFG"
  else
    echo "[ERROR] LXC config $CFG not found"
    exit 1
  fi
}

migrate_to_incus() {
  echo "[DEBUG] Running lxc-to-incus for $LXCHOSTNAME"
  lxc-to-incus --containers "$LXCHOSTNAME"
}

ensure_no_migration_running() {
  echo "[DEBUG] Checking for existing Incus migration operations"
  if incus operation list 2>/dev/null | grep -q "Migrating instance"; then
    echo "[ERROR] Existing Incus migration operation is running. Aborting."
    exit 1
  fi
}

stop_incus_container() {
  echo "[DEBUG] Ensuring Incus container $LXCHOSTNAME is stopped before copy"
  if incus info "$LXCHOSTNAME" &>/dev/null; then
    incus stop "$LXCHOSTNAME" 2>/dev/null || true
  else
    echo "[WARN] Incus container $LXCHOSTNAME not found (yet). This is expected before initial migration."
  fi
}

push_to_remote() {
  ensure_no_migration_running
  stop_incus_container

  echo "[DEBUG] Copying Incus container $LXCHOSTNAME to $REMOTE_NAME project $TARGET_PROJECT"
  incus copy --mode push "$LXCHOSTNAME" "${REMOTE_NAME}:${LXCHOSTNAME}" --target-project "$TARGET_PROJECT"
  local RC=$?

  if [ $RC -ne 0 ]; then
    echo "[ERROR] incus copy failed with status $RC"
    if [ "$DEBUG" -eq 1 ] 2>/dev/null; then
      echo "[DEBUG] Active Incus operations:"
      incus operation list || true
    fi
    exit $RC
  fi

  if [ "$DEBUG" -eq 1 ] 2>/dev/null; then
    echo "[DEBUG] incus copy completed without immediate error (rc=0)"
  fi
}

# Main Process
# ========
stop_lxc_container
fix_lxc_config
migrate_to_incus
push_to_remote

echo "[INFO] Migration of $LXCHOSTNAME completed"