Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add compressLogs Functionality to Bitwarden Self-Hosted (Bash) #225

Merged
merged 4 commits into from Mar 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
65 changes: 65 additions & 0 deletions bitwarden.sh
Expand Up @@ -123,6 +123,66 @@ function checkOutputDirNotExists() {
fi
}

function compressLogs() {
LOG_DIR=${1#$(pwd)/}/logs
START_DATE=$2
END_DATE=$3
tempfile=$(mktemp)

function validateDateFormat() {
if ! [[ $1 =~ ^[0-9]{8}$ ]]; then
echo "Error: $2 date format is invalid. Please use YYYYMMDD."
exit 1
fi
}

function validateDateOrder() {
if [[ $(date -d "$1" +%s) > $(date -d "$2" +%s) ]]; then
echo "Error: start date ($1) must be earlier than end date ($2)."
exit 1
fi
}

# Validate start date format
if [ -n "$START_DATE" ]; then
validateDateFormat "$START_DATE" "start"
if [ -z "$END_DATE" ]; then
echo "Error: an end date is required when an start date is provided."
exit 1
fi
fi

# Validate end date format and order
if [ -n "$END_DATE" ]; then
validateDateFormat "$END_DATE" "end"
validateDateOrder "$START_DATE" "$END_DATE"
fi

if [ -n "$START_DATE" ] && [ -n "$END_DATE" ]; then

OUTPUT_FILE="bitwarden-logs-${START_DATE}-to-${END_DATE}.tar.gz"

if [[ "$START_DATE" == "$END_DATE" ]]; then
OUTPUT_FILE="bitwarden-logs-${START_DATE}.tar.gz"
fi

for d in $(seq $(date -d "$START_DATE" "+%Y%m%d") $(date -d "$END_DATE" "+%Y%m%d")); do
# Find and list files matching the date in the filename and modification time, append to tempfile
find $LOG_DIR \( -type f -name "*$d*.txt" -o -name "*.log" -newermt "$START_DATE" ! -newermt "$END_DATE" \) -exec bash -c 'echo "${1#./}" >> "$2"' _ {} "$tempfile" \;
done

echo "Compressing logs from $START_DATE to $END_DATE ..."
else
OUTPUT_FILE="bitwarden-logs-all.tar.gz"
find $LOG_DIR -type f -exec bash -c 'echo "${1#./}" >> "$2"' bash {} "$tempfile" \;
echo "Compressing all logs..."
fi

tar -czvf "$OUTPUT_FILE" -T "$tempfile"
echo "Logs compressed into $(pwd $OUTPUT_FILE)/$OUTPUT_FILE"
rm $tempfile
}

function listCommands() {
cat << EOT
Available commands:
Expand All @@ -139,6 +199,7 @@ updateconf
uninstall
renewcert
rebuild
compresslogs
help

See more at https://bitwarden.com/help/article/install-on-premise/#script-commands-reference
Expand Down Expand Up @@ -195,6 +256,10 @@ case $1 in
checkOutputDirExists
$SCRIPTS_DIR/run.sh uninstall $OUTPUT
;;
"compresslogs")
checkOutputDirExists
compressLogs $OUTPUT $2 $3
;;
"help")
listCommands
;;
Expand Down