#!/bin/sh

SCRIPT_VERSION="v1"
BACKUP_ROOT=${BACKUP_ROOT:-/usr/local/openvpn_as/etc/backup}
AS_CONF=${AS_CONF:-/usr/local/openvpn_as/etc/as.conf}
DB_DIR=${DB_DIR:-/usr/local/openvpn_as/etc/db}
LOCK_FILE=${LOCK_FILE:-/run/as-backup.lock}
DATABASES="config certs userprop log config_local cluster notification"
# Scheduled backups carry the reserved comment "auto"; AUTO_MARK is its base64url form.
AUTO_COMMENT="auto"
AUTO_MARK="YXV0bw"
# Version part of a backup name: v<major>-<minor>-<patch>, plus an optional _suffix that the
# v1 script wrote for internal builds ("3.3.0_internal" -> v3-3-0_internal).
NAME_VER_RE='v[0-9]+-[0-9]+-[0-9]+(_[A-Za-z0-9]+)?'

# Run state used by _cleanup (one trap handler for the whole run).
_lock_held=0
_bk_tmpdir=""
_rs_tmpdir=""
_archive_path=""
_restore_active=0
_pre_backup_running=0

# as_version_xyz: X.Y.Z of the running AS ("3.3.0_internal (9e89bdd7)" -> 3.3.0); empty
# when sacli does not answer.
as_version_xyz() {
    sacli version 2>/dev/null | sed -n -E '1s/^([0-9]+\.[0-9]+\.[0-9]+).*/\1/p'
}

die() {
    printf '%s\n' "$1" >&2
    exit "${2:-1}"
}

# Lock: a symlink whose target is the owner's PID. `ln -s` creates it atomically, so the
# lock and its PID appear together. A lock whose PID is no longer running is stale and is
# taken over once. Re-entrant: a nested backup inside a restore keeps the restore's lock.
acquire_lock() {
    [ "$_lock_held" = "1" ] && return 0
    LOCK_OWNER=""
    _lock_try=0
    while :; do
        if ln -s "$$" "$LOCK_FILE" 2>/dev/null; then
            _lock_held=1
            return 0
        fi
        LOCK_OWNER=$(readlink "$LOCK_FILE" 2>/dev/null) || LOCK_OWNER=""
        if [ -n "$LOCK_OWNER" ] && kill -0 "$LOCK_OWNER" 2>/dev/null; then
            return 1
        fi
        [ "$_lock_try" = "0" ] || return 1
        _lock_try=1
        rm -f "$LOCK_FILE"
    done
}

lock_or_die() {
    acquire_lock || die "Another as-backup operation is running (pid ${LOCK_OWNER:-unknown})" 4
}

_release_lock() {
    if [ "$_lock_held" = "1" ]; then
        rm -f "$LOCK_FILE"
        _lock_held=0
    fi
}

_cleanup() {
    if [ -n "$_bk_tmpdir" ]; then
        rm -rf "$_bk_tmpdir"
        _bk_tmpdir=""
    fi
    if [ -n "$_archive_path" ]; then
        rm -f "$_archive_path"
        _archive_path=""
    fi
    if [ "$_restore_active" = "1" ]; then
        _restore_cleanup
    fi
    _release_lock
}

setup_traps() {
    trap '_cleanup' EXIT
    trap '_cleanup; exit 130' INT
    trap '_cleanup; exit 143' TERM
}

check_sacli() {
    _path=$(command -v sacli 2>/dev/null) || die "sacli not found or not executable"
    [ -x "$_path" ] || die "sacli not executable"
}

check_root() {
    [ "$(id -u)" -eq 0 ] || die "This operation requires root privileges"
}

check_tools() {
    for _tool in tar gzip sqlite3; do
        command -v "$_tool" >/dev/null 2>&1 || die "$_tool not found"
    done
}

check_mysql_backup_tools() {
    command -v mysqldump >/dev/null 2>&1 || die "mysqldump not found"
}

check_mysql_restore_tools() {
    command -v mysql >/dev/null 2>&1 || die "mysql not found"
}

db_conf_key() {
    case "$1" in
        userprop)
            printf '%s\n' "user_prop_db"
            ;;
        *)
            printf '%s_db\n' "$1"
            ;;
    esac
}

