From 19cc18037c0af075b3b8277eb6ac4db021552f44 Mon Sep 17 00:00:00 2001 From: "CanbiZ (MickLesk)" <47820557+MickLesk@users.noreply.github.com> Date: Thu, 12 Mar 2026 09:06:41 +0100 Subject: [PATCH] vm app-deployer --- docs/vm/APP_DEPLOYER_VM.md | 173 ++++++++++ misc/vm-app.func | 683 +++++++++++++++++++++++++++++++++++++ vm/app-deployer-vm.sh | 426 +++++++++++++++++++++++ 3 files changed, 1282 insertions(+) create mode 100644 docs/vm/APP_DEPLOYER_VM.md create mode 100644 misc/vm-app.func create mode 100644 vm/app-deployer-vm.sh diff --git a/docs/vm/APP_DEPLOYER_VM.md b/docs/vm/APP_DEPLOYER_VM.md new file mode 100644 index 000000000..88010b005 --- /dev/null +++ b/docs/vm/APP_DEPLOYER_VM.md @@ -0,0 +1,173 @@ +# App Deployer VM + +Deploy LXC applications inside a full Virtual Machine instead of an LXC container. + +## Overview + +The App Deployer VM bridges the gap between CT install scripts (`install/*.sh`) and VM infrastructure. It leverages the existing install scripts — originally designed for LXC containers — and runs them inside a full VM via a first-boot systemd service. + +### Supported Operating Systems + +| OS | Version | Codename | Cloud-Init | +| ---- | --------- | ---------- | ------------ | +| Debian | 13 | Trixie | Optional | +| Debian | 12 | Bookworm | Optional | +| Ubuntu | 24.04 LTS | Noble | Required | +| Ubuntu | 22.04 LTS | Jammy | Required | + +## Usage + +### Create a new App VM (interactive) + +```bash +bash -c "$(curl -fsSL https://git.community-scripts.org/community-scripts/ProxmoxVED/raw/branch/main/vm/app-deployer-vm.sh)" +``` + +### Pre-select application + +```bash +APP_SELECT=yamtrack bash -c "$(curl -fsSL https://git.community-scripts.org/community-scripts/ProxmoxVED/raw/branch/main/vm/app-deployer-vm.sh)" +``` + +### Update the application later (inside the VM) + +```bash +bash /opt/community-scripts/update-app.sh +``` + +## How It Works + +### Installation Flow + +``` +┌─────────────────────────────────────┐ +│ Proxmox Host │ +│ │ +│ 1. Select app (e.g. Yamtrack) │ +│ 2. Select OS (e.g. Debian 13) │ +│ 3. Configure VM resources │ +│ 4. Download cloud image │ +│ 5. virt-customize: │ +│ - Install base packages │ +│ - Inject install.func │ +│ - Inject tools.func │ +│ - Inject install script │ +│ - Create first-boot service │ +│ - Inject update mechanism │ +│ 6. Create VM (qm create) │ +│ 7. Import customized disk │ +│ 8. Start VM │ +└────────────┬────────────────────────┘ + │ First Boot +┌────────────▼────────────────────────┐ +│ VM (Debian/Ubuntu) │ +│ │ +│ app-install.service (oneshot): │ +│ 1. Wait for network │ +│ 2. Set environment variables │ +│ (FUNCTIONS_FILE_PATH, etc.) │ +│ 3. Run install/-install.sh │ +│ 4. Mark as installed │ +│ │ +│ → Application running in VM! │ +└─────────────────────────────────────┘ +``` + +### Update Flow + +``` +┌─────────────────────────────────────┐ +│ Inside the VM (SSH or console) │ +│ │ +│ bash /opt/community-scripts/ │ +│ update-app.sh │ +│ │ +│ → Downloads ct/.sh │ +│ → start() detects no pveversion │ +│ → Shows update/settings menu │ +│ → Runs update_script() │ +└─────────────────────────────────────┘ +``` + +The update mechanism reuses the existing CT script logic. Since `pveversion` is not available inside the VM, the `start()` function automatically enters the update/settings mode — the same path it takes inside LXC containers. + +## Architecture + +### Files + +| File | Purpose | +| ------ | --------- | +| `vm/app-deployer-vm.sh` | Main user-facing script | +| `misc/vm-app.func` | Core library for VM app deployment | +| `misc/vm-core.func` | Shared VM functions (colors, spinner, etc.) | +| `misc/cloud-init.func` | Cloud-Init configuration (optional) | + +### Key Design Decisions + +1. **Install scripts run unmodified** — The same `install/*.sh` scripts that work in LXC containers work inside VMs. The environment (`FUNCTIONS_FILE_PATH`, exports) is replicated identically. + +2. **Image customization via `virt-customize`** — All files are injected into the qcow2 image before the VM boots. No SSH or guest agent required during setup. + +3. **First-boot systemd service** — The install script runs automatically on first boot. Progress can be monitored via `/var/log/app-install.log`. + +4. **Update via CT script** — The existing CT script's `start()` → `update_script()` flow works in VMs without modification. + +### Environment Variables (set during first-boot) + +| Variable | Description | +| ---------- | ------------- | +| `FUNCTIONS_FILE_PATH` | Full contents of `install.func` | +| `APPLICATION` | App display name (e.g. "Yamtrack") | +| `app` | App identifier (e.g. "yamtrack") | +| `VERBOSE` | "no" (silent mode) | +| `SSH_ROOT` | "yes" | +| `PCT_OSTYPE` | OS type (debian/ubuntu) | +| `PCT_OSVERSION` | OS version (12/13/22.04/24.04) | +| `COMMUNITY_SCRIPTS_URL` | Repository base URL | +| `DEPLOY_TARGET` | "vm" (distinguishes from LXC) | + +### VM Directory Structure + +``` +/opt/community-scripts/ +├── install.func # Function library +├── tools.func # Helper functions +├── install/ +│ └── -install.sh # Application install script +├── ct/ +│ └── (downloaded on update) # CT script for updates +└── update-app.sh # Update wrapper script +``` + +## Limitations + +- **Alpine-based apps**: Currently only Debian/Ubuntu VMs are supported. Alpine install scripts are not compatible. +- **LXC-specific features**: Some CT features (FUSE, TUN, GPU passthrough) are configured differently in VMs. +- **First-boot timing**: The app installation happens after the VM boots, so the application is not immediately available (monitor `/var/log/app-install.log`). +- **`cleanup_lxc`**: This function works fine in VMs (it only cleans package caches), but the name is LXC-centric. + +## Troubleshooting + +### Check installation progress + +```bash +# From inside the VM +tail -f /var/log/app-install.log + +# From the Proxmox host (via guest agent) +qm guest exec -- cat /var/log/app-install.log +``` + +### Re-run installation + +```bash +# Remove the installed marker and reboot +rm /root/.app-installed +systemctl start app-install.service +``` + +### Check if installation completed + +```bash +test -f /root/.app-installed && echo "Installed" || echo "Not yet installed" +``` diff --git a/misc/vm-app.func b/misc/vm-app.func new file mode 100644 index 000000000..dddefd8a5 --- /dev/null +++ b/misc/vm-app.func @@ -0,0 +1,683 @@ +#!/usr/bin/env bash + +# Copyright (c) 2021-2026 community-scripts ORG +# Author: MickLesk (CanbiZ) +# License: MIT | https://git.community-scripts.org/community-scripts/ProxmoxVED/raw/branch/main/LICENSE + +# ============================================================================== +# VM-APP.FUNC - DEPLOY LXC APPLICATIONS INSIDE VIRTUAL MACHINES +# ============================================================================== +# +# This library enables deploying applications that are normally installed in +# LXC containers into full Virtual Machines instead. It bridges the gap between +# CT install scripts (install/*.sh) and VM infrastructure. +# +# How it works: +# 1. Creates a VM with a cloud image (Debian 12/13, Ubuntu 22.04/24.04) +# 2. Uses virt-customize to inject install scripts and dependencies +# 3. Creates a first-boot systemd service that runs the install script +# 4. For updates: the CT script can be run directly inside the VM +# +# Key Functions: +# select_app() - Interactive app selection from install/*.sh +# get_app_metadata() - Extract app defaults from ct/*.sh +# get_image_url() - Cloud image URL for selected OS +# download_and_cache_image()- Download with caching +# customize_vm_image() - Inject app install script into image +# build_app_vm() - Main orchestrator +# +# Usage: +# source <(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/vm-app.func") +# APP_INSTALL_SCRIPT="yamtrack" +# build_app_vm +# +# ============================================================================== + +# ============================================================================== +# SECTION 1: APP DISCOVERY & SELECTION +# ============================================================================== + +# ------------------------------------------------------------------------------ +# list_available_apps() +# +# Scans the install/ directory for available app install scripts. +# Returns a sorted list of app names (without -install.sh suffix). +# Excludes base OS install scripts (debian, ubuntu, alpine, etc.) +# ------------------------------------------------------------------------------ +list_available_apps() { + local base_url="$COMMUNITY_SCRIPTS_URL" + local exclude_pattern="^(debian|ubuntu|alpine|devuan|fedora|centos|rockylinux|almalinux|opensuse|openeuler|gentoo|arm)-install\.sh$" + + # Try to list from local checkout first, fall back to known apps + if [[ -d "/tmp/proxmoxved-repo/install" ]]; then + find /tmp/proxmoxved-repo/install -name '*-install.sh' -printf '%f\n' | + grep -vE "$exclude_pattern" | + sed 's/-install\.sh$//' | + sort + else + # Fetch install script list from API/repo + curl -fsSL "${base_url}/install/" 2>/dev/null | + grep -oP '[a-z0-9_-]+-install\.sh' | + grep -vE "$exclude_pattern" | + sed 's/-install\.sh$//' | + sort + fi +} + +# ------------------------------------------------------------------------------ +# select_app() +# +# Interactive app selection using whiptail. +# Sets: APP_INSTALL_SCRIPT (app name, e.g. "yamtrack") +# If called with $1, uses that as pre-selected app (non-interactive). +# ------------------------------------------------------------------------------ +select_app() { + if [[ -n "${1:-}" ]]; then + APP_INSTALL_SCRIPT="$1" + return 0 + fi + + local apps=() + local app_list + + msg_info "Discovering available applications" + + # Build app list for whiptail + app_list=$(list_available_apps) + if [[ -z "$app_list" ]]; then + msg_error "Could not retrieve application list" + exit 1 + fi + + local count=0 + while IFS= read -r app; do + [[ -z "$app" ]] && continue + apps+=("$app" "$app" "OFF") + count=$((count + 1)) + done <<<"$app_list" + + msg_ok "Found ${count} available applications" + + if [[ $count -eq 0 ]]; then + msg_error "No applications found" + exit 1 + fi + + # Calculate display height + local menu_height=$((count > 20 ? 20 : count)) + local box_height=$((menu_height + 8)) + + stop_spinner 2>/dev/null || true + if APP_INSTALL_SCRIPT=$(whiptail --backtitle "Proxmox VE Helper Scripts" \ + --title "SELECT APPLICATION" \ + --radiolist "Choose an application to deploy in the VM.\nUse Space to select, Enter to confirm." \ + "$box_height" 68 "$menu_height" \ + "${apps[@]}" 3>&1 1>&2 2>&3); then + if [[ -z "$APP_INSTALL_SCRIPT" ]]; then + msg_error "No application selected" + exit 1 + fi + echo -e "${INFO}${BOLD}${DGN}Application: ${BGN}${APP_INSTALL_SCRIPT}${CL}" + else + exit_script + fi +} + +# ------------------------------------------------------------------------------ +# get_app_metadata() +# +# Extracts metadata from the CT script (ct/.sh) for the selected app. +# This gives us the app's recommended CPU, RAM, disk, OS requirements. +# Sets: APP_NAME, APP_CPU, APP_RAM, APP_DISK, APP_OS, APP_VERSION +# ------------------------------------------------------------------------------ +get_app_metadata() { + local app="${APP_INSTALL_SCRIPT}" + local ct_script_url="${COMMUNITY_SCRIPTS_URL}/ct/${app}.sh" + local ct_content + + ct_content=$(curl -fsSL "$ct_script_url" 2>/dev/null) || { + # No CT script found - use sensible defaults + APP_NAME="${app^}" + APP_CPU="2" + APP_RAM="2048" + APP_DISK="10" + APP_OS="${OS_TYPE:-debian}" + APP_VERSION="${OS_VERSION:-13}" + return 0 + } + + # Extract metadata from CT script using grep (safe - no eval/source) + APP_NAME=$(echo "$ct_content" | grep -oP '^APP="\K[^"]+' | head -1) + APP_CPU=$(echo "$ct_content" | grep -oP '^var_cpu="\$\{var_cpu:-\K[0-9]+' | head -1) + APP_RAM=$(echo "$ct_content" | grep -oP '^var_ram="\$\{var_ram:-\K[0-9]+' | head -1) + APP_DISK=$(echo "$ct_content" | grep -oP '^var_disk="\$\{var_disk:-\K[0-9]+' | head -1) + APP_OS=$(echo "$ct_content" | grep -oP '^var_os="\$\{var_os:-\K[^}]+' | head -1) + APP_VERSION=$(echo "$ct_content" | grep -oP '^var_version="\$\{var_version:-\K[^}]+' | head -1) + + # Fallbacks + APP_NAME="${APP_NAME:-${app^}}" + APP_CPU="${APP_CPU:-2}" + APP_RAM="${APP_RAM:-2048}" + APP_DISK="${APP_DISK:-10}" + APP_OS="${APP_OS:-debian}" + APP_VERSION="${APP_VERSION:-13}" +} + +# ============================================================================== +# SECTION 2: OS SELECTION & IMAGE MANAGEMENT +# ============================================================================== + +# ------------------------------------------------------------------------------ +# select_vm_os() +# +# Interactive OS selection for the VM. Users can choose: +# - Debian 12 (Bookworm) +# - Debian 13 (Trixie) +# - Ubuntu 22.04 LTS (Jammy) +# - Ubuntu 24.04 LTS (Noble) +# +# Sets: OS_TYPE, OS_VERSION, OS_CODENAME, OS_DISPLAY +# ------------------------------------------------------------------------------ +select_vm_os() { + # Default to the app's recommended OS + local default_choice="debian13" + case "${APP_OS:-debian}" in + ubuntu) + case "${APP_VERSION:-24.04}" in + 22.04) default_choice="ubuntu2204" ;; + *) default_choice="ubuntu2404" ;; + esac + ;; + debian) + case "${APP_VERSION:-13}" in + 12) default_choice="debian12" ;; + *) default_choice="debian13" ;; + esac + ;; + esac + + stop_spinner 2>/dev/null || true + if OS_CHOICE=$(whiptail --backtitle "Proxmox VE Helper Scripts" --title "SELECT OS" --radiolist \ + "Choose Operating System for ${APP_NAME} VM\n(App recommends: ${APP_OS} ${APP_VERSION})" 16 68 4 \ + "debian13" "Debian 13 (Trixie) - Latest" $([[ "$default_choice" == "debian13" ]] && echo "ON" || echo "OFF") \ + "debian12" "Debian 12 (Bookworm) - Stable" $([[ "$default_choice" == "debian12" ]] && echo "ON" || echo "OFF") \ + "ubuntu2404" "Ubuntu 24.04 LTS (Noble)" $([[ "$default_choice" == "ubuntu2404" ]] && echo "ON" || echo "OFF") \ + "ubuntu2204" "Ubuntu 22.04 LTS (Jammy)" $([[ "$default_choice" == "ubuntu2204" ]] && echo "ON" || echo "OFF") \ + 3>&1 1>&2 2>&3); then + case $OS_CHOICE in + debian13) + OS_TYPE="debian" + OS_VERSION="13" + OS_CODENAME="trixie" + OS_DISPLAY="Debian 13 (Trixie)" + ;; + debian12) + OS_TYPE="debian" + OS_VERSION="12" + OS_CODENAME="bookworm" + OS_DISPLAY="Debian 12 (Bookworm)" + ;; + ubuntu2404) + OS_TYPE="ubuntu" + OS_VERSION="24.04" + OS_CODENAME="noble" + OS_DISPLAY="Ubuntu 24.04 LTS" + ;; + ubuntu2204) + OS_TYPE="ubuntu" + OS_VERSION="22.04" + OS_CODENAME="jammy" + OS_DISPLAY="Ubuntu 22.04 LTS" + ;; + esac + echo -e "${OS}${BOLD}${DGN}Operating System: ${BGN}${OS_DISPLAY}${CL}" + else + exit_script + fi + + # Ubuntu always needs Cloud-Init + if [ "$OS_TYPE" = "ubuntu" ]; then + USE_CLOUD_INIT="yes" + else + USE_CLOUD_INIT="no" + fi +} + +# ------------------------------------------------------------------------------ +# get_image_url() +# +# Returns the cloud image download URL for the selected OS. +# Uses genericcloud (Cloud-Init) or nocloud variants as appropriate. +# ------------------------------------------------------------------------------ +get_image_url() { + local arch + arch=$(dpkg --print-architecture) + + case $OS_TYPE in + debian) + if [ "$USE_CLOUD_INIT" = "yes" ]; then + echo "https://cloud.debian.org/images/cloud/${OS_CODENAME}/latest/debian-${OS_VERSION}-generic-${arch}.qcow2" + else + echo "https://cloud.debian.org/images/cloud/${OS_CODENAME}/latest/debian-${OS_VERSION}-nocloud-${arch}.qcow2" + fi + ;; + ubuntu) + echo "https://cloud-images.ubuntu.com/${OS_CODENAME}/current/${OS_CODENAME}-server-cloudimg-${arch}.img" + ;; + esac +} + +# ------------------------------------------------------------------------------ +# download_and_cache_image() +# +# Downloads the cloud image with caching support. +# Sets: CACHE_FILE (path to the cached/downloaded image) +# ------------------------------------------------------------------------------ +download_and_cache_image() { + msg_info "Retrieving the URL for the ${OS_DISPLAY} Qcow2 Disk Image" + URL=$(get_image_url) + CACHE_DIR="/var/lib/vz/template/cache" + CACHE_FILE="$CACHE_DIR/$(basename "$URL")" + mkdir -p "$CACHE_DIR" + msg_ok "${CL}${BL}${URL}${CL}" + + if [[ ! -s "$CACHE_FILE" ]]; then + curl -f#SL -o "$CACHE_FILE" "$URL" + echo -en "\e[1A\e[0K" + msg_ok "Downloaded ${CL}${BL}$(basename "$CACHE_FILE")${CL}" + else + msg_ok "Using cached image ${CL}${BL}$(basename "$CACHE_FILE")${CL}" + fi +} + +# ============================================================================== +# SECTION 3: IMAGE CUSTOMIZATION +# ============================================================================== + +# ------------------------------------------------------------------------------ +# ensure_virt_customize() +# +# Ensures virt-customize (libguestfs-tools) is installed on the Proxmox host. +# ------------------------------------------------------------------------------ +ensure_virt_customize() { + if ! command -v virt-customize &>/dev/null; then + msg_info "Installing libguestfs-tools" + apt-get -qq update >/dev/null + apt-get -qq install libguestfs-tools -y >/dev/null + msg_ok "Installed libguestfs-tools" + fi +} + +# ------------------------------------------------------------------------------ +# customize_vm_image() +# +# Main image customization function. Uses virt-customize to: +# 1. Install base packages (qemu-guest-agent, curl, sudo, etc.) +# 2. Inject install.func and tools.func as files +# 3. Inject the application install script +# 4. Create a first-boot systemd service +# 5. Inject the update mechanism +# 6. Configure hostname, SSH, auto-login +# +# Parameters: None (uses global variables) +# Sets: WORK_FILE (path to the customized image), APP_PREINSTALLED flag +# ------------------------------------------------------------------------------ +customize_vm_image() { + local app="${APP_INSTALL_SCRIPT}" + + WORK_FILE=$(mktemp --suffix=.qcow2) + cp "$CACHE_FILE" "$WORK_FILE" + + export LIBGUESTFS_BACKEND_SETTINGS=dns=8.8.8.8,1.1.1.1 + + APP_PREINSTALLED="no" + + # --- Step 1: Install base packages --- + msg_info "Installing base packages in image" + if virt-customize -a "$WORK_FILE" --install qemu-guest-agent,curl,sudo,ca-certificates,gnupg2,jq,mc >/dev/null 2>&1; then + msg_ok "Installed base packages" + else + msg_warn "Base packages will be installed on first boot" + fi + + # --- Step 2: Create directory structure --- + virt-customize -q -a "$WORK_FILE" \ + --mkdir /opt/community-scripts \ + --mkdir /opt/community-scripts/install \ + --mkdir /opt/community-scripts/ct >/dev/null 2>&1 + + # --- Step 3: Inject function libraries --- + msg_info "Injecting function libraries into image" + + # Download install.func and tools.func content + local install_func_content tools_func_content + install_func_content=$(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/install.func") + tools_func_content=$(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/tools.func") + + # Write function libraries to temp files for injection + local tmp_install_func tmp_tools_func + tmp_install_func=$(mktemp) + tmp_tools_func=$(mktemp) + echo "$install_func_content" >"$tmp_install_func" + echo "$tools_func_content" >"$tmp_tools_func" + + virt-customize -q -a "$WORK_FILE" \ + --upload "$tmp_install_func:/opt/community-scripts/install.func" \ + --upload "$tmp_tools_func:/opt/community-scripts/tools.func" >/dev/null 2>&1 + + rm -f "$tmp_install_func" "$tmp_tools_func" + msg_ok "Injected function libraries" + + # --- Step 4: Inject application install script --- + msg_info "Injecting ${APP_NAME} install script" + + local install_script_content + install_script_content=$(curl -fsSL "$COMMUNITY_SCRIPTS_URL/install/${app}-install.sh") + + local tmp_install_script + tmp_install_script=$(mktemp) + echo "$install_script_content" >"$tmp_install_script" + + virt-customize -q -a "$WORK_FILE" \ + --upload "$tmp_install_script:/opt/community-scripts/install/${app}-install.sh" \ + --chmod 0755:/opt/community-scripts/install/${app}-install.sh >/dev/null 2>&1 + + rm -f "$tmp_install_script" + msg_ok "Injected ${APP_NAME} install script" + + # --- Step 5: Create first-boot wrapper script --- + msg_info "Creating first-boot installation service" + + local wrapper_script + wrapper_script=$(mktemp) + cat >"$wrapper_script" < /var/log/app-install.log 2>&1 +echo "[\$(date)] Starting ${APP_NAME} installation" + +# Wait for network connectivity +echo "[\$(date)] Waiting for network..." +for i in {1..60}; do + if ping -c 1 -W 2 8.8.8.8 >/dev/null 2>&1 || ping -c 1 -W 2 1.1.1.1 >/dev/null 2>&1; then + echo "[\$(date)] Network is up" + break + fi + sleep 2 +done + +# Set environment variables (same as build_container provides) +export FUNCTIONS_FILE_PATH="\$(cat /opt/community-scripts/install.func)" +export APPLICATION="${APP_NAME}" +export app="${app}" +export VERBOSE="no" +export SSH_ROOT="yes" +export CTTYPE="1" +export PCT_OSTYPE="${OS_TYPE}" +export PCT_OSVERSION="${OS_VERSION}" +export COMMUNITY_SCRIPTS_URL="${COMMUNITY_SCRIPTS_URL}" +export DEPLOY_TARGET="vm" + +# Run the install script +echo "[\$(date)] Running install script..." +bash /opt/community-scripts/install/${app}-install.sh + +# Mark installation as complete +touch /root/.app-installed +echo "[\$(date)] ${APP_NAME} installation completed successfully" +WRAPPER_EOF + + virt-customize -q -a "$WORK_FILE" \ + --upload "$wrapper_script:/root/app-install-wrapper.sh" \ + --chmod 0755:/root/app-install-wrapper.sh >/dev/null 2>&1 + + rm -f "$wrapper_script" + + # --- Step 6: Create systemd first-boot service --- + local service_file + service_file=$(mktemp) + cat >"$service_file" <<'SERVICE_EOF' +[Unit] +Description=Install Application on First Boot (ProxmoxVED App Deployer) +After=network-online.target +Wants=network-online.target +ConditionPathExists=!/root/.app-installed + +[Service] +Type=oneshot +ExecStart=/root/app-install-wrapper.sh +RemainAfterExit=yes +TimeoutStartSec=1800 +StandardOutput=journal+console +StandardError=journal+console + +[Install] +WantedBy=multi-user.target +SERVICE_EOF + + virt-customize -q -a "$WORK_FILE" \ + --upload "$service_file:/etc/systemd/system/app-install.service" >/dev/null 2>&1 + virt-customize -q -a "$WORK_FILE" \ + --run-command 'systemctl enable app-install.service' >/dev/null 2>&1 + + rm -f "$service_file" + msg_ok "Created first-boot installation service" + + # --- Step 7: Inject update mechanism --- + msg_info "Injecting update mechanism" + + local update_wrapper + update_wrapper=$(mktemp) + cat >"$update_wrapper" </dev/null 2>&1 + + rm -f "$update_wrapper" + msg_ok "Injected update mechanism" + + # --- Step 8: Configure hostname and SSH --- + msg_info "Finalizing image (hostname, SSH config)" + + virt-customize -q -a "$WORK_FILE" --hostname "${HN}" >/dev/null 2>&1 + virt-customize -q -a "$WORK_FILE" --run-command "truncate -s 0 /etc/machine-id" >/dev/null 2>&1 + virt-customize -q -a "$WORK_FILE" --run-command "rm -f /var/lib/dbus/machine-id" >/dev/null 2>&1 + + if [ "$USE_CLOUD_INIT" = "yes" ]; then + virt-customize -q -a "$WORK_FILE" --run-command "sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config" >/dev/null 2>&1 || true + virt-customize -q -a "$WORK_FILE" --run-command "sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config" >/dev/null 2>&1 || true + else + # Configure auto-login for nocloud images + virt-customize -q -a "$WORK_FILE" --run-command "mkdir -p /etc/systemd/system/serial-getty@ttyS0.service.d" >/dev/null 2>&1 || true + virt-customize -q -a "$WORK_FILE" --run-command 'cat > /etc/systemd/system/serial-getty@ttyS0.service.d/autologin.conf << EOF +[Service] +ExecStart= +ExecStart=-/sbin/agetty --autologin root --noclear %I \$TERM +EOF' >/dev/null 2>&1 || true + virt-customize -q -a "$WORK_FILE" --run-command "mkdir -p /etc/systemd/system/getty@tty1.service.d" >/dev/null 2>&1 || true + virt-customize -q -a "$WORK_FILE" --run-command 'cat > /etc/systemd/system/getty@tty1.service.d/autologin.conf << EOF +[Service] +ExecStart= +ExecStart=-/sbin/agetty --autologin root --noclear %I \$TERM +EOF' >/dev/null 2>&1 || true + fi + + msg_ok "Finalized image" + + # --- Step 9: Resize disk --- + msg_info "Resizing disk image to ${DISK_SIZE}" + qemu-img resize "$WORK_FILE" "${DISK_SIZE}" >/dev/null 2>&1 + msg_ok "Resized disk image" +} + +# ============================================================================== +# SECTION 4: VM CREATION & ORCHESTRATION +# ============================================================================== + +# ------------------------------------------------------------------------------ +# create_app_vm() +# +# Creates the QEMU VM, imports the customized disk, attaches EFI + scsi, +# configures Cloud-Init if needed, and starts the VM. +# ------------------------------------------------------------------------------ +create_app_vm() { + msg_info "Creating ${APP_NAME} VM shell" + + qm create "$VMID" -agent 1${MACHINE} -tablet 0 -localtime 1 -bios ovmf${CPU_TYPE} \ + -cores "$CORE_COUNT" -memory "$RAM_SIZE" -name "$HN" -tags "community-script;app-deployer;${APP_INSTALL_SCRIPT}" \ + -net0 "virtio,bridge=$BRG,macaddr=$MAC$VLAN$MTU" -onboot 1 -ostype l26 -scsihw virtio-scsi-pci >/dev/null + + msg_ok "Created VM shell" + + # Import disk + msg_info "Importing disk into storage ($STORAGE)" + if qm disk import --help >/dev/null 2>&1; then + IMPORT_CMD=(qm disk import) + else + IMPORT_CMD=(qm importdisk) + fi + + IMPORT_OUT="$("${IMPORT_CMD[@]}" "$VMID" "$WORK_FILE" "$STORAGE" ${DISK_IMPORT:-} 2>&1 || true)" + DISK_REF_IMPORTED="$(printf '%s\n' "$IMPORT_OUT" | sed -n "s/.*successfully imported disk '\([^']\+\)'.*/\1/p" | tr -d "\r\"'")" + [[ -z "$DISK_REF_IMPORTED" ]] && DISK_REF_IMPORTED="$(pvesm list "$STORAGE" | awk -v id="$VMID" '$5 ~ ("vm-"id"-disk-") {print $1":"$5}' | sort | tail -n1)" + [[ -z "$DISK_REF_IMPORTED" ]] && { + msg_error "Unable to determine imported disk reference." + echo "$IMPORT_OUT" + exit 1 + } + msg_ok "Imported disk (${CL}${BL}${DISK_REF_IMPORTED}${CL})" + + # Clean up work file + rm -f "$WORK_FILE" + + # Attach disks + msg_info "Attaching EFI and root disk" + if [ "$USE_CLOUD_INIT" = "yes" ]; then + qm set "$VMID" \ + --efidisk0 "${STORAGE}:0,efitype=4m" \ + --scsi0 "${DISK_REF_IMPORTED},${DISK_CACHE}${THIN%,}" \ + --scsi1 "${STORAGE}:cloudinit" \ + --boot order=scsi0 \ + --serial0 socket >/dev/null + else + qm set "$VMID" \ + --efidisk0 "${STORAGE}:0,efitype=4m" \ + --scsi0 "${DISK_REF_IMPORTED},${DISK_CACHE}${THIN%,}" \ + --boot order=scsi0 \ + --serial0 socket >/dev/null + fi + + qm set "$VMID" --agent enabled=1 >/dev/null + msg_ok "Attached EFI and root disk" + + # Set VM description + set_description + + # Cloud-Init configuration + if [ "$USE_CLOUD_INIT" = "yes" ] && declare -f setup_cloud_init >/dev/null 2>&1; then + msg_info "Configuring Cloud-Init" + setup_cloud_init "$VMID" "$STORAGE" "$HN" "yes" + msg_ok "Cloud-Init configured" + fi + + # Start VM + if [ "$START_VM" == "yes" ]; then + msg_info "Starting ${APP_NAME} VM" + qm start "$VMID" >/dev/null 2>&1 + msg_ok "Started ${APP_NAME} VM" + fi +} + +# ------------------------------------------------------------------------------ +# wait_for_vm_ip() +# +# Waits for the VM to obtain an IP address via qemu-guest-agent. +# Sets: VM_IP +# ------------------------------------------------------------------------------ +wait_for_vm_ip() { + VM_IP="" + if [ "$START_VM" != "yes" ]; then + return 0 + fi + + set +e + for i in {1..20}; do + VM_IP=$(qm guest cmd "$VMID" network-get-interfaces 2>/dev/null | + jq -r '.[] | select(.name != "lo") | ."ip-addresses"[]? | select(."ip-address-type" == "ipv4") | ."ip-address"' 2>/dev/null | + grep -v "^127\." | head -1) || true + [ -n "$VM_IP" ] && break + sleep 3 + done + set -e +} + +# ------------------------------------------------------------------------------ +# show_app_vm_summary() +# +# Displays the final summary with VM details and access information. +# ------------------------------------------------------------------------------ +show_app_vm_summary() { + echo "" + echo -e "${INFO}${BOLD}${GN}${APP_NAME} VM Configuration Summary:${CL}" + echo -e "${TAB}${DGN}VM ID: ${BGN}${VMID}${CL}" + echo -e "${TAB}${DGN}Hostname: ${BGN}${HN}${CL}" + echo -e "${TAB}${DGN}OS: ${BGN}${OS_DISPLAY}${CL}" + echo -e "${TAB}${DGN}Application: ${BGN}${APP_NAME}${CL}" + echo -e "${TAB}${DGN}CPU Cores: ${BGN}${CORE_COUNT}${CL}" + echo -e "${TAB}${DGN}RAM: ${BGN}${RAM_SIZE} MiB${CL}" + echo -e "${TAB}${DGN}Disk: ${BGN}${DISK_SIZE}${CL}" + [ -n "${VM_IP:-}" ] && echo -e "${TAB}${DGN}IP Address: ${BGN}${VM_IP}${CL}" + echo "" + echo -e "${TAB}${DGN}${APP_NAME}: ${BGN}Installing on first boot${CL}" + echo -e "${TAB}${YW} The application will be installed automatically after the VM boots.${CL}" + echo -e "${TAB}${YW} This may take several minutes depending on the application.${CL}" + echo -e "${TAB}${YW} Monitor progress: ${BL}cat /var/log/app-install.log${CL}" + echo "" + echo -e "${TAB}${DGN}Update later: ${BGN}bash /opt/community-scripts/update-app.sh${CL}" + echo "" + + if [ "$USE_CLOUD_INIT" = "yes" ] && declare -f display_cloud_init_info >/dev/null 2>&1; then + display_cloud_init_info "$VMID" "$HN" 2>/dev/null || true + fi +} + +# ------------------------------------------------------------------------------ +# build_app_vm() +# +# Main orchestration function. Executes the complete VM app deployment: +# 1. Ensure prerequisites (libguestfs-tools) +# 2. Download and cache cloud image +# 3. Customize image with app install script +# 4. Create and configure VM +# 5. Start VM and show summary +# ------------------------------------------------------------------------------ +build_app_vm() { + ensure_virt_customize + download_and_cache_image + customize_vm_image + create_app_vm + wait_for_vm_ip + show_app_vm_summary + + post_update_to_api "done" "none" + msg_ok "Completed successfully!\n" +} diff --git a/vm/app-deployer-vm.sh b/vm/app-deployer-vm.sh new file mode 100644 index 000000000..353a11896 --- /dev/null +++ b/vm/app-deployer-vm.sh @@ -0,0 +1,426 @@ +#!/usr/bin/env bash + +# Copyright (c) 2021-2026 community-scripts ORG +# Author: MickLesk (CanbiZ) +# License: MIT | https://github.com/community-scripts/ProxmoxVED/raw/main/LICENSE + +# ============================================================================== +# APP DEPLOYER VM - Deploy LXC Applications Inside a Virtual Machine +# ============================================================================== +# +# Creates a VM (Debian 12/13, Ubuntu 22.04/24.04) and deploys any LXC +# application inside it using the existing install scripts. +# +# Usage: +# bash app-deployer-vm.sh # Interactive mode +# APP=yamtrack bash app-deployer-vm.sh # Pre-select application +# +# Update the application later (inside the VM): +# bash /opt/community-scripts/update-app.sh +# +# ============================================================================== + +COMMUNITY_SCRIPTS_URL="${COMMUNITY_SCRIPTS_URL:-https://git.community-scripts.org/community-scripts/ProxmoxVED/raw/branch/main}" +source <(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/api.func") 2>/dev/null +source <(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/vm-core.func") 2>/dev/null +source <(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/cloud-init.func") 2>/dev/null || true +source <(curl -fsSL "$COMMUNITY_SCRIPTS_URL/misc/vm-app.func") 2>/dev/null +load_functions + +# ============================================================================== +# SCRIPT VARIABLES +# ============================================================================== +APP="${APP:-App Deployer}" +APP_TYPE="vm" +NSAPP="app-deployer-vm" + +GEN_MAC=02:$(openssl rand -hex 5 | awk '{print toupper($0)}' | sed 's/\(..\)/\1:/g; s/.$//') +RANDOM_UUID="$(cat /proc/sys/kernel/random/uuid)" +METHOD="" +DISK_SIZE="20G" +USE_CLOUD_INIT="no" +OS_TYPE="" +OS_VERSION="" +THIN="discard=on,ssd=1," +APP_INSTALL_SCRIPT="" + +# ============================================================================== +# ERROR HANDLING & CLEANUP +# ============================================================================== +set -e +trap 'error_handler $LINENO "$BASH_COMMAND"' ERR +trap cleanup EXIT +trap 'post_update_to_api "failed" "INTERRUPTED"' SIGINT +trap 'post_update_to_api "failed" "TERMINATED"' SIGTERM + +function error_handler() { + local exit_code="$?" + local line_number="$1" + local command="$2" + local error_message="${RD}[ERROR]${CL} in line ${RD}$line_number${CL}: exit code ${RD}$exit_code${CL}: while executing command ${YW}$command${CL}" + post_update_to_api "failed" "${command}" + echo -e "\n$error_message\n" + cleanup_vmid +} + +# ============================================================================== +# SETTINGS FUNCTIONS +# ============================================================================== +function default_settings() { + # App & OS selection (always interactive) + select_app "${PRE_APP:-}" + get_app_metadata + select_vm_os + + # SSH Key selection for Cloud-Init VMs + if [ "$USE_CLOUD_INIT" = "yes" ] && declare -f configure_cloudinit_ssh_keys >/dev/null 2>&1; then + configure_cloudinit_ssh_keys || true + fi + + # Use app-recommended resources (with reasonable VM minimums) + local min_disk=$((APP_DISK > 10 ? APP_DISK : 10)) + local min_ram=$((APP_RAM > 2048 ? APP_RAM : 2048)) + + VMID=$(get_valid_nextid) + FORMAT="" + MACHINE=" -machine q35" + DISK_CACHE="" + DISK_SIZE="${min_disk}G" + HN="${APP_INSTALL_SCRIPT}" + CPU_TYPE=" -cpu host" + CORE_COUNT="${APP_CPU}" + RAM_SIZE="${min_ram}" + BRG="vmbr0" + MAC="$GEN_MAC" + VLAN="" + MTU="" + START_VM="yes" + METHOD="default" + + # Update NSAPP and APP for descriptions + NSAPP="${APP_INSTALL_SCRIPT}-vm" + APP="${APP_NAME}" + + echo -e "${CONTAINERID}${BOLD}${DGN}Virtual Machine ID: ${BGN}${VMID}${CL}" + echo -e "${CONTAINERTYPE}${BOLD}${DGN}Machine Type: ${BGN}Q35 (Modern)${CL}" + echo -e "${DISKSIZE}${BOLD}${DGN}Disk Size: ${BGN}${DISK_SIZE}${CL}" + echo -e "${HOSTNAME}${BOLD}${DGN}Hostname: ${BGN}${HN}${CL}" + echo -e "${OS}${BOLD}${DGN}CPU Model: ${BGN}Host${CL}" + echo -e "${CPUCORE}${BOLD}${DGN}CPU Cores: ${BGN}${CORE_COUNT}${CL}" + echo -e "${RAMSIZE}${BOLD}${DGN}RAM Size: ${BGN}${RAM_SIZE}${CL}" + echo -e "${BRIDGE}${BOLD}${DGN}Bridge: ${BGN}${BRG}${CL}" + echo -e "${MACADDRESS}${BOLD}${DGN}MAC Address: ${BGN}${MAC}${CL}" + echo -e "${VLANTAG}${BOLD}${DGN}VLAN: ${BGN}Default${CL}" + echo -e "${DEFAULT}${BOLD}${DGN}Interface MTU Size: ${BGN}Default${CL}" + echo -e "${GATEWAY}${BOLD}${DGN}Start VM when completed: ${BGN}yes${CL}" + echo -e "${CREATING}${BOLD}${DGN}Creating ${APP_NAME} VM using the above settings${CL}" +} + +function advanced_settings() { + # App & OS selection (always interactive) + select_app "${PRE_APP:-}" + get_app_metadata + select_vm_os + + # SSH Key selection for Cloud-Init VMs + if [ "$USE_CLOUD_INIT" = "yes" ] && declare -f configure_cloudinit_ssh_keys >/dev/null 2>&1; then + configure_cloudinit_ssh_keys || true + fi + + METHOD="advanced" + + # Update NSAPP and APP for descriptions + NSAPP="${APP_INSTALL_SCRIPT}-vm" + APP="${APP_NAME}" + + # Use app-recommended resources as defaults + local default_disk=$((APP_DISK > 10 ? APP_DISK : 10)) + local default_ram=$((APP_RAM > 2048 ? APP_RAM : 2048)) + + [ -z "${VMID:-}" ] && VMID=$(get_valid_nextid) + + # VM ID + while true; do + if VMID=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set Virtual Machine ID" 8 58 $VMID --title "VIRTUAL MACHINE ID" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$VMID" ]; then + VMID=$(get_valid_nextid) + fi + if pct status "$VMID" &>/dev/null || qm status "$VMID" &>/dev/null; then + echo -e "${CROSS}${RD} ID $VMID is already in use${CL}" + sleep 2 + continue + fi + echo -e "${CONTAINERID}${BOLD}${DGN}Virtual Machine ID: ${BGN}$VMID${CL}" + break + else + exit_script + fi + done + + # Machine Type + if MACH=$(whiptail --backtitle "Proxmox VE Helper Scripts" --title "MACHINE TYPE" --radiolist --cancel-button Exit-Script "Choose Type" 10 58 2 \ + "q35" "Q35 (Modern, PCIe)" ON \ + "i440fx" "i440fx (Legacy, PCI)" OFF \ + 3>&1 1>&2 2>&3); then + if [ "$MACH" = "q35" ]; then + echo -e "${CONTAINERTYPE}${BOLD}${DGN}Machine Type: ${BGN}Q35 (Modern)${CL}" + FORMAT="" + MACHINE=" -machine q35" + else + echo -e "${CONTAINERTYPE}${BOLD}${DGN}Machine Type: ${BGN}i440fx (Legacy)${CL}" + FORMAT=",efitype=4m" + MACHINE="" + fi + else + exit_script + fi + + # Disk Size + if DISK_SIZE=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set Disk Size in GiB (App recommends: ${APP_DISK}G)" 8 58 "${default_disk}" --title "DISK SIZE" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + DISK_SIZE=$(echo "$DISK_SIZE" | tr -d ' ') + if [[ "$DISK_SIZE" =~ ^[0-9]+$ ]]; then + DISK_SIZE="${DISK_SIZE}G" + echo -e "${DISKSIZE}${BOLD}${DGN}Disk Size: ${BGN}$DISK_SIZE${CL}" + elif [[ "$DISK_SIZE" =~ ^[0-9]+G$ ]]; then + echo -e "${DISKSIZE}${BOLD}${DGN}Disk Size: ${BGN}$DISK_SIZE${CL}" + else + echo -e "${DISKSIZE}${BOLD}${RD}Invalid Disk Size. Please use a number (e.g., 10 or 10G).${CL}" + exit_script + fi + else + exit_script + fi + + # Disk Cache + if DISK_CACHE=$(whiptail --backtitle "Proxmox VE Helper Scripts" --title "DISK CACHE" --radiolist "Choose" --cancel-button Exit-Script 10 58 2 \ + "0" "None (Default)" ON \ + "1" "Write Through" OFF \ + 3>&1 1>&2 2>&3); then + if [ "$DISK_CACHE" = "1" ]; then + echo -e "${DISKSIZE}${BOLD}${DGN}Disk Cache: ${BGN}Write Through${CL}" + DISK_CACHE="cache=writethrough," + else + echo -e "${DISKSIZE}${BOLD}${DGN}Disk Cache: ${BGN}None${CL}" + DISK_CACHE="" + fi + else + exit_script + fi + + # Hostname + if VM_NAME=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set Hostname" 8 58 "${APP_INSTALL_SCRIPT}" --title "HOSTNAME" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$VM_NAME" ]; then + HN="${APP_INSTALL_SCRIPT}" + else + HN=$(echo "${VM_NAME,,}" | tr -d ' ') + fi + echo -e "${HOSTNAME}${BOLD}${DGN}Hostname: ${BGN}$HN${CL}" + else + exit_script + fi + + # CPU Model + if CPU_TYPE1=$(whiptail --backtitle "Proxmox VE Helper Scripts" --title "CPU MODEL" --radiolist "Choose" --cancel-button Exit-Script 10 58 2 \ + "1" "Host (Recommended)" ON \ + "0" "KVM64" OFF \ + 3>&1 1>&2 2>&3); then + if [ "$CPU_TYPE1" = "1" ]; then + echo -e "${OS}${BOLD}${DGN}CPU Model: ${BGN}Host${CL}" + CPU_TYPE=" -cpu host" + else + echo -e "${OS}${BOLD}${DGN}CPU Model: ${BGN}KVM64${CL}" + CPU_TYPE="" + fi + else + exit_script + fi + + # CPU Cores + if CORE_COUNT=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Allocate CPU Cores (App recommends: ${APP_CPU})" 8 58 "${APP_CPU}" --title "CORE COUNT" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$CORE_COUNT" ]; then + CORE_COUNT="${APP_CPU}" + fi + echo -e "${CPUCORE}${BOLD}${DGN}CPU Cores: ${BGN}$CORE_COUNT${CL}" + else + exit_script + fi + + # RAM Size + if RAM_SIZE=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Allocate RAM in MiB (App recommends: ${APP_RAM})" 8 58 "${default_ram}" --title "RAM" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$RAM_SIZE" ]; then + RAM_SIZE="${default_ram}" + fi + echo -e "${RAMSIZE}${BOLD}${DGN}RAM Size: ${BGN}$RAM_SIZE${CL}" + else + exit_script + fi + + # Bridge + if BRG=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set a Bridge" 8 58 vmbr0 --title "BRIDGE" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$BRG" ]; then + BRG="vmbr0" + fi + echo -e "${BRIDGE}${BOLD}${DGN}Bridge: ${BGN}$BRG${CL}" + else + exit_script + fi + + # MAC Address + if MAC1=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set a MAC Address" 8 58 $GEN_MAC --title "MAC ADDRESS" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$MAC1" ]; then + MAC="$GEN_MAC" + else + MAC="$MAC1" + fi + echo -e "${MACADDRESS}${BOLD}${DGN}MAC Address: ${BGN}$MAC${CL}" + else + exit_script + fi + + # VLAN + if VLAN1=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set a Vlan (leave blank for default)" 8 58 --title "VLAN" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$VLAN1" ]; then + VLAN1="Default" + VLAN="" + else + VLAN=",tag=$VLAN1" + fi + echo -e "${VLANTAG}${BOLD}${DGN}VLAN: ${BGN}$VLAN1${CL}" + else + exit_script + fi + + # MTU + if MTU1=$(whiptail --backtitle "Proxmox VE Helper Scripts" --inputbox "Set Interface MTU Size (leave blank for default)" 8 58 --title "MTU SIZE" --cancel-button Exit-Script 3>&1 1>&2 2>&3); then + if [ -z "$MTU1" ]; then + MTU1="Default" + MTU="" + else + MTU=",mtu=$MTU1" + fi + echo -e "${DEFAULT}${BOLD}${DGN}Interface MTU Size: ${BGN}$MTU1${CL}" + else + exit_script + fi + + # Start VM + if (whiptail --backtitle "Proxmox VE Helper Scripts" --title "START VIRTUAL MACHINE" --yesno "Start VM when completed?" 10 58); then + echo -e "${GATEWAY}${BOLD}${DGN}Start VM when completed: ${BGN}yes${CL}" + START_VM="yes" + else + echo -e "${GATEWAY}${BOLD}${DGN}Start VM when completed: ${BGN}no${CL}" + START_VM="no" + fi + + # Confirm + if (whiptail --backtitle "Proxmox VE Helper Scripts" --title "ADVANCED SETTINGS COMPLETE" --yesno "Ready to create a ${APP_NAME} VM?" --no-button Do-Over 10 58); then + echo -e "${CREATING}${BOLD}${DGN}Creating ${APP_NAME} VM using the above advanced settings${CL}" + else + header_info + echo -e "${ADVANCED}${BOLD}${RD}Using Advanced Settings${CL}" + advanced_settings + fi +} + +function start_script() { + if (whiptail --backtitle "Proxmox VE Helper Scripts" --title "SETTINGS" --yesno "Use Default Settings?" --no-button Advanced 10 58); then + header_info + echo -e "${DEFAULT}${BOLD}${BL}Using Default Settings${CL}" + default_settings + else + header_info + echo -e "${ADVANCED}${BOLD}${RD}Using Advanced Settings${CL}" + advanced_settings + fi +} + +# ============================================================================== +# STORAGE SELECTION (same pattern as docker-vm.sh) +# ============================================================================== +select_storage() { + msg_info "Validating Storage" + while read -r line; do + TAG=$(echo "$line" | awk '{print $1}') + TYPE=$(echo "$line" | awk '{printf "%-10s", $2}') + FREE=$(echo "$line" | numfmt --field 4-6 --from-unit=K --to=iec --format %.2f | awk '{printf( "%9sB", $6)}') + ITEM=" Type: $TYPE Free: $FREE " + OFFSET=2 + if [[ $((${#ITEM} + $OFFSET)) -gt ${MSG_MAX_LENGTH:-} ]]; then + MSG_MAX_LENGTH=$((${#ITEM} + $OFFSET)) + fi + STORAGE_MENU+=("$TAG" "$ITEM" "OFF") + done < <(pvesm status -content images | awk 'NR>1') + + VALID=$(pvesm status -content images | awk 'NR>1') + if [ -z "$VALID" ]; then + msg_error "Unable to detect a valid storage location." + exit + elif [ $((${#STORAGE_MENU[@]} / 3)) -eq 1 ]; then + STORAGE=${STORAGE_MENU[0]} + else + if [ -n "${SPINNER_PID:-}" ] && ps -p "$SPINNER_PID" >/dev/null 2>&1; then kill "$SPINNER_PID" >/dev/null; fi + printf "\e[?25h" + while [ -z "${STORAGE:+x}" ]; do + STORAGE=$(whiptail --backtitle "Proxmox VE Helper Scripts" --title "Storage Pools" --radiolist \ + "Which storage pool would you like to use for ${HN}?\nTo make a selection, use the Spacebar.\n" \ + 16 $(($MSG_MAX_LENGTH + 23)) 6 \ + "${STORAGE_MENU[@]}" 3>&1 1>&2 2>&3) + done + fi + msg_ok "Using ${CL}${BL}$STORAGE${CL} ${GN}for Storage Location." + msg_ok "Virtual Machine ID is ${CL}${BL}$VMID${CL}." + + # Detect storage type for disk format + STORAGE_TYPE=$(pvesm status -storage "$STORAGE" | awk 'NR>1 {print $2}') + case $STORAGE_TYPE in + nfs | dir) + DISK_EXT=".qcow2" + DISK_REF="$VMID/" + DISK_IMPORT="--format qcow2" + THIN="" + ;; + btrfs) + DISK_EXT=".raw" + DISK_REF="$VMID/" + DISK_IMPORT="--format raw" + FORMAT=",efitype=4m" + THIN="" + ;; + *) + DISK_EXT="" + DISK_REF="" + DISK_IMPORT="" + ;; + esac +} + +# ============================================================================== +# MAIN EXECUTION +# ============================================================================== +header_info + +check_root +arch_check +pve_check + +# Support pre-selecting app via environment variable +if [[ -n "${APP_SELECT:-}" ]]; then + PRE_APP="${APP_SELECT}" +else + PRE_APP="" +fi + +if whiptail --backtitle "Proxmox VE Helper Scripts" --title "App Deployer VM" --yesno \ + "This will create a new VM and deploy an LXC application inside it.\n\nSupported OS: Debian 12/13, Ubuntu 22.04/24.04\n\nProceed?" 14 68; then + : +else + header_info && echo -e "${CROSS}${RD}User exited script${CL}\n" && exit +fi + +start_script +post_to_api_vm + +select_storage + +# Build the App VM +build_app_vm