Files
backup-scripts/borg/bin/reposetup
2026-01-14 14:33:04 -06:00

68 lines
2.4 KiB
Bash

#!/usr/bin/env bash
###################################################################################
## reposetup - a script to automate the setup of borg repositories
## Copyright (C) 2026 wytch
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU Affero General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Affero General Public License for more details.
##
## You should have received a copy of the GNU Affero General Public License
## along with this program. If not, see <https://www.gnu.org/licenses/>.
##
#################################################################################
# Ensure running as root to read the environment file
if [ "$EUID" -ne 0 ]; then
printf "Error: This script must be run as root (or via sudo).\n"
exit 1
fi
# Load the environment variables
if [ -f /opt/borg/etc/borg_environment ]; then
# shellcheck source=/dev/null
source /opt/borg/etc/borg_environment
export BORG_REPO BORG_PASSPHRASE
else
printf "Error: /opt/borg/etc/borg_environment not found.\n"
exit 1
fi
printf "Checking repository status at: %s\n" "$BORG_REPO"
# Check if the repo already exists to prevent accidental re-init
if borg info >/dev/null 2>&1; then
printf "Error: Repository already exists and is initialized.\n"
exit 1
fi
printf "Initializing repository...\n"
# Logic for encryption mode based on whether a passphrase exists
if [ -z "$BORG_PASSPHRASE" ]; then
printf "No passphrase detected. Initializing with 'none' encryption.\n"
borg init --encryption=none
else
printf "Passphrase detected. Initializing with 'repokey' encryption.\n"
# repokey stores the key inside the repository config, protected by the passphrase
borg init --encryption=repokey
fi
init_exit=$?
if [ "$init_exit" -eq 0 ]; then
printf "\nSuccess: Repository initialized successfully.\n"
printf "You can now run your first backup using: sudo /opt/borg/bin/backup\n"
else
printf "\nError: Repository initialization failed (Exit code: %s).\n" "$init_exit"
exit "$init_exit"
fi