get_db_uri() {
    _db="$1"
    _conf="${2:-$AS_CONF}"
    _key=$(db_conf_key "$_db")

    [ -f "$_conf" ] || return 1

    sed -n "s/^[[:space:]]*${_key}[[:space:]]*=[[:space:]]*//p" "$_conf" |
        sed 's/[[:space:]]*$//' |
        sed -n '1p'
}

db_backend() {
    _db="$1"
    _conf="${2:-$AS_CONF}"
    _uri=$(get_db_uri "$_db" "$_conf") || _uri=""

    case "$_uri" in
        ""|sqlite://*)
            printf '%s\n' "sqlite"
            ;;
        mysql://*)
            printf '%s\n' "mysql"
            ;;
        *://*)
            die "Unsupported database URI scheme for $_db: $_uri"
            ;;
        *)
            die "Unsupported database URI for $_db: $_uri"
            ;;
    esac
}

mysql_backup_required() {
    for _db in $DATABASES; do
        _b=$(db_backend "$_db") || exit 1
        if [ "$_b" = "mysql" ]; then
            return 0
        fi
    done
    return 1
}

parse_mysql_uri() {
    _uri="$1"
    MYSQL_URI_USER="" MYSQL_URI_PASSWORD="" MYSQL_URI_HOST="" MYSQL_URI_PORT="" MYSQL_URI_DATABASE=""

    case "$_uri" in
        mysql://*:*@*:*/*) ;;
        *) die "Invalid MySQL URI: $_uri" ;;
    esac

    _mysql_rest=${_uri#mysql://}
    MYSQL_URI_USER=${_mysql_rest%%:*}
    _mysql_after_user=${_mysql_rest#*:}
    MYSQL_URI_PASSWORD=${_mysql_after_user%%@*}
    _mysql_after_at=${_mysql_after_user#*@}
    _mysql_hostport=${_mysql_after_at%%/*}
    MYSQL_URI_DATABASE=${_mysql_after_at#*/}
    MYSQL_URI_HOST=${_mysql_hostport%:*}
    MYSQL_URI_PORT=${_mysql_hostport##*:}

    [ -n "$MYSQL_URI_USER" ] || die "Invalid MySQL URI: missing user"
    [ -n "$MYSQL_URI_HOST" ] || die "Invalid MySQL URI: missing host"
    case "$MYSQL_URI_HOST" in
        *@*) die "Invalid MySQL URI: password contains unescaped '@'" ;;
    esac
    [ "$MYSQL_URI_HOST" != "$_mysql_hostport" ] || die "Invalid MySQL URI: missing port"
    [ -n "$MYSQL_URI_PORT" ] || die "Invalid MySQL URI: missing port"
    case "$MYSQL_URI_PORT" in
        *[!0-9]*)
            die "Invalid MySQL URI: non-numeric port"
            ;;
    esac
    [ -n "$MYSQL_URI_DATABASE" ] || die "Invalid MySQL URI: missing database"
}

dump_mysql_db() {
    _db="$1"
    _uri="$2"
    _out="$3"

    parse_mysql_uri "$_uri"
    MYSQL_PWD=$MYSQL_URI_PASSWORD mysqldump \
        --host="$MYSQL_URI_HOST" \
        --port="$MYSQL_URI_PORT" \
        --user="$MYSQL_URI_USER" \
        "$MYSQL_URI_DATABASE" > "$_out" || die "Failed to dump MySQL database: $_db"
}

restore_mysql_db() {
    _db="$1"
    _uri="$2"
    _in="$3"

    case "$_uri" in
        mysql://*) ;;
        *) die "MySQL restore for $_db requires mysql:// record in as.conf.bak" ;;
    esac

    parse_mysql_uri "$_uri"
    _restore_promoted=1
    MYSQL_PWD=$MYSQL_URI_PASSWORD mysql \
        --host="$MYSQL_URI_HOST" \
        --port="$MYSQL_URI_PORT" \
        --user="$MYSQL_URI_USER" \
        "$MYSQL_URI_DATABASE" < "$_in" || die "Failed to restore MySQL database: $_db"
}

mysql_restore_required() {
    _dir="$1"

    for _db in $DATABASES; do
        if [ -e "${_dir}/${_db}.mysql.sql" ]; then
            return 0
        fi
    done
    return 1
}

encode_comment() {
    printf '%s' "$1" | base64 | tr -d '\n=' | sed 's/+/-/g; s|/|_|g'
}

