Skip to content

Instantly share code, notes, and snippets.

@tyrm
Created February 28, 2024 17:31
Show Gist options
  • Save tyrm/32f9c8cc692b24f8a84acd82389d3a0d to your computer and use it in GitHub Desktop.
Save tyrm/32f9c8cc692b24f8a84acd82389d3a0d to your computer and use it in GitHub Desktop.
apt-rsync.sh
#!/bin/bash -e
# source config
. ~/.syncconf
REPO_ID=$1
if [ -z "$REPO_ID" ]; then
echo "Repo ID is empty."
exit 1
fi
function do_rsync() {
APT_MIRROR=$1
STORAGE_PATH=$2
mkdir -p $STORAGE_PATH
rsync \
--recursive \
--links \
--perms \
--times \
--compress \
--progress \
--delete \
$APT_MIRROR \
$STORAGE_PATH
return $?
}
function send_telegram_message() {
MESSAGE_BODY=$1
DISABLE_NOTIFICATION=$2
curl -sS -X POST \
-H "Content-Type: application/json" \
-d "{\"chat_id\": \"${CHAT_ID}\", \"text\": \"$(hostname -A)\\n${MESSAGE_BODY}\", \"disable_notification\": ${DISABLE_NOTIFICATION}}" \
https://api.telegram.org/bot${TELEGRAM_TOKEN}/sendMessage > /dev/null
}
function telegram_info() {
MESSAGE_BODY=$1
send_telegram_message "🔵 sync> ${MESSAGE_BODY}" true
}
function telegram_fail() {
MESSAGE_BODY=$1
send_telegram_message "🔴 sync> ${MESSAGE_BODY}" true
}
function telegram_warn() {
MESSAGE_BODY=$1
send_telegram_message "🟡 sync> ${MESSAGE_BODY}" true
}
function telegram_success() {
MESSAGE_BODY=$1
send_telegram_message "🟢 sync> ${MESSAGE_BODY}" true
}
############
# PID LOCK #
############
lockfile="/run/apt_rsync.lock"
# Exit if lockfile exists and the process is running
if [ -e "$lockfile" ]; then
# Check if the PID in lockfile is still running
old_pid=$(cat "$lockfile")
if [ -e "/proc/$old_pid" ]; then
telegram_warn "Not syncing ${REPO_ID} because a sync is in progress." true
echo "Script is already running."
exit 1
else
telegram_info "Found stale lock file. Removing it." true
echo "Found stale lock file. Removing it."
rm -f "$lockfile"
fi
fi
# Create a new lock file with the current PID
echo $$ > "$lockfile"
# Define a cleanup function
cleanup() {
rm -f "$lockfile"
exit
}
# Set trap to call cleanup function on script exit
trap cleanup EXIT
###########
# le sync #
###########
telegram_info "Starting sync of ${REPO_ID}." true
do_rsync ${APT_MIRROR}${REPO_ID} ${STORAGE_PATH}${REPO_ID}
exit_status=$?
# Check if rsync command was successful
if [ $exit_status -eq 0 ]; then
telegram_success "Sync of ${REPO_ID} completed successfully." true
echo "rsync completed successfully"
else
telegram_fail "Sync of ${REPO_ID} failed." true
echo "rsync failed with exit status $exit_status"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment