#!/bin/bash
# **********************************************************************
# * Privileged helper for file-rewind, started through pkexec.
# *
# * It does NOT run arbitrary commands. It performs a fixed set of
# * checkpoint operations on system folders, validates every argument and
# * builds every command itself:
# *
# *   git      STORE FOLDER SUBCOMMAND [OPTIONS...] [-- PATHS...]
# *   folder-state STORE FOLDER          directory (central or in-folder store), or missing
# *   probe    STORE FOLDER RELPATH...   type of each path (never through a symlink)
# *   walk     STORE FOLDER RELPATH      everything inside a folder
# *   init     STORE FOLDER              create a new store (ignore rules on stdin)
# *   mkdir    STORE FOLDER              recreate a deleted folder
# *   delete   STORE FOLDER              delete all checkpoints of FOLDER
# *   lock     STORE FOLDER              take the store lock for the calling program
# *   unlock   STORE FOLDER              release it
# *   schedule STORE FOLDER off|hourly|daily|weekly|startup
# *   clean-schedules                   drop jobs older versions wrote (run on install/upgrade)
# *   metadata        STORE FOLDER      mode, owner and type of FOLDER and everything in it
# *   record-metadata STORE FOLDER -- [PATH...]
# *   apply-metadata  STORE FOLDER TARGET SAFETY whole|files -- [PATH...]
# *                   save / restore file permissions; both run the installed program as root,
# *                   which derives them from the trusted store and the folder (never the caller)
# *   check-restore   STORE FOLDER TARGET SAFETY whole|files -- [PATH...]
# *                   before a restore: refuse if a file couldn't be created privately
# *
# * Only the exact git command lines the program produces are accepted (see GIT_FORMS).
# *
# * STORE is /var/lib/file-rewind/NAME.git (bound to FOLDER by its
# * configuration) or FOLDER/.git (made by older versions).
# *
# * Trust rule: git reads its configuration from the store, and that can make
# * it run programs. So the store, the folder, and every folder above them must
# * be changeable by root only: no symlinks, owned by root, not writable by
# * group or others (a sticky folder such as /tmp is fine). Anything else is
# * refused before git or the file system is touched.
# **********************************************************************
set -u
umask 077 # whatever is created (restored files, stores) starts private
export LC_ALL=C
export GIT_EDITOR=false GIT_SEQUENCE_EDITOR=false GIT_PAGER=cat PAGER=cat GIT_TERMINAL_PROMPT=0
PATH=/usr/sbin:/usr/bin:/sbin:/bin

GIT=/usr/bin/git
FIND=/usr/bin/find
SYSTEM_STORE=/var/lib/file-rewind
CRON_FILE=/etc/cron.d/file-rewind
PROGRAM=/usr/bin/file-rewind
TRUSTED_UID=0
LOCK_WAIT=20 # seconds

# Locations can be redirected only for tests: not as root and not through pkexec
# (pkexec clears the environment, so a caller can't set these)
if [[ -z ${PKEXEC_UID:-} && $(id -u) != 0 && -n ${FILE_REWIND_HELPER_TEST_ROOT:-} ]]; then
    SYSTEM_STORE=$FILE_REWIND_HELPER_TEST_ROOT/var-lib-file-rewind
    CRON_FILE=$FILE_REWIND_HELPER_TEST_ROOT/cron.d/file-rewind
    PROGRAM=$FILE_REWIND_HELPER_TEST_ROOT/file-rewind
    TRUSTED_UID=$(id -u)
    LOCK_WAIT=${FILE_REWIND_HELPER_TEST_LOCK_WAIT:-$LOCK_WAIT}
fi

die() {
    printf 'file-rewind helper: %s\n' "$*" >&2
    exit 3
}