decode_comment() {
    _b64=$(printf '%s' "$1" | sed 's/-/+/g; s|_|/|g')
    case $(( ${#_b64} % 4 )) in
        2) _b64="${_b64}==" ;;
        3) _b64="${_b64}=" ;;
    esac
    printf '%s' "$_b64" | base64 -d 2>/dev/null
}

find_backup_by_id() {
    # Glob for candidate names and compare in the shell: no process per archive (a host with
    # ~4000 archives took ~1 minute with a basename+sed per file). Own variable names: POSIX
    # sh has no `local`, and callers keep their own _id.
    _fb_id="$1"
    case "$_fb_id" in
        ""|*[!0-9]*) return 1 ;;
    esac
    for _fb_f in "${BACKUP_ROOT}"/[0-9][0-9][0-9][0-9]/v[0-9]*-"${_fb_id}"-*.tar.gz; do
        [ -f "$_fb_f" ] || continue
        _fb_rest=${_fb_f##*/}
        _fb_rest=${_fb_rest#v*-}
        if [ "${_fb_rest%%-*}" = "$_fb_id" ]; then
            printf '%s\n' "$_fb_f"
            return 0
        fi
    done
    return 1
}

# create_backup COMMENT: write one archive; sets BACKUP_CREATED_ID and BACKUP_CREATED_PATH,
# prints nothing. Caller has done the checks and holds the lock.
create_backup() {
    _comment="$1"

    if [ -n "$_comment" ]; then
        _len=$(printf '%s' "$_comment" | wc -c)
        [ "$_len" -le 80 ] || die "Comment exceeds 80 characters"
    fi

    # The ID is the Unix second; never reuse one that already exists.
    _id_try=0
    while :; do
        timestamp=$(date -u +%s)
        find_backup_by_id "$timestamp" >/dev/null || break
        _id_try=$((_id_try + 1))
        [ "$_id_try" -lt 3 ] || die "Cannot get a unique backup ID"
        sleep 1
    done
    year=$(date -u +%Y -d "@$timestamp")
    as_version=$(as_version_xyz)
    as_version_dashed=$(printf '%s' "$as_version" | sed 's/\./-/g')

    if [ -n "$_comment" ]; then
        _comment_b64=$(encode_comment "$_comment")
        [ -n "$_comment_b64" ] || die "Failed to encode comment (base64 missing?)"
        filename="${SCRIPT_VERSION}-${timestamp}-v${as_version_dashed}-${_comment_b64}.tar.gz"
    else
        filename="${SCRIPT_VERSION}-${timestamp}-v${as_version_dashed}.tar.gz"
    fi

    dest_dir="${BACKUP_ROOT}/${year}"
    mkdir -p "$dest_dir" || die "Cannot create backup directory: $dest_dir"
    [ -w "$dest_dir" ] || die "Backup directory not writable: $dest_dir"

    _bk_tmpdir=$(mktemp -d) || die "Failed to create temporary directory"

    for db in $DATABASES; do
        _backend=$(db_backend "$db") || exit 1
        case "$_backend" in
            sqlite)
                if [ -e "${DB_DIR}/${db}.db" ]; then
                    sqlite3 "${DB_DIR}/${db}.db" .dump > "${_bk_tmpdir}/${db}.db.bak" || die "Failed to dump database: $db"
                fi
                ;;
            mysql)
                _uri=$(get_db_uri "$db")
                dump_mysql_db "$db" "$_uri" "${_bk_tmpdir}/${db}.mysql.sql"
                ;;
        esac
    done

    if [ -e "$AS_CONF" ]; then
        cp "$AS_CONF" "${_bk_tmpdir}/as.conf.bak" || die "Failed to copy as.conf"
    fi

    _archive_path="${dest_dir}/${filename}"
    tar czf "$_archive_path" -C "$_bk_tmpdir" . || die "Failed to create archive"
    _archive_path=""
    rm -rf "$_bk_tmpdir"
    _bk_tmpdir=""

    BACKUP_CREATED_ID=$timestamp
    BACKUP_CREATED_PATH="${dest_dir}/${filename}"
}

