#!/usr/bin/env bash
# shellcheck shell=bash
set -Eeuo pipefail
IFS=$'\n\t'

RUNDIR=${ROOTAUFS4_SAVEFILE_RUNDIR:-/run/rootaufs4-savefile}
WORKDIR=
PARTIALS=()
PARTIAL_DIRS=()
MOUNTS=()
LOOPS=()
ROLLBACK_TARGET=
ROLLBACK_BACKUP=

progress() { printf 'progress\t%s\t%s\n' "$1" "$2"; }
result() { printf 'result'; printf '\t%s' "$@"; printf '\n'; }
die() { printf 'rootaufs4-savefile-helper: %s\n' "$*" >&2; exit 1; }

cleanup() {
    local status=$? item
    for ((item=${#MOUNTS[@]} - 1; item >= 0; item--)); do
        if mountpoint -q "${MOUNTS[item]}"; then umount "${MOUNTS[item]}" || true; fi
    done
    for ((item=${#LOOPS[@]} - 1; item >= 0; item--)); do losetup -d "${LOOPS[item]}" || true; done
    for item in "${PARTIALS[@]}"; do rm -f -- "$item"; done
    for item in "${PARTIAL_DIRS[@]}"; do rm -rf -- "$item"; done
    if [[ -n $ROLLBACK_BACKUP && -e $ROLLBACK_BACKUP && ! -e $ROLLBACK_TARGET ]]; then
        mv -- "$ROLLBACK_BACKUP" "$ROLLBACK_TARGET" || true
    fi
    [[ -n $WORKDIR ]] && rm -rf -- "$WORKDIR"
    exit "$status"
}
trap cleanup EXIT HUP INT TERM

require_root() { [[ ${ROOTAUFS4_SAVEFILE_TESTING:-0} = 1 || $EUID -eq 0 ]] || die 'must be run as root'; }
init_lock() { install -d -m 700 "$RUNDIR"; exec 9>"$RUNDIR/helper.lock"; flock -n 9 || die 'another save operation is in progress'; }
absolute_path() { [[ $1 == /* && $1 != *$'\n'* && $1 != *$'\r'* ]]; }

existing_path() {
    absolute_path "$1" || die 'path must be absolute'
    [[ -e $1 && ! -L $1 ]] || die "unsafe or missing path: $1"
    realpath -e -- "$1"
}

# All existing parent components are checked before creating an output.  The
# final file itself must not be a symlink either.
output_path() {
    local path=$1 parent base part current=/
    absolute_path "$path" || die 'path must be absolute'
    [[ $path != / && $path != */. && $path != */.. && $path != *'/../'* && $path != *'//'* ]] || die 'unsafe output path'
    [[ ! -L $path ]] || die 'output must not be a symlink'
    parent=${path%/*}; base=${path##*/}; [[ -n $base && $base != . && $base != .. ]] || die 'unsafe output name'
    IFS=/ read -r -a _parts <<< "${parent#/}"
    for part in "${_parts[@]}"; do
        [[ -n $part ]] || continue
        current+="$part"; [[ -d $current && ! -L $current ]] || die "unsafe output directory: $current"; current+=/
    done
    parent=$(realpath -e -- "$parent")
    printf '%s/%s\n' "$parent" "$base"
}

# File containers and PFS modules work on removable FAT/exFAT/NTFS media.
# A folder save needs ownership, permissions and atomic directory rename, so
# it is deliberately restricted to local POSIX filesystems.
safe_storage() {
    local path=$1 kind=$2 fs
    fs=$(findmnt -no FSTYPE -T "$path" 2>/dev/null || true)
    [[ -n $fs && -w $path ]] || die "destination is not writable: $path"
    case $fs in aufs|overlay|tmpfs) die "unsafe live destination filesystem: $fs";; esac
    if [[ $kind == folder ]]; then
        case $fs in ext2|ext3|ext4|xfs|btrfs|f2fs|zfs) ;; *) die "folder destination requires POSIX filesystem: $fs";; esac
    fi
}

default_source() {
    if [[ ${ROOTAUFS4_SAVEFILE_TESTING:-0} = 1 && -n ${ROOTAUFS4_SAVEFILE_TEST_SOURCE:-} && -d $ROOTAUFS4_SAVEFILE_TEST_SOURCE ]]; then
        printf '%s\n' "$ROOTAUFS4_SAVEFILE_TEST_SOURCE"; return
    fi
    [[ -d /run/archroot/live/memory/changes ]] && printf '%s\n' /run/archroot/live/memory/changes && return
    [[ -d /mnt/live/memory/changes ]] && printf '%s\n' /mnt/live/memory/changes && return
    die 'live changes directory was not found'
}
default_directory() {
    local cmdline_file=${ROOTAUFS4_SAVEFILE_CMDLINE_FILE:-/proc/cmdline}
    local media=${ROOTAUFS4_SAVEFILE_MEDIA_ROOT:-/run/archroot/root_ro}
    local cmdline dir part
    [[ -r $cmdline_file && -d $media ]] || return 1
    IFS= read -r cmdline <"$cmdline_file" || true
    [[ $cmdline =~ (^|[[:space:]])dir=([^[:space:]]+) ]] || return 1
    dir=${BASH_REMATCH[2]}
    while [[ $dir == /* ]]; do dir=${dir#/}; done
    while [[ $dir == */ ]]; do dir=${dir%/}; done
    [[ -n $dir && $dir != *$'\n'* && $dir != *$'\r'* ]] || return 1
    IFS=/ read -r -a _dir_parts <<< "$dir"
    for part in "${_dir_parts[@]}"; do
        [[ $part != .. ]] || return 1
    done
    [[ -d $media/$dir ]] || return 1
    printf '%s/%s\n' "$media" "$dir"
}

default_stamp() {
    local date=${ROOTAUFS4_SAVEFILE_DATE:-$(date +%Y%m%d)}
    local host=${ROOTAUFS4_SAVEFILE_HOST:-$(hostname -s)}
    host=$(tr -cd '[:alnum:]._-' <<<"$host")
    printf '%s\t%s\n' "$date" "${host:-host}"
}

default_module() {
    local directory stamp date host
    directory=$(default_directory) || return 1
    stamp=$(default_stamp); date=${stamp%%$'\t'*}; host=${stamp#*$'\t'}
    printf '%s/base/090-save-%s-%s.pfs\n' "$directory" "$date" "$host"
}

default_container() {
    local directory stamp date host
    directory=$(default_directory) || return 1
    stamp=$(default_stamp); date=${stamp%%$'\t'*}; host=${stamp#*$'\t'}
    printf '%s/save-%s-%s.dat\n' "$directory" "$date" "$host"
}

valid_user_name() { [[ $1 =~ ^[a-z_][a-z0-9_-]*\$?$ ]]; }

caller_user() {
    local uid entry user
    for uid in "${PKEXEC_UID:-}" "${SUDO_UID:-}"; do
        [[ $uid =~ ^[0-9]+$ ]] || continue
        entry=$(getent passwd "$uid" 2>/dev/null || true)
        user=${entry%%:*}
        valid_user_name "$user" && { printf '%s\n' "$user"; return; }
    done
    user=${USER:-root}
    valid_user_name "$user" && { printf '%s\n' "$user"; return; }
    printf '%s\n' root
}

changes_size() {
    local mode=$1 source=$2 user=${3:-} item name bytes total=0
    local -a items=()
    shopt -s dotglob nullglob
    case $mode in
        full)
            for item in "$source"/*; do
                name=${item##*/}
                case $name in dev|proc|sys|run|tmp|mnt) continue;; esac
                items+=("$item")
            done
            ;;
        settings)
            for name in etc "home/$user" root; do
                [[ -e $source/$name ]] && items+=("$source/$name")
            done
            ;;
        *) die 'mode must be full or settings' ;;
    esac
    shopt -u dotglob nullglob
    ((${#items[@]})) || { printf '0\n'; return; }
    while IFS=$'\t ' read -r bytes _; do
        [[ $bytes =~ ^[0-9]+$ ]] && ((total += bytes))
    done < <(du -sb -- "${items[@]}" 2>/dev/null || true)
    printf '%s\n' "$total"
}

copy_changes() {
    local mode=$1 source=$2 destination=$3 user=$4 item name parent
    mkdir -p -- "$destination"; shopt -s dotglob nullglob
    case $mode in
        full) for item in "$source"/*; do name=${item##*/}; case $name in dev|proc|sys|run|tmp|mnt) continue;; esac; cp -a -- "$item" "$destination/"; done ;;
        settings)
            valid_user_name "$user" || die 'invalid user name'
            for name in etc "home/$user" root; do
                [[ -e $source/$name ]] || continue
                parent=${name%/*}; [[ $parent == "$name" ]] && parent=.
                mkdir -p -- "$destination/$parent"; cp -a -- "$source/$name" "$destination/$parent/"
            done ;;
        *) die 'mode must be full or settings' ;;
    esac
    shopt -u dotglob nullglob
}

changes_argument() {
    local target mount
    target=$(realpath -e -- "$1"); mount=$(findmnt -no TARGET -T "$target" 2>/dev/null || true)
    [[ -n $mount ]] || { printf '%s\n' "$target"; return; }
    mount=$(realpath -e -- "$mount")
    [[ $target == "$mount" ]] && { printf '/\n'; return; }
    [[ $target == "$mount"/* ]] && { printf '%s\n' "${target#"$mount"/}"; return; }
    printf '%s\n' "$target"
}

preview_changes() {
    local path=$1 parent base part current=/ target mount
    absolute_path "$path" || die 'path must be absolute'
    [[ $path != / && $path != */. && $path != */.. && $path != *'/../'* && $path != *'//'* ]] || die 'unsafe path'
    parent=${path%/*}; base=${path##*/}; [[ -n $base && $base != . && $base != .. ]] || die 'unsafe path name'
    IFS=/ read -r -a _parts <<< "${parent#/}"
    for part in "${_parts[@]}"; do
        [[ -n $part ]] || continue
        current+="$part"; [[ -d $current && ! -L $current ]] || die "unsafe or missing path parent: $current"; current+=/
    done
    parent=$(realpath -e -- "$parent")
    if [[ -e $path ]]; then
        [[ ! -L $path ]] || die 'path must not be a symlink'
        target=$(realpath -e -- "$path")
    else
        target="$parent/$base"
    fi
    mount=$(findmnt -no TARGET -T "$target" 2>/dev/null || true)
    [[ -n $mount ]] || { result "$target" "$target"; return; }
    mount=$(realpath -e -- "$mount")
    if [[ $target == "$mount" ]]; then
        result / "$target"
    elif [[ $target == "$mount"/* ]]; then
        result "${target#"$mount"/}" "$target"
    else
        result "$target" "$target"
    fi
}

format_container() {
    case $2 in ext4) mkfs.ext4 -F -q "$1";; ext2) mkfs.ext2 -F -q "$1";; xfs) mkfs.xfs -f -q "$1";; *) die 'filesystem must be ext4, ext2, or xfs';; esac
}
image_partial() { printf '%s.partial.%s\n' "$1" "$$"; }
create_image() {
    local partial=$1 size=$2 fs=$3
    [[ $size =~ ^[1-9][0-9]*$ ]] || die 'SIZE_MIB must be a positive integer'
    PARTIALS+=("$partial"); truncate -s "$((size * 1024 * 1024))" "$partial"; format_container "$partial" "$fs"
}
attach_image() {
    local image=$1 options=$2 mountdir=$3 loop
    local -a loop_options=()
    [[ -n $options ]] && loop_options=("$options")
    loop=$(losetup --find --show "${loop_options[@]}" "$image"); LOOPS+=("$loop")
    mkdir -p -- "$mountdir"
    if [[ $options == --read-only ]]; then
        mount -o ro "$loop" "$mountdir"
    else
        mount "$loop" "$mountdir"
    fi
    MOUNTS+=("$mountdir")
}
detach_all_images() {
    local item
    for ((item=${#MOUNTS[@]} - 1; item >= 0; item--)); do umount "${MOUNTS[item]}"; done; MOUNTS=()
    for ((item=${#LOOPS[@]} - 1; item >= 0; item--)); do losetup -d "${LOOPS[item]}"; done; LOOPS=()
}
used_with_reserve() {
    local tree=$1 bytes=$2 usage
    usage=$(du -sb "$tree"); usage=${usage%%[[:space:]]*}
    (( usage + 16 * 1024 * 1024 <= bytes )) || die 'container size does not leave a 16 MiB reserve'
}

create_container() {
    local output size fs partial
    output=$(output_path "$1"); size=$2; fs=$3; [[ ! -e $output ]] || die 'output already exists'
    safe_storage "${output%/*}" file; partial=$(image_partial "$output"); progress 10 'creating sparse container'
    create_image "$partial" "$size" "$fs"; mv -f -- "$partial" "$output"; PARTIALS=()
    progress 100 'container created'; result "$(changes_argument "$output")" "$output"
}

save_module() {
    local mode=$1 source output user compression=${5:-xz} stage partial
    source=$(existing_path "$2"); output=$(output_path "$3"); user=$4
    [[ $output == *.pfs ]] || die 'module output must end in .pfs'; [[ ! -e $output ]] || die 'output already exists'
    case $compression in xz|zstd|lz4|gzip) ;; *) die 'compression must be xz, zstd, lz4, or gzip' ;; esac
    safe_storage "${output%/*}" file; WORKDIR=$(mktemp -d "$RUNDIR/module.XXXXXX"); stage="$WORKDIR/changes"; partial="${output%.pfs}.partial.$$.pfs"; PARTIALS+=("$partial")
    progress 10 'copying changes'; copy_changes "$mode" "$source" "$stage" "$user"; progress -1 'Создание PFS-модуля'
    case $compression in
        xz) mkpfs -l "$stage" -o "$partial" ;;
        lz4) mkpfs -l "$stage" -o "$partial" -f ;;
        gzip) mkpfs -l "$stage" -o "$partial" --mksqfs -comp gzip ;;
        zstd) mkpfs -l "$stage" -o "$partial" --mksqfs -comp zstd -Xcompression-level 15 ;;
        *) die 'compression must be xz, zstd, lz4, or gzip' ;;
    esac
    mv -f -- "$partial" "$output"; PARTIALS=(); rm -rf -- "$WORKDIR"; WORKDIR=
    progress 100 'module saved'; result '' "$output"
}

save_folder() {
    local mode=$1 source dest action=$4 user=$5 target stage old
    source=$(existing_path "$2"); dest=$(output_path "$3"); [[ ! -e $dest || -d $dest ]] || die 'DEST is not a directory'
    safe_storage "${dest%/*}" folder; mkdir -p -- "$dest"; [[ ! -L $dest ]] || die 'DEST must not be a symlink'
    [[ $action == merge || $action == replace ]] || die 'MODE_ACTION must be merge or replace'
    target="$dest/changes"; stage="$dest/.changes.partial.$$"; old="$dest/.changes.backup.$$"
    [[ ! -e $stage && ! -e $old ]] || die 'stale folder save transaction exists'
    PARTIAL_DIRS+=("$stage"); progress 10 'staging changes'
    [[ $action == merge && -d $target ]] && cp -a -- "$target" "$stage"
    copy_changes "$mode" "$source" "$stage" "$user"
    ROLLBACK_TARGET=$target; ROLLBACK_BACKUP=$old
    [[ ! -e $target ]] || mv -- "$target" "$old"; mv -- "$stage" "$target"
    PARTIAL_DIRS=(); rm -rf -- "$old"; ROLLBACK_TARGET=; ROLLBACK_BACKUP=
    progress 100 'folder saved'; result "$(changes_argument "$dest")" "$target"
}

container_mounted() { findmnt -rn -S "$1" >/dev/null 2>&1 || losetup -j "$1" | grep -q .; }

save_container() {
    local mode=$1 source output size fs action user partial old_fs old_size old_mount new_mount
    source=$(existing_path "$2"); output=$(output_path "$3"); size=$4; fs=$5; action=$6; user=$7
    [[ -d $source ]] || die 'container changes source must be a directory'
    [[ $source != "$output" ]] || die 'source and output must differ'
    [[ $action == merge || $action == replace ]] || die 'ACTION must be merge or replace'; safe_storage "${output%/*}" file
    if [[ -e $output ]]; then
        [[ -f $output && ! -L $output ]] || die 'existing container must be a regular file'
        if container_mounted "$output"; then die 'container is active'; fi
        old_fs=$(blkid -o value -s TYPE "$output" 2>/dev/null || true); [[ -n $old_fs ]] || die 'cannot detect container filesystem'
        old_size=$(( ($(stat -c %s "$output") + 1048575) / 1048576 ))
        if [[ $size == 0 ]]; then size=$old_size; fs=$old_fs; elif [[ $fs == auto ]]; then fs=$old_fs; fi
    fi
    [[ $fs == ext4 || $fs == ext2 || $fs == xfs ]] || die 'filesystem must be ext4, ext2, or xfs'
    [[ $size =~ ^[1-9][0-9]*$ ]] || die 'SIZE_MIB must be positive (or 0 for an existing container)'
    WORKDIR=$(mktemp -d "$RUNDIR/container.XXXXXX"); partial=$(image_partial "$output"); create_image "$partial" "$size" "$fs"
    new_mount="$WORKDIR/new"; attach_image "$partial" '' "$new_mount"
    if [[ -e $output && $action == merge ]]; then old_mount="$WORKDIR/old"; attach_image "$output" '--read-only' "$old_mount"; used_with_reserve "$old_mount" "$((size * 1048576))"; cp -a -- "$old_mount/." "$new_mount/"; fi
    copy_changes "$mode" "$source" "$new_mount" "$user"; used_with_reserve "$new_mount" "$((size * 1048576))"; sync; detach_all_images
    mv -f -- "$partial" "$output"
    PARTIALS=(); rm -rf -- "$WORKDIR"; WORKDIR=
    progress 100 'container saved'; result "$(changes_argument "$output")" "$output"
}

resize_container() {
    local source output size delete_source fs partial src_mount dst_mount
    source=$(existing_path "$1"); output=$(output_path "$2"); size=$3; delete_source=$4
    [[ -f $source && ! -L $source ]] || die 'resize source must be a regular file'
    [[ $source != "$output" ]] || die 'source and output must differ'
    [[ $size =~ ^[1-9][0-9]*$ && ! -e $output ]] || die 'invalid resize arguments'
    container_mounted "$source" && die 'container is active'
    safe_storage "${output%/*}" file; fs=$(blkid -o value -s TYPE "$source" 2>/dev/null || true); [[ -n $fs ]] || die 'cannot detect container filesystem'
    WORKDIR=$(mktemp -d "$RUNDIR/resize.XXXXXX"); partial=$(image_partial "$output"); create_image "$partial" "$size" "$fs"
    src_mount="$WORKDIR/src"; dst_mount="$WORKDIR/dst"; attach_image "$source" '--read-only' "$src_mount"; used_with_reserve "$src_mount" "$((size * 1048576))"
    attach_image "$partial" '' "$dst_mount"; cp -a -- "$src_mount/." "$dst_mount/"; sync; detach_all_images
    mv -- "$partial" "$output"; PARTIALS=(); rm -rf -- "$WORKDIR"; WORKDIR=
    [[ $delete_source == 1 || $delete_source == true ]] && rm -f -- "$source"
    progress 100 'container resized'; result "$(changes_argument "$output")" "$output"
}

case ${1:-} in
    probe)
        source=$(default_source); module=$(default_module 2>/dev/null || true); directory=$(default_directory 2>/dev/null || true); container=$(default_container 2>/dev/null || true); user=$(caller_user)
        result "$source" "$module" "$(changes_size full "$source")" "$(changes_size settings "$source" "$user")" "$directory" "$container"
        exit 0
        ;;
    preview-changes)
        [[ $# -eq 2 ]] || die 'usage: preview-changes PATH'
        preview_changes "$2"
        exit 0
        ;;
esac
require_root; init_lock
case ${1:-} in
    save-module) [[ $# -eq 5 || $# -eq 6 ]] || die 'usage: save-module MODE SOURCE OUTPUT USER [COMPRESSION]'; save_module "$2" "$3" "$4" "$5" "${6:-xz}" ;;
    save-folder) [[ $# -eq 6 ]] || die 'usage: save-folder MODE SOURCE DEST MODE_ACTION USER'; save_folder "$2" "$3" "$4" "$5" "$6" ;;
    save-container) [[ $# -eq 8 ]] || die 'usage: save-container MODE SOURCE OUTPUT SIZE_MIB FS ACTION USER'; save_container "$2" "$3" "$4" "$5" "$6" "$7" "$8" ;;
    create-container) [[ $# -eq 4 ]] || die 'usage: create-container OUTPUT SIZE_MIB FS'; create_container "$2" "$3" "$4" ;;
    resize-container) [[ $# -eq 5 ]] || die 'usage: resize-container SOURCE OUTPUT SIZE_MIB DELETE_SOURCE'; resize_container "$2" "$3" "$4" "$5" ;;
    *) die 'unknown command' ;;
esac