# Absolute, normalised path: no "." or ".." parts, no "//", no trailing "/", no line break
valid_folder() {
    local p=$1
    [[ $p == /?* && $p != */ && $p != *//* && $p != *$'\n'* ]] || return 1
    [[ /$p/ != */./* && /$p/ != */../* ]]
}

# Path inside the folder: relative, no "." or ".." parts
valid_relative() {
    local p=$1
    [[ -n $p && $p != /* && $p != */ && $p != *//* ]] || return 1
    [[ /$p/ != */./* && /$p/ != */../* ]]
}

is_revision() {
    [[ $1 =~ ^[0-9a-f]{40}$ || $1 == HEAD ]]
}

# One existing entry that only root can change, checked without following symlinks: owned by
# root, not writable by group or others. A sticky folder (like /tmp) is accepted as a parent,
# because only an entry's owner can rename it; a sticky file gets no such exception.
trusted_entry() { # PATH [ancestor]: only an ancestor folder may be sticky instead of private
    local uid mode
    [[ -e $1 && ! -L $1 ]] || return 1
    read -r uid mode < <(stat -c '%u %a' -- "$1") || return 1
    [[ $uid == 0 || $uid == "$TRUSTED_UID" ]] || return 1
    mode=$((8#$mode))
    ((!(mode & 8#022))) && return 0
    [[ ${2:-} == ancestor && -d $1 ]] && ((mode & 8#1000))
}

# A regular file only root can change
trusted_file() {
    [[ -f $1 ]] && trusted_entry "$1"
}

# Calls the function named $1 for each leading path of $2 ("a", "a/b", ...). Splits on "/" only,
# so names containing line breaks are handled whole.
for_each_prefix() {
    local callback=$1 rest=$2 current=""
    while [[ -n $rest ]]; do
        if [[ $rest == */* ]]; then
            current+=${current:+/}${rest%%/*}
            rest=${rest#*/}
        else
            current+=${current:+/}$rest
            rest=""
        fi
        "$callback" "$current" || return 1
    done
}

TRUSTED_PATH_TARGET=""
trusted_absolute_prefix() {
    if [[ /$1 == "$TRUSTED_PATH_TARGET" ]]; then
        trusted_entry "/$1" # the entry itself: private, even if it is a folder
    else
        trusted_entry "/$1" ancestor
    fi
}

# Every component of an existing absolute path, from / down. Folders above it may be sticky
# (like /tmp); the entry itself must be private.
trusted_path() {
    TRUSTED_PATH_TARGET=$1
    if [[ $1 == / ]]; then
        trusted_entry /
    else
        trusted_entry / ancestor && for_each_prefix trusted_absolute_prefix "${1#/}"
    fi
}

# The deepest existing folder above (or at) a path, for a path that may not exist yet
existing_ancestor() {
    local p=$1
    while [[ ! -e $p && ! -L $p ]]; do
        p=$(dirname -- "$p")
    done
    printf '%s' "$p"
}

# Sets STORE, FOLDER and KIND
select_repository() {
    STORE=$1
    FOLDER=$2
    valid_folder "$FOLDER" || die "invalid folder"
    # These are the same areas excluded by Git::folderEligibilityError. Helper
    # paths must already be absolute and normalised, and trusted_path rejects links.
    case "$FOLDER/" in
    /run/media/?*/?*/) ;; # /run/media/<user>/<drive> and its contents
    /proc/*|/sys/*|/dev/*|/run/*|/tmp/*) die "checkpoints cannot be made of this folder" ;;
    esac
    if [[ $STORE == "$FOLDER/.git" ]]; then
        KIND=infolder
    elif [[ $STORE =~ ^${SYSTEM_STORE//./\\.}/[A-Za-z0-9._-]+\.git$ ]]; then
        KIND=central
    else
        die "invalid store"
    fi
    # The folder (or, if it was deleted, what exists above it) must be root's alone
    trusted_path "$(existing_ancestor "$FOLDER")" || die "the folder can be changed by other users"
}

# An existing store whose configuration only root can have written, bound to FOLDER
require_trusted_store() {
    [[ -d $STORE ]] || die "no checkpoints for this folder"
    trusted_path "$STORE" || die "the checkpoint store can be changed by other users"
    trusted_file "$STORE/config" || die "the checkpoint store's configuration can be changed by other users"
    # No indirection to other repositories, settings or object stores
    local other
    for other in config.worktree commondir gitdir objects/info/alternates objects/info/http-alternates; do
        if [[ -e $STORE/$other || -L $STORE/$other ]]; then
            die "unexpected layout in the checkpoint store"
        fi
    done
    # Included configuration files could live anywhere
    if "$GIT" config --file "$STORE/config" --get-regexp '^include(if)?\.' >/dev/null; then
        die "unexpected configuration in the checkpoint store"
    fi
    if [[ $KIND == central ]]; then
        # Byte-exact comparison (command substitution would drop trailing line breaks)
        "$GIT" config --file "$STORE/config" -z --get file-rewind.folder | cmp -s - <(printf '%s\0' "$FOLDER") \
            || die "the checkpoint store belongs to another folder"
    fi
}

make_private_store_root() {
    if [[ -e $SYSTEM_STORE || -L $SYSTEM_STORE ]]; then
        # Never change the permissions of something that isn't root's own folder
        if [[ ! -d $SYSTEM_STORE ]] || ! trusted_path "$SYSTEM_STORE"; then
            return 1
        fi
        chmod 0700 -- "$SYSTEM_STORE"
    else
        trusted_path "$(dirname -- "$SYSTEM_STORE")" && mkdir -m 0700 -- "$SYSTEM_STORE"
    fi
}

make_lock_folder() {
    if [[ -e $SYSTEM_STORE/locks || -L $SYSTEM_STORE/locks ]]; then
        [[ -d $SYSTEM_STORE/locks ]] && trusted_entry "$SYSTEM_STORE/locks"
    else
        mkdir -m 0700 -- "$SYSTEM_STORE/locks"
    fi
}

identity() { # name and e-mail of the user who asked for the operation
    local login=root name="" entry
    if [[ -n ${PKEXEC_UID:-} ]]; then
        entry=$(getent passwd "$PKEXEC_UID") || true
        if [[ -n $entry ]]; then
            login=${entry%%:*}
            name=$(cut -d: -f5 <<<"$entry")
            name=${name%%,*}
        fi
    fi
    NAME=${name:-$login}
    EMAIL="$login@$(hostname)"
}

git_command() {
    identity
    GITCMD=("$GIT" --no-pager -c "safe.directory=*" -c core.quotepath=off -c core.hooksPath=/dev/null
        -c core.editor=false -c sequence.editor=false -c core.pager=cat -c core.fsmonitor=false
        -c commit.gpgsign=false -c advice.addEmbeddedRepo=false -c submodule.recurse=false -c "user.name=$NAME" -c "user.email=$EMAIL"
        --no-optional-locks --literal-pathspecs "--git-dir=$STORE")
    if [[ $KIND == central ]]; then
        GITCMD+=(-c core.excludesFile=/dev/null)
    fi
    if [[ -d $FOLDER ]]; then
        GITCMD+=("--work-tree=$FOLDER" -C "$FOLDER")
    else
        # A deleted folder: only commands that don't touch a work tree (op_git checks). git rejects a
        # missing work tree (also the one in the store's settings), so they get an empty, private
        # folder of the central store, which is never removed
        [[ $KIND == central ]] || die "the folder does not exist"
        local empty=$SYSTEM_STORE/empty
        if [[ ! -e $empty && ! -L $empty ]]; then
            mkdir -m 0700 -- "$empty" || die "cannot create an empty folder"
        fi
        if [[ ! -d $empty ]] || ! trusted_entry "$empty"; then
            die "unexpected empty folder"
        fi
        GITCMD+=("--work-tree=$empty")
    fi
}

# The exact command lines the program uses. The subcommand must be one of the known words; each
# following argument before "--" is reduced to a placeholder ({REV}, {SRC}, {BLOB}, {FMT_C},
# {FMT_H}; braces can't occur in a kept argument) or kept as is. The result must be one of these
# forms, and the number of paths after "--" must fit: none, one, some (1 or more), any.
LOG_FORMAT_CHECKPOINTS='--format=%H%x1f%at%x1f%s%x1f%(trailers:key=File-Rewind-Kind,valueonly,separator=)'
LOG_FORMAT_HISTORY='--format=%x1e%H%x1f%at%x1f%s%x1f%(trailers:key=File-Rewind-Kind,valueonly,separator=)%x1f'
git_form_arity() {
    case $1 in
    "rev-parse --git-dir" | "rev-parse -q --verify {REV}") echo none ;;
    "log -z --no-show-signature {FMT_C}") echo none ;;
    "log --no-show-signature --no-renames --name-status {FMT_H} --") echo one ;;
    "log --no-show-signature --no-renames --name-only -z --format=") echo none ;;
    "diff --name-status -z --no-renames {REV}") echo none ;;
    "diff --no-color --no-ext-diff --no-textconv --no-renames --src-prefix=a/ --dst-prefix=b/ {REV} --") echo some ;;
    "diff --no-color --no-ext-diff --no-textconv --no-renames --src-prefix=a/ --dst-prefix=b/ --diff-filter=A {REV} --") echo any ;;
    "diff --cached --quiet") echo none ;;
    "diff --cached --quiet --") echo any ;;
    "ls-files -z --others --exclude-standard" | "ls-files -z --cached") echo none ;;
    "ls-tree -r -z --name-only {REV}") echo none ;;
    "ls-tree -r -z --name-only {REV} --") echo any ;;
    "ls-tree -r -z {REV} --") echo any ;;
    "cat-file blob {BLOB}" | "count-objects -v") echo none ;;
    "add -A --ignore-errors --" | "add -A --no-ignore-errors --") echo some ;;
    "commit -q --no-verify --cleanup=whitespace -F -") echo none ;;
    "commit -q --no-verify --cleanup=whitespace -F - --allow-empty") echo none ;;
    "commit -q --no-verify --cleanup=whitespace -F - --") echo some ;;
    "commit -q --no-verify --cleanup=whitespace -F - --allow-empty --") echo some ;;
    "update-index --add -z --stdin" | "update-index --force-remove -z --stdin") echo none ;;
    "notes --ref=file-rewind-meta show {REV}") echo none ;;
    *) return 1 ;;
    esac
}

op_git() {
    (($# >= 3)) || die "usage"
    select_repository "$1" "$2"
    shift 2
    if [[ $* == "rev-parse --git-dir" ]]; then
        # "do checkpoints exist" must work before anything else
        [[ -e $STORE || -L $STORE ]] || exit 1
    fi
    require_trusted_store

    if [[ $# == 5 && $1 == --no-literal-pathspecs && $2 == check-ignore &&
          $3 == --no-index && $4 == -z && $5 == --stdin ]]; then
        [[ -d $FOLDER ]] || die "the folder does not exist"
        git_command
        exec "${GITCMD[@]}" "$@"
    fi

    # The safety add can exclude untracked projects without a commit. Require literal pathspecs
    # so even names containing Git pathspec syntax are taken literally.
    if [[ $1 == --no-literal-pathspecs ]]; then
        [[ -d $FOLDER && $# -ge 7 && $2 == add && $3 == -A && $4 == --no-ignore-errors &&
            $5 == -- && $6 == ':(literal).' ]] || die "invalid safety add"
        local exclude
        for exclude in "${@:7}"; do
            [[ $exclude == ':(exclude,literal)'* ]] && valid_relative "${exclude#':(exclude,literal)'}" || die "invalid exclusion"
        done
        git_command
        exec "${GITCMD[@]}" "$@"
    fi

    local form="" arg separator=0
    local -a paths=()
    for arg in "$@"; do
        if ((separator)); then
            paths+=("$arg")
            continue
        fi
        if [[ $arg == -- ]]; then
            separator=1
            form+=" --"
        elif [[ -z $form ]]; then
            case $arg in # the subcommand: one known word
            rev-parse | log | diff | ls-files | ls-tree | cat-file | count-objects | add | commit | update-index | notes)
                form=$arg ;;
            *) die "git command not allowed" ;;
            esac
        elif is_revision "$arg"; then
            form+=" {REV}"
        elif [[ $arg =~ ^--source=[0-9a-f]{40}$ ]]; then
            form+=" {SRC}"
        elif [[ $form == cat-file* && $arg =~ ^[0-9a-f]{40}:. ]]; then
            form+=" {BLOB}"
        elif [[ $arg == "$LOG_FORMAT_CHECKPOINTS" ]]; then
            form+=" {FMT_C}"
        elif [[ $arg == "$LOG_FORMAT_HISTORY" ]]; then
            form+=" {FMT_H}"
        elif [[ $arg =~ ^[-A-Za-z0-9=/_]+$ ]]; then # only exact forms pass below
            form+=" $arg"
        else
            die "git argument not allowed: $arg"
        fi
    done
    local arity
    arity=$(git_form_arity "$form") || die "git command not allowed: $form"
    if [[ ! -d $FOLDER ]]; then # a deleted folder: nothing that uses a work tree
        case $form in
        rev-parse* | log* | ls-tree* | cat-file* | count-objects* | "notes --ref=file-rewind-meta show"*) ;;
        *) die "the folder does not exist" ;;
        esac
    fi
    case $arity in
    none) ((${#paths[@]} == 0)) ;;
    one) ((${#paths[@]} == 1)) ;;
    some) ((${#paths[@]} >= 1)) ;;
    any) true ;;
    esac || die "wrong number of paths for: $form"
    git_command
    exec "${GITCMD[@]}" "$@"
}

# Paths below FOLDER are only looked at through folders that only root can change, so nothing
# can be swapped for a symlink in the middle of a path
trusted_relative_folder() {
    local current=$FOLDER/$1
    [[ -e $current || -L $current ]] || return 2 # missing: so is everything below it
    [[ -d $current ]] && trusted_entry "$current"
}
require_trusted_parents() {
    local parents=$1
    [[ $parents == */* ]] || return 0
    parents=${parents%/*}
    for_each_prefix trusted_relative_folder "$parents"
    (($? != 1))
}

# Compare saved paths with the work tree using an index private to this invocation.
op_compare() (
    (($# >= 5)) || die "usage"
    [[ $5 == -- ]] || die "usage"
    select_repository "$1" "$2"
    local rev=$3 format=$4 p scratch
    [[ $rev =~ ^[0-9a-f]{40}$ && -d $FOLDER ]] || die "invalid checkpoint or folder"
    shift 5
    for p in "$@"; do valid_relative "$p" || die "invalid path"; done
    local -a options
    case $format in
    stats) (($# == 0)) || die "usage"; options=(--no-ext-diff --no-textconv --numstat -z --no-renames) ;;
    patch) options=(--no-color --no-ext-diff --no-textconv --no-renames --src-prefix=a/ --dst-prefix=b/) ;;
    *) die "invalid comparison" ;;
    esac
    require_trusted_store
    git_command
    "${GITCMD[@]}" merge-base --is-ancestor "$rev" HEAD || die "unknown checkpoint"
    scratch=$(mktemp -d -- /tmp/file-rewind-compare.XXXXXXXXXX) || die "cannot prepare comparison"
    trap 'rm -rf -- "$scratch"' EXIT
    export GIT_INDEX_FILE="$scratch/index"
    local -a compare_git=("${GITCMD[@]}" -c core.splitIndex=false -c core.sparseCheckout=false)
    "${compare_git[@]}" read-tree "$rev" || exit
    if [[ $format == stats ]]; then
        while IFS= read -r -d '' p; do
            valid_relative "$p" || die "invalid path"
            printf '%s\0' "$p" || exit 1
        done > "$scratch/paths" || exit 1
        xargs -0 -r -a "$scratch/paths" "${compare_git[@]}" diff "${options[@]}" "$rev" --
    else
        "${compare_git[@]}" diff "${options[@]}" "$rev" -- "$@"
    fi
)

entry_type() {
    local result
    if result=$(stat -c %F -- "$1" 2>&1); then
        printf '%s' "$result"
    elif [[ $result == *": No such file or directory" || $result == *": Not a directory" ]]; then
        printf missing
    else
        printf '%s\n' "$result" >&2
        return 1
    fi
}

op_folder_state() {
    (($# == 2)) || die "usage"
    select_repository "$1" "$2"
    # Also works before the first checkpoint. Only inspect the folder and the fixed legacy store name.
    local kind
    kind=$(entry_type "$FOLDER") || die "cannot inspect the folder"
    case $kind in
    missing) echo missing ;;
    directory)
        kind=$(entry_type "$FOLDER/.git") || die "cannot inspect the folder"
        case $kind in
        directory) echo in-folder ;;
        'symbolic link') die "cannot safely inspect the in-folder checkpoint store" ;;
        *) echo central ;;
        esac ;;
    *) die "the path is not a folder" ;;
    esac
}

op_probe() {
    (($# >= 3)) || die "usage"
    select_repository "$1" "$2"
    shift 2
    require_trusted_store
    local -a paths=()
    local p
    for p in "$@"; do
        valid_relative "$p" || die "invalid path"
        require_trusted_parents "$p" || die "cannot safely check a path"
        paths+=("$FOLDER/$p")
    done
    exec "$FIND" -P "${paths[@]}" -maxdepth 0 -printf '%y\0%p\0'
}

op_walk() {
    (($# == 3)) || die "usage"
    select_repository "$1" "$2"
    require_trusted_store
    valid_relative "$3" || die "invalid path"
    require_trusted_parents "$3/x" || die "cannot safely check a path"
    exec "$FIND" -P "$FOLDER/$3" -mindepth 1 -printf '%y\0%P\0'
}

op_metadata() { # STORE FOLDER [-- PATH...]: everything, or just the named entries (by exact path)
    (($# == 2)) || [[ $# -ge 3 && $3 == -- ]] || die "usage"
    select_repository "$1" "$2"
    require_trusted_store
    [[ -d $FOLDER ]] || exit 0
    cd -- "$FOLDER" || die "cannot enter the folder"
    if (($# == 2)); then
        exec "$FIND" -P . \( -path ./.git -prune \) -o -printf '%m %U %G %y %P\0'
    fi
    local -a paths=()
    local path
    for path in "${@:4}"; do
        valid_relative "$path" || die "invalid path"
        require_trusted_parents "$path" || die "cannot safely check a path"
        paths+=("./$path")
    done
    ((${#paths[@]})) || exit 0
    exec "$FIND" -P "${paths[@]}" -maxdepth 0 -printf '%m %U %G %y %p\0'
}

# Recording and applying permissions belong to a checkpoint or restore the caller is doing now
require_caller_holds_lock() {
    verified_holder "$(lock_file)" >/dev/null || die "the folder is not locked by the caller"
}

# The caller's lock holder as "pid:start time": the steps of one restore (check, restore, apply)
# must all come from the same holder, so a lock given up and taken again starts over
holder_token() {
    local holder stat
    local -a fields
    holder=$(verified_holder "$(lock_file)") || die "the folder is not locked by the caller"
    stat=$(<"/proc/$holder/stat") || die "the folder is not locked by the caller"
    stat=${stat##*) } # the fields after the command name, from the state (field 3) on
    read -r -a fields <<<"$stat"
    [[ ${fields[19]:-} =~ ^[0-9]+$ ]] || die "the folder is not locked by the caller"
    printf '%s:%s' "$holder" "${fields[19]}"
}

# The program that records and applies metadata as root: only the installed one
require_installed_program() {
    if [[ ! -x $PROGRAM ]] || ! trusted_file "$PROGRAM" || ! trusted_path "$PROGRAM"; then
        die "$PROGRAM is not installed"
    fi
}

op_exclude_file() {
    (($# == 3)) && valid_relative "$3" || die "invalid path"
    select_repository "$1" "$2"
    require_trusted_store
    require_caller_holds_lock
    require_installed_program
    exec "$PROGRAM" --internal-metadata exclude "$STORE" "$FOLDER" "$3"
}

# Undo the latest exclusion: STORE FOLDER PATH. What to take back is read from the store, never
# from the caller
op_unexclude_file() {
    (($# == 3)) && valid_relative "$3" || die "invalid path"
    select_repository "$1" "$2"
    require_trusted_store
    require_caller_holds_lock
    require_installed_program
    exec "$PROGRAM" --internal-metadata unexclude "$STORE" "$FOLDER" "$3"
}

op_record_metadata() {
    if (($# < 3)) || [[ $3 != -- ]]; then
        die "usage"
    fi
    select_repository "$1" "$2"
    require_trusted_store
    local path
    for path in "${@:4}"; do
        valid_relative "$path" || die "invalid path"
    done
    require_caller_holds_lock
    require_installed_program
    exec "$PROGRAM" --internal-metadata record "$STORE" "$FOLDER" "${@:4}"
}

# One step of a restore (check, restore, apply), done by the installed program as root for the
# caller's lock holder: STORE FOLDER TARGET SAFETY whole|files -- PATH...
restore_step() {
    local step=$1
    shift
    if (($# < 6)) || [[ $6 != -- ]]; then
        die "usage"
    fi
    select_repository "$1" "$2"
    require_trusted_store
    [[ $3 =~ ^[0-9a-f]{40}$ && $4 =~ ^[0-9a-f]{40}$ ]] || die "invalid checkpoint"
    # The whole folder names no paths; files name at least one
    if ! [[ ($5 == whole && $# -eq 6) || ($5 == files && $# -gt 6) ]]; then
        die "usage"
    fi
    local path
    for path in "${@:7}"; do
        valid_relative "$path" || die "invalid path"
    done
    if [[ $step == restore && ! -d $FOLDER ]]; then
        die "the folder does not exist"
    fi
    local holder
    holder=$(holder_token) || exit 3
    require_installed_program
    exec "$PROGRAM" --internal-metadata "$step" "$STORE" "$FOLDER" "$holder" "$3" "$4" "$5" "${@:7}"
}

op_init() { # ignore rules on stdin
    (($# == 2)) || die "usage"
    select_repository "$1" "$2"
    # Only brand-new stores; an existing or half-made one can't be verified
    [[ $KIND == central ]] || die "cannot create checkpoints inside a system folder"
    [[ -d $FOLDER ]] || die "the folder does not exist"
    make_private_store_root || die "cannot create $SYSTEM_STORE"
    [[ ! -e $STORE && ! -L $STORE ]] || die "the checkpoint store already exists"
    local excludes
    excludes=$(head -c 65536)
    git_command
    "${GITCMD[@]}" init -q --object-format=sha1 || exit
    "$GIT" config --file "$STORE/config" file-rewind.folder "$FOLDER" || exit
    mkdir -p -- "$STORE/info" && printf '%s\n' "$excludes" >"$STORE/info/exclude"
}

op_mkdir() {
    (($# == 2)) || die "usage"
    select_repository "$1" "$2"
    [[ $KIND == central ]] || die "usage"
    require_trusted_store
    # Create the missing folders one at a time, below a folder nobody else can write to at all
    # (not even a sticky one, where another user could create the next name first)
    local base rest part
    base=$(existing_ancestor "$FOLDER")
    # This exact base is checked (owner, ancestry, no group/other write at all) and then used
    if [[ ! -d $base ]] || ! trusted_path "$base"; then
        die "cannot safely create the folder here"
    fi
    rest=${FOLDER#"$base"}
    rest=${rest#/}
    while [[ -n $rest ]]; do
        part=${rest%%/*}
        if [[ $rest == */* ]]; then
            rest=${rest#*/}
        else
            rest=""
        fi
        base+=/$part
        if ! mkdir -m 0700 -- "$base" || ! trusted_entry "$base"; then # private until its permissions are applied
            die "cannot create the folder"
        fi
    done
}

op_delete() {
    (($# == 2)) || die "usage"
    select_repository "$1" "$2"
    require_trusted_store
    rm -rf -- "$STORE"
}

# ---- Locking ------------------------------------------------------------------------------
# One persistent lock file per folder, never removed: whoever holds flock() on it may write the
# folder's checkpoints. File Rewind running as root (scheduled checkpoints) flocks the same file.
# The kernel drops the lock when its holder ends, so there is no stale-lock clean-up.
# The lock belongs to the calling program (PPID): a small holder process keeps it until the
# program unlocks or exits.

lock_file() {
    local hash
    hash=$(printf '%s' "$FOLDER" | sha1sum)
    printf '%s/locks/%s.lock' "$SYSTEM_STORE" "${hash:0:16}"
}

# The holder recorded for the lock, if it is alive and really holds the lock file open
verified_holder() {
    local file=$1 owner holder fd
    read -r owner holder 2>/dev/null <"$file.owner" || return 1
    [[ $owner == "$PPID" && $holder =~ ^[0-9]+$ ]] || return 1
    for fd in /proc/"$holder"/fd/*; do
        if [[ $(readlink -- "$fd" 2>/dev/null) == "$file" ]]; then
            printf '%s' "$holder"
            return 0
        fi
    done
    return 1
}

op_lock() {
    (($# == 2)) || die "usage"
    select_repository "$1" "$2"
    make_private_store_root || die "cannot create $SYSTEM_STORE"
    make_lock_folder || die "cannot create the lock folder"
    local file owner=$PPID fd
    file=$(lock_file)
    if [[ -e $file || -L $file ]]; then
        trusted_file "$file" || die "unexpected lock file"
    fi
    if verified_holder "$file" >/dev/null; then
        exit 0 # already held for this program
    fi
    exec {fd}>>"$file" || die "cannot open the lock file"
    flock -w "$LOCK_WAIT" "$fd" || die "busy"
    # The holder shares this open file, and with it the lock, after the helper exits
    # The holder removes its own record (only if it is still its own) before giving up the lock,
    # so a record never outlives its lock and never erases the next holder's record
    (
        forget() {
            local recorded
            recorded=$(head -n 1 -- "$file.owner" 2>/dev/null)
            [[ $recorded == "$owner $BASHPID" ]] && rm -f -- "$file.owner"
            exit 0
        }
        trap forget TERM
        while kill -0 "$owner" 2>/dev/null; do
            sleep 1 {fd}>&- & # sleep must not get a copy of the lock
            wait $!
        done
        forget
    ) </dev/null >/dev/null 2>&1 &
    local holder=$!
    if ! printf '%s %s\n' "$owner" "$holder" 2>/dev/null >"$file.owner.new" \
        || ! mv -fT -- "$file.owner.new" "$file.owner" 2>/dev/null; then # -T: never into a folder
        # Without a record nobody could unlock it: give the lock up again before failing
        kill -TERM "$holder" 2>/dev/null
        wait "$holder" 2>/dev/null
        die "cannot record the lock owner"
    fi
}

op_unlock() {
    (($# == 2)) || die "usage"
    # Releasing must not depend on the folder still being usable (its permissions may have changed
    # since it was locked): only the folder name as a key, root's own lock folder, and a holder
    # verified to be this program's
    FOLDER=$2
    valid_folder "$FOLDER" || die "invalid folder"
    [[ -d $SYSTEM_STORE/locks ]] && trusted_path "$SYSTEM_STORE/locks" || exit 0
    local file holder wait=0
    file=$(lock_file)
    if [[ -e $file.owner || -L $file.owner ]]; then
        trusted_file "$file.owner" || exit 0
    fi
    holder=$(verified_holder "$file") || exit 0
    kill -TERM "$holder" 2>/dev/null
    while kill -0 "$holder" 2>/dev/null && ((wait++ < 50)); do
        sleep 0.1
    done
}

# ---- Scheduled checkpoints ----------------------------------------------------------------

# cron's shell quoting; '%' is special to cron
cron_quote() {
    local q=${1//\'/\'\\\'\'}
    q=${q//%/\\%}
    printf "'%s'" "$q"
}

op_schedule() {
    (($# == 3)) || die "usage"
    local frequency=$3 pattern
    case $frequency in
    off) pattern="" ;;
    hourly) pattern="0 * * * *" ;;
    daily) pattern="*/15 * * * *" ;;
    weekly) pattern="30 12 * * 1" ;;
    startup) pattern="@reboot" ;;
    *) die "invalid frequency" ;;
    esac
    valid_folder "$2" || die "invalid folder"
    if [[ $frequency != off ]]; then
        # Only for a folder whose checkpoints are root's (the job revalidates them when it runs)
        select_repository "$1" "$2"
        require_trusted_store
        # Jobs only ever run the installed program, never one a user could replace
        require_installed_program
    fi
    local folder=$2 store=$1 job="" daily=""
    if [[ $frequency == daily ]]; then
        daily=" --daily"
    fi
    if [[ -n $pattern ]]; then
        job="$pattern root test ! -x $PROGRAM || $PROGRAM$daily --auto-checkpoint $(cron_quote "$folder") --store $(cron_quote "$store")"
    fi
    rewrite_cron_file "$folder" "$job"
}