# prune_auto N: delete all but the newest N scheduled backups (comment "auto"). Manual
# backups are never touched.
prune_auto() {
    _pa_keep="$1"
    for _pa_dir in "${BACKUP_ROOT}"/[0-9][0-9][0-9][0-9]; do
        [ -d "$_pa_dir" ] || continue
        for _pa_f in "$_pa_dir"/*-"${AUTO_MARK}".tar.gz; do
            [ -f "$_pa_f" ] || continue
            _pa_ts=$(basename "$_pa_f" .tar.gz | sed -n -E "s/^v[0-9]+-([0-9]+)-${NAME_VER_RE}-${AUTO_MARK}\$/\\1/p")
            [ -n "$_pa_ts" ] && printf '%s %s\n' "$_pa_ts" "$_pa_f"
        done
    done | sort -n -r | {
        _pa_n=0
        while read -r _pa_ts _pa_f; do
            _pa_n=$((_pa_n + 1))
            [ "$_pa_n" -le "$_pa_keep" ] && continue
            if rm -f "$_pa_f"; then
                [ "$_pa_quiet" = "1" ] || printf 'Pruned scheduled backup: %s\n' "$_pa_ts"
            else
                printf 'Warning: cannot delete %s\n' "$_pa_f" >&2
            fi
        done
    }
}

do_backup() {
    _comment="$1"
    _pa_quiet="${2:-}"
    _bk_auto="${3:-}"
    _bk_keep="${4:-}"
    check_sacli
    check_root
    check_tools
    if mysql_backup_required; then
        check_mysql_backup_tools
    fi
    setup_traps
    if [ "$_bk_auto" = "1" ]; then
        _comment=$AUTO_COMMENT
        if ! acquire_lock; then
            printf 'Another as-backup operation is running (pid %s); scheduled backup skipped\n' "${LOCK_OWNER:-unknown}"
            exit 0
        fi
    else
        lock_or_die
    fi

    create_backup "$_comment"

    if [ "$_pa_quiet" = "1" ]; then
        printf '%s\n' "$BACKUP_CREATED_ID"
    else
        printf 'Backup created: %s\n' "$BACKUP_CREATED_PATH"
        printf 'Backup ID: %s\n' "$BACKUP_CREATED_ID"
    fi
    if [ -n "$_bk_keep" ]; then
        prune_auto "$_bk_keep"
    fi
}

do_list() {
    _no_header="$1"
    _as_version="$2"
    _tsv="${3:-}"
    check_sacli

    if [ -z "$_no_header" ] && [ -z "$_tsv" ]; then
        printf '%-12s%-22s%-12s%s\n' "ID" "DATE (UTC)" "AS VERSION" "COMMENT"
    fi

    _result=$(
        for _year_dir in "${BACKUP_ROOT}"/[0-9][0-9][0-9][0-9]; do
            [ -d "$_year_dir" ] || continue
            for _f in "$_year_dir"/*.tar.gz; do
                [ -f "$_f" ] || continue
                printf '%s\n' "$_f"
            done
        done | awk -v as_version="$_as_version" -v tsv="$_tsv" -v name_re="^v[0-9]+-[0-9]+-${NAME_VER_RE}(-[A-Za-z0-9_-]+)?\$" '
        BEGIN {
            _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            for (_k = 0; _k < 64; _k++) _val[substr(_chars, _k+1, 1)] = _k
        }
        function b64decode(s,    _i,_c1,_c2,_c3,_c4,_v1,_v2,_v3,_v4,_b1,_b2,_b3,_r) {
            gsub(/-/, "+", s); gsub(/_/, "/", s)
            while (length(s) % 4 != 0) s = s "="
            _r = ""
            for (_i = 1; _i <= length(s); _i += 4) {
                _c1 = substr(s,_i,1);   _c2 = substr(s,_i+1,1)
                _c3 = substr(s,_i+2,1); _c4 = substr(s,_i+3,1)
                _v1 = _val[_c1]; _v2 = _val[_c2]
                _v3 = (_c3 == "=") ? 0 : _val[_c3]
                _v4 = (_c4 == "=") ? 0 : _val[_c4]
                _b1 = _v1 * 4 + int(_v2 / 16)
                _b2 = (_v2 % 16) * 16 + int(_v3 / 4)
                _b3 = (_v3 % 4) * 64 + _v4
                _r = _r sprintf("%c", _b1)
                if (_c3 != "=") _r = _r sprintf("%c", _b2)
                if (_c4 != "=") _r = _r sprintf("%c", _b3)
            }
            return _r
        }
        function ts_to_date(ts,    _s,_mi,_h,_d,_y,_mo,_leap,_dim) {
            _s = ts % 60; ts = int(ts / 60)
            _mi = ts % 60; ts = int(ts / 60)
            _h = ts % 24; _d = int(ts / 24)
            for (_y = 1970; ; _y++) {
                _leap = (_y % 4 == 0 && (_y % 100 != 0 || _y % 400 == 0)) ? 1 : 0
                if (_d < 365 + _leap) break
                _d -= 365 + _leap
            }
            _leap = (_y % 4 == 0 && (_y % 100 != 0 || _y % 400 == 0)) ? 1 : 0
            split("31 " (_leap ? 29 : 28) " 31 30 31 30 31 31 30 31 30 31", _dim)
            for (_mo = 1; _mo <= 12; _mo++) {
                if (_d < _dim[_mo]) break
                _d -= _dim[_mo]
            }
            return sprintf("%04d-%02d-%02d %02d:%02d:%02d", _y, _mo, _d + 1, _h, _mi, _s)
        }
        {
            _base = $0; sub(/.*\//, "", _base); sub(/\.tar\.gz$/, "", _base)
            if (_base !~ name_re) next
            _nf = split(_base, _p, "-")
            _ts  = _p[2] + 0
            sub(/_.*/, "", _p[5])
            _ver = substr(_p[3], 2) "." _p[4] "." _p[5]
            if (as_version != "" && _ver != as_version) next
            _cb  = ""
            for (_i = 6; _i <= _nf; _i++) _cb = _cb (_i > 6 ? "-" : "") _p[_i]
            _comment = (_cb != "") ? b64decode(_cb) : "-"
            _date = ts_to_date(_ts)
            if (tsv != "") {
                if (_cb == "") _comment = ""
                gsub(/[\t\r\n]/, " ", _comment)
                printf "%s\t%s\t%s\t%s\t%s\n", _ts, _date, _ver, $0, _comment
                next
            }
            printf "%-12s%-22s%-12s%s\n", _ts, _date, _ver, _comment
        }
        ' | sort -n
    )

    if [ -z "$_result" ]; then
        [ -n "$_tsv" ] || printf 'No backups found.\n'
        return 0
    fi

    printf '%s\n' "$_result"
}

