#!/bin/sh
# This script is designed to be called from a cron job, once per night.
# It tars the entire filesystem, and transports it via the network to a
# Samba share elsewhere.  It can also create a local copy of the file, if
# desired.
#
# Copyright (c) 2003-2007, Paul Kreiner


# Set some authentication options:
SMB_USERNAME="someuser"
SMB_PASSWORD="a_sekrit"
SMB_DOMAIN="SOMEDOMAIN"

# The server name and share name:
SMB_SERVER="servername"
SMB_SHARE="share name"

# Local copy of the file (optional, set to /dev/null if not using)
#LOCALFILE="/dev/null"
LOCALFILE="/mnt/storage/linux_system_backup.tgz"

# List of mount points to back up, path to log file, name/path of remote
# SMB tar file:
FILESYSTEMS="/ /boot /var /home /usr /tmp /mnt/storage"
LOGFILE="/var/log/backups-smb.log"
SMBFILE="linux_system_backup.tgz"



# Here we go...
# First, we create the tar-file, streaming over stdout to smbclient, so it
# gets created directly on the SMB share.
# We also 'tee' a copy of the file locally, to /mnt/storage.
# Next, assuming the backup went successfully, we then rename the new/temp
# backup file, overwriting the previous backup file.  This means we should 
# always have exactly ONE complete backup file stored on the SMB share.
# We redirect FD2 for both processes out to a local log file.

(
  (
	echo >> "${LOGFILE}" 1>&2 && \
	echo "--------------------" 1>&2 && \
	echo "BEGIN: " `date` 1>&2 && \
	echo "--------------------" 1>&2
  ) && ( /bin/tar -cvz --one-file-system \
      / /boot /var /home /usr /tmp | \
    /usr/bin/tee "${LOCALFILE}_temp" | \
    /usr/bin/smbclient \
      "//${SMB_SERVER}/${SMB_SHARE}" \
      "${SMB_PASSWORD}" \
      -U "${SMB_USERNAME}" \
      -W "${SMB_DOMAIN}" \
      -c "put - ${SMBFILE}_temp"
  ) && (
    /bin/mv -f "${LOCALFILE}_temp" "${LOCALFILE}" && \
    /usr/bin/smbclient \
      "//${SMB_SERVER}/${SMB_SHARE}" \
      "${SMB_PASSWORD}" \
      -U "${SMB_USERNAME}" \
      -W "${SMB_DOMAIN}" \
      -c "rm ${SMBFILE} ; ren ${SMBFILE}_temp ${SMBFILE}"
  ) && (
	echo "--------------------" 1>&2 && \
	echo "END (SUCCESS): " `date` 1>&2 && \
	echo 1>&2
  )
) 2>>"${LOGFILE}"


