diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7516a2a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,16 @@ +FROM alpine + +RUN apk add --no-cache curl sqlite + +RUN rm /etc/crontabs/root +RUN mkdir /usr/local/app +RUN adduser -D -h /usr/local/app backup + + +WORKDIR /usr/local/app + +COPY entrypoint.sh backup.sh reload.sh initdb.sql /usr/local/app/ + +ENV USER=backup + +ENTRYPOINT /usr/local/app/entrypoint.sh diff --git a/backup.sh b/backup.sh index 2e51687..918fcb1 100755 --- a/backup.sh +++ b/backup.sh @@ -1,4 +1,4 @@ -#!/bin/bash +#!/bin/sh set -euo pipefail @@ -14,7 +14,7 @@ function extract() { usage "$0 " exit 1 fi - echo "select $1 from files where id=$id" | sqlite3 db.sqlite + echo "select $1 from files where id=$id" | sqlite3 db/db.sqlite } # Extract variables from database diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100755 index 0000000..30327ce --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,51 @@ +#!/bin/sh + +set -u + +# This script run as root (as crond needs to be root). +# But the crontab user is different so the work is done by user $USER +echo "The cronjobs will be run as user '$USER'" + +while true ; do + + # Database init if needed + if [ ! -e "db/db.sqlite" ] ; then + mkdir db + touch db/db.sqlite + chown "$USER:$USER" db -R + su "$USER" -c "sqlite3 db/db.sqlite" < initdb.sql + fi + + cronfile="/etc/crontabs/$USER" + + echo -n '' > "$cronfile" + tmp="$(mktemp)" + echo 'select id,crontab_time from files' | sqlite3 db/db.sqlite > "$tmp" + while read res ; do + id="$(echo "$res" | cut -d '|' -f 1)" + cron_raw="$(echo "$res" | cut -d '|' -f 2)" + # Trim + cron_raw="$(echo "$cron_raw" | sed -e 's/^[[:space:]]\+//' -e 's/[[:space:]]\+$//')" + # only get valid cron times + cron="$(echo "$cron_raw " | grep -oE '^(([[:digit:]]+|\*)[[:space:]]+){3}$')" + if [ -z "$cron" ] ; then + echo "Invalid cron times for id=$id : '$cron_raw'" + continue + fi + echo "$id 5 $cron backup.sh $id" >> "$cronfile" + + done <"$tmp" + rm "$tmp" + + # Reglementary empty line at the end + echo '' >> "$cronfile" + + # run cron and log + date >> /var/log/cron.log + crond -L /var/log/cron.log & + tail -f /var/log/cron.log + + # Clean + killall crond + +done diff --git a/reload.sh b/reload.sh new file mode 100755 index 0000000..2b49391 --- /dev/null +++ b/reload.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +killall tail