_restore_cleanup() {
    _restore_active=0
    if [ "$_pre_backup_running" = "1" ]; then
        printf 'Pre-restore backup failed: restore aborted, nothing changed\n' >&2
    fi
    for _db in $DATABASES; do
        rm -f "${DB_DIR}/${_db}.db.new"
    done
    rm -rf "$_rs_tmpdir"
    if [ "$_service_stopped" = "1" ]; then
        if [ "$_restore_promoted" = "0" ]; then
            systemctl start openvpnas || printf 'Warning: openvpnas failed to restart -- run: systemctl start openvpnas\n' >&2
        else
            printf 'Warning: restore failed after database promotion -- service NOT restarted. Installation may be in a mixed state. Inspect and start manually.\n' >&2
        fi
    fi
}

# restore_skips DB: true for databases the restore leaves as they are (--skip-log).
restore_skips() {
    [ "$_rs_skip_log" = "1" ] && [ "$1" = "log" ]
}

# is_log_db_line LINE: true for a `log_db = ...` record (leading blanks allowed).
is_log_db_line() {
    _ll=$1
    _ll=${_ll#"${_ll%%[![:space:]]*}"}
    case "$_ll" in
        log_db=*) return 0 ;;
        log_db[[:space:]]*=*)
            _ll=${_ll#log_db}
            _ll=${_ll#"${_ll%%[![:space:]]*}"}
            case "$_ll" in =*) return 0 ;; esac
            ;;
    esac
    return 1
}

# merge_keep_log_db BAK CURRENT OUT: copy BAK to OUT with every log_db record replaced by
# the current one (dropped when CURRENT has none; appended when BAK has none).
merge_keep_log_db() {
    _mk_cur=""
    if [ -f "$2" ]; then
        while IFS= read -r _mk_line || [ -n "$_mk_line" ]; do
            if is_log_db_line "$_mk_line"; then
                _mk_cur=$_mk_line
                break
            fi
        done < "$2"
    fi
    _mk_done=0
    : > "$3" || return 1
    while IFS= read -r _mk_line || [ -n "$_mk_line" ]; do
        if is_log_db_line "$_mk_line"; then
            if [ -n "$_mk_cur" ] && [ "$_mk_done" = "0" ]; then
                printf '%s\n' "$_mk_cur" >> "$3" || return 1
                _mk_done=1
            fi
            continue
        fi
        printf '%s\n' "$_mk_line" >> "$3" || return 1
    done < "$1"
    if [ -n "$_mk_cur" ] && [ "$_mk_done" = "0" ]; then
        printf '%s\n' "$_mk_cur" >> "$3" || return 1
    fi
}