# A job exactly as this version writes it: a known time, root, the installed program, the folder
# and its store. Anything else in the file (older versions wrote the program that happened to be
# running, or ran git directly) is dropped whenever the file is rewritten.
is_current_job() {
    local line=$1 time rest="" quoted="'([^']|'\\\\'')*'"
    local prefix="${line%% root *} root "
    # Check the executable and arguments in exactly the same way for guarded and older jobs.
    if [[ $line == "${prefix}test ! -x $PROGRAM || "* ]]; then
        line=$prefix${line#"${prefix}test ! -x $PROGRAM || "}
    fi
    local daily="*/15 * * * * root $PROGRAM --daily --auto-checkpoint "
    if [[ $line == "$daily"* ]]; then
        rest=${line#"$daily"}
    fi
    for time in "0 * * * *" "30 12 * * *" "30 12 * * 1" "@reboot"; do
        if [[ $line == "$time root $PROGRAM --auto-checkpoint '"* ]]; then
            rest=${line#"$time root $PROGRAM --auto-checkpoint "}
            break
        fi
    done
    [[ -n $rest && $rest =~ ^${quoted}\ --store\ ${quoted}$ ]]
}

# Rewrites the cron file under its lock: keeps comments and current jobs of other folders, drops
# the jobs of FOLDER (if given) and every job not in the current form, then adds JOB (if given)
rewrite_cron_file() {
    local folder=$1 job=$2
    make_private_store_root || die "cannot create $SYSTEM_STORE"
    make_lock_folder || die "cannot create the lock folder"
    local lockfd
    if [[ -e $SYSTEM_STORE/locks/cron.lock || -L $SYSTEM_STORE/locks/cron.lock ]]; then
        trusted_file "$SYSTEM_STORE/locks/cron.lock" || die "unexpected lock file"
    fi
    exec {lockfd}>>"$SYSTEM_STORE/locks/cron.lock" || die "cannot lock $CRON_FILE"
    flock -w "$LOCK_WAIT" "$lockfd" || die "busy"

    local mine="" line tmp readfd
    if [[ -n $folder ]]; then
        mine=" --auto-checkpoint $(cron_quote "$folder") --store "
    fi
    local -a lines=()
    if [[ -e $CRON_FILE || -L $CRON_FILE ]]; then
        # The existing file must really be read before anything replaces or removes it
        [[ -f $CRON_FILE && ! -L $CRON_FILE ]] || die "unexpected $CRON_FILE"
        exec {readfd}<"$CRON_FILE" || die "cannot read $CRON_FILE"
        # All of it, with cat's exit status checked: "read" can't tell a read error from the end
        local content
        content=$(cat <&"$readfd") || die "cannot read $CRON_FILE"
        exec {readfd}<&-
        while IFS= read -r line; do
            if [[ $line == \#* || -z ${line//[[:space:]]/} ]]; then
                lines+=("$line")
            elif is_current_job "$line" && [[ -z $mine || $line != *"$mine"* ]]; then
                lines+=("$line")
            fi
        done <<<"$content"
    fi
    while ((${#lines[@]})) && [[ -z ${lines[-1]//[[:space:]]/} ]]; do
        unset 'lines[-1]'
    done
    if [[ -n $job ]]; then
        lines+=("$job")
    fi
    if ((${#lines[@]} == 0)); then
        rm -f -- "$CRON_FILE"
        return
    fi
    mkdir -p -- "$(dirname -- "$CRON_FILE")"
    # cron ignores file names containing a dot, so the temporary file is never run
    tmp=$(mktemp "$(dirname -- "$CRON_FILE")/.file-rewind.XXXXXX") || die "cannot write $CRON_FILE"
    if ! printf '%s\n' "${lines[@]}" >"$tmp" || ! chmod 0644 -- "$tmp" || ! mv -fT -- "$tmp" "$CRON_FILE"; then
        rm -f -- "$tmp"
        die "cannot write $CRON_FILE"
    fi
}

# Run by the package on install and upgrade: drops jobs left by older versions
op_clean_schedules() {
    (($# == 0)) || die "usage"
    [[ -e $CRON_FILE ]] || exit 0
    rewrite_cron_file "" ""
}

(($# >= 1)) || die "usage"
operation=$1
shift
case $operation in
git) op_git "$@" ;;
compare) op_compare "$@" ;;
folder-state) op_folder_state "$@" ;;
probe) op_probe "$@" ;;
walk) op_walk "$@" ;;
init) op_init "$@" ;;
mkdir) op_mkdir "$@" ;;
delete) op_delete "$@" ;;
lock) op_lock "$@" ;;
unlock) op_unlock "$@" ;;
schedule) op_schedule "$@" ;;
clean-schedules) op_clean_schedules "$@" ;;
metadata) op_metadata "$@" ;;
exclude-file) op_exclude_file "$@" ;;
unexclude-file) op_unexclude_file "$@" ;;
record-metadata) op_record_metadata "$@" ;;
check-restore) restore_step check "$@" ;;
restore) restore_step restore "$@" ;;
apply-metadata) restore_step apply "$@" ;;
*) die "unknown operation" ;;
esac