stdin_is_tty() {
    [ -t 0 ]
}

# backup_comment FILE: the decoded comment of a backup archive, empty when it has none.
backup_comment() {
    _bc_b64=$(basename "$1" .tar.gz | sed -n -E "s/^v[0-9]+-[0-9]+-${NAME_VER_RE}-([A-Za-z0-9_-]+)\$/\\2/p")
    [ -n "$_bc_b64" ] && decode_comment "$_bc_b64"
    return 0
}

# print_restore_plan: what a restore of $_rs_tmpdir would change (used by --dry-run).
print_restore_plan() {
    _rp_comment=$(backup_comment "$backup_file")
    printf 'Dry run: restore of backup %s (AS %s, comment: %s)\n' "$_id" "$_backup_ver" "${_rp_comment:--}"
    printf '  archive: %s\n' "$backup_file"
    printf '  current AS version: %s\n' "${_current_ver:-unknown}"
    printf '  pre-restore backup: would be created ("pre-restore of %s")\n' "$_id"
    printf '  service: openvpnas would be stopped and started\n'
    for _rp_db in $DATABASES; do
        if restore_skips "$_rp_db"; then
            printf '  %s: kept (--skip-log)\n' "$_rp_db"
        elif [ -e "${_rs_tmpdir}/${_rp_db}.db.bak" ]; then
            printf '  %s: replace (sqlite)\n' "$_rp_db"
        elif [ -e "${_rs_tmpdir}/${_rp_db}.mysql.sql" ]; then
            _rp_uri=$(get_db_uri "$_rp_db" "${_rs_tmpdir}/as.conf.bak") || _rp_uri=""
            case "$_rp_uri" in
                mysql://*) ;;
                *) die "MySQL restore for $_rp_db requires mysql:// record in as.conf.bak" ;;
            esac
            parse_mysql_uri "$_rp_uri"
            printf '  %s: import (mysql %s:%s/%s)\n' "$_rp_db" "$MYSQL_URI_HOST" "$MYSQL_URI_PORT" "$MYSQL_URI_DATABASE"
        else
            printf '  %s: not in backup, left as is\n' "$_rp_db"
        fi
    done
    if [ -e "${_rs_tmpdir}/as.conf.bak" ]; then
        printf '  as.conf: replace\n'
    else
        printf '  as.conf: not in backup, left as is\n'
    fi
    printf 'No changes made.\n'
}

# confirm_restore: ask on a terminal unless --yes; without a terminal, proceed (scripts).
confirm_restore() {
    [ "$_rs_yes" = "1" ] && return 0
    stdin_is_tty || return 0
    _cr_comment=$(backup_comment "$backup_file")
    if [ -n "$_cr_comment" ]; then
        printf 'Restore backup %s (AS %s, "%s") over the current configuration? [y/N] ' "$_id" "$_backup_ver" "$_cr_comment" >&2
    else
        printf 'Restore backup %s (AS %s) over the current configuration? [y/N] ' "$_id" "$_backup_ver" >&2
    fi
    _cr_answer=""
    read -r _cr_answer || _cr_answer=""
    case "$_cr_answer" in
        y|Y|yes|YES) return 0 ;;
    esac
    die "Restore cancelled"
}

do_restore() {
    _id="$1"
    _rs_dry_run="${2:-}"
    _rs_yes="${3:-}"
    _rs_skip_log="${4:-}"
    check_sacli
    check_root
    check_tools
    setup_traps
    lock_or_die

    backup_file=$(find_backup_by_id "$_id") || die "Backup ID not found: $_id"

    _backup_ver=$(basename "$backup_file" .tar.gz | sed -E 's/^v[0-9]+-[0-9]+-(v[0-9]+-[0-9]+-[0-9]+).*/\1/' | sed 's/^v//; s/-/./g')
    _current_ver=$(as_version_xyz)
    if [ "$_backup_ver" != "$_current_ver" ]; then
        printf 'Warning: backup version (%s) differs from current AS version (%s)\n' "$_backup_ver" "$_current_ver" >&2
    fi

    for _db in $DATABASES; do
        rm -f "${DB_DIR}/${_db}.db.new"
    done

    _service_stopped=0
    _restore_promoted=0
    _rs_tmpdir=$(mktemp -d) || die "Failed to create temporary directory"
    _restore_active=1

    tar xzf "$backup_file" -C "$_rs_tmpdir" || die "Failed to extract archive"
    if mysql_restore_required "$_rs_tmpdir"; then
        check_mysql_restore_tools
    fi
    if mysql_backup_required; then
        check_mysql_backup_tools
    fi

    if [ "$_rs_dry_run" = "1" ]; then
        print_restore_plan
        exit 0
    fi
    confirm_restore

    _pre_backup_running=1
    create_backup "pre-restore of $_id"
    _pre_backup_running=0
    _pre_id=$BACKUP_CREATED_ID
    printf 'Pre-restore backup ID: %s\n' "$_pre_id"

    # The as.conf to install, prepared before the service is stopped.
    _rs_conf=""
    if [ -e "${_rs_tmpdir}/as.conf.bak" ]; then
        _rs_conf="${_rs_tmpdir}/as.conf.bak"
        if [ "$_rs_skip_log" = "1" ]; then
            _rs_cur_log=$(get_db_uri log "$AS_CONF") || _rs_cur_log=""
            _rs_bak_log=$(get_db_uri log "${_rs_tmpdir}/as.conf.bak") || _rs_bak_log=""
            if [ "$_rs_cur_log" != "$_rs_bak_log" ]; then
                merge_keep_log_db "${_rs_tmpdir}/as.conf.bak" "$AS_CONF" "${_rs_tmpdir}/as.conf.merged" ||
                    die "Failed to prepare as.conf"
                _rs_conf="${_rs_tmpdir}/as.conf.merged"
                printf 'Warning: kept the current log_db record (--skip-log)\n' >&2
            fi
        fi
    fi

    systemctl stop openvpnas || die "Failed to stop openvpnas service"
    _service_stopped=1

    for db in $DATABASES; do
        restore_skips "$db" && continue
        if [ -e "${_rs_tmpdir}/${db}.db.bak" ]; then
            sqlite3 "${DB_DIR}/${db}.db.new" < "${_rs_tmpdir}/${db}.db.bak" || die "Failed to restore database: $db"
        fi
        if [ -e "${_rs_tmpdir}/${db}.mysql.sql" ]; then
            _uri=$(get_db_uri "$db" "${_rs_tmpdir}/as.conf.bak") || _uri=""
            restore_mysql_db "$db" "$_uri" "${_rs_tmpdir}/${db}.mysql.sql"
        fi
    done

    for db in $DATABASES; do
        restore_skips "$db" && continue
        if [ -e "${DB_DIR}/${db}.db.new" ]; then
            mv "${DB_DIR}/${db}.db.new" "${DB_DIR}/${db}.db" || die "Failed to install database: $db"
            _restore_promoted=1
        fi
    done

    if [ -n "$_rs_conf" ]; then
        cp "$_rs_conf" "$AS_CONF" || die "Failed to restore as.conf"
    fi
    if [ "$_rs_skip_log" = "1" ]; then
        printf 'log database kept (--skip-log)\n'
    fi

    for db in $DATABASES; do
        if [ -e "${DB_DIR}/${db}.db" ]; then
            chmod 0600 "${DB_DIR}/${db}.db" || die "Failed to set permissions on database: $db"
        fi
    done
    if [ -e "$AS_CONF" ]; then
        chmod 0600 "$AS_CONF" || die "Failed to set permissions on as.conf"
    fi

    _service_stopped=0
    systemctl start openvpnas || {
        printf 'Restore complete. openvpnas failed to start -- run: systemctl start openvpnas\n' >&2
        die "Failed to start openvpnas service"
    }

    printf 'Restore complete from backup ID: %s (undo: as-backup.sh -r %s)\n' "$_id" "$_pre_id"
}

usage() {
    printf 'Usage: %s [OPTIONS]\n\n' "$0"
    printf 'OpenVPN Access Server Backup Tool\n\n'
    printf 'Options:\n'
    printf '  (no args)              Create a backup\n'
    printf '  -c, --comment VAL      Create a backup with a comment (max 80 chars)\n'
    printf '  -q, --quiet            Print only the new backup ID (use when creating a backup)\n'
    printf '      --auto             Scheduled backup (comment "auto"); skipped if another run is active\n'
    printf '      --keep N           Keep only the newest N scheduled backups (use with --auto)\n'
    printf '  -l, --list             List all backups\n'
    printf '      --no-header        Suppress header row (use with --list)\n'
    printf '      --as-version VER   Filter list by AS version (e.g. 3.2.1) (use with --list)\n'
    printf '      --tsv              Tab-separated list: id, date, version, path, comment (use with --list)\n'
    printf '  -r, --restore ID       Restore from backup with given ID\n'
    printf '      --dry-run          Show what the restore would change; change nothing (use with --restore)\n'
    printf '  -y, --yes              Do not ask for confirmation (use with --restore)\n'
    printf '      --skip-log         Keep the current log database (use with --restore)\n'
    printf '  -h, --help             Show this help\n'
}

main() {
    _comment=""
    _no_header=""
    _as_version=""
    _mode="backup"
    _restore_id=""
    _dry_run=""
    _yes=""
    _skip_log=""
    _quiet=""
    _tsv=""
    _auto=""
    _keep=""
    _comment_set=""

    while [ $# -gt 0 ]; do
        case "$1" in
            -c|--comment)
                shift
                [ $# -gt 0 ] || die "Missing value for --comment"
                _comment="$1"
                _comment_set="1"
                _mode="backup"
                ;;
            -l|--list)
                _mode="list"
                ;;
            --no-header)
                _no_header="1"
                ;;
            --as-version)
                shift
                [ $# -gt 0 ] || die "Missing value for --as-version"
                _as_version="$1"
                case "$_as_version" in
                    *[!0-9.]*)
                        die "Invalid --as-version value: '$_as_version' (expected format: X.Y.Z, e.g. 3.2.1)" ;;
                    [0-9]*.[0-9]*.[0-9]*) ;;
                    *) die "Invalid --as-version value: '$_as_version' (expected format: X.Y.Z, e.g. 3.2.1)" ;;
                esac
                ;;
            -r|--restore)
                shift
                [ $# -gt 0 ] || die "Missing value for --restore"
                _restore_id="$1"
                _mode="restore"
                ;;
            --dry-run)
                _dry_run="1"
                ;;
            -y|--yes)
                _yes="1"
                ;;
            --skip-log)
                _skip_log="1"
                ;;
            -q|--quiet)
                _quiet="1"
                ;;
            --tsv)
                _tsv="1"
                ;;
            --auto)
                _auto="1"
                ;;
            --keep)
                shift
                [ $# -gt 0 ] || die "Missing value for --keep"
                _keep="$1"
                case "$_keep" in
                    ""|*[!0-9]*) die "Invalid --keep value: '$_keep' (expected a whole number of at least 1)" ;;
                esac
                [ "$_keep" -ge 1 ] || die "Invalid --keep value: '$_keep' (expected a whole number of at least 1)"
                ;;
            -h|--help)
                usage
                exit 0
                ;;
            *)
                die "Unknown option: $1"
                ;;
        esac
        shift
    done

    if [ "$_mode" != "restore" ]; then
        [ -z "$_dry_run" ] || die "--dry-run requires --restore"
        [ -z "$_yes" ] || die "--yes requires --restore"
        [ -z "$_skip_log" ] || die "--skip-log requires --restore"
    fi
    [ "$_mode" = "backup" ] || [ -z "$_quiet" ] || die "--quiet is only valid when creating a backup"
    [ "$_mode" = "list" ] || [ -z "$_tsv" ] || die "--tsv requires --list"
    if [ "$_mode" = "backup" ]; then
        [ -z "$_auto" ] || [ -z "$_comment_set" ] || die "--auto cannot be combined with --comment"
        [ "$_comment_set" != "1" ] || [ "$_comment" != "$AUTO_COMMENT" ] ||
            die "Comment '$AUTO_COMMENT' is reserved for scheduled backups"
    else
        [ -z "$_auto" ] || die "--auto is only valid when creating a backup"
    fi
    [ -z "$_keep" ] || [ "$_auto" = "1" ] || die "--keep requires --auto"

    case "$_mode" in
        backup)
            do_backup "$_comment" "$_quiet" "$_auto" "$_keep"
            ;;
        list)
            do_list "$_no_header" "$_as_version" "$_tsv"
            ;;
        restore)
            do_restore "$_restore_id" "$_dry_run" "$_yes" "$_skip_log"
            ;;
    esac
}

if [ "${AS_BACKUP_TESTING:-}" != "1" ]; then
    main "$@"
fi
