#!/bin/bash

amandaconf=uwe
# The scsi ID for /proc/scsi/scsi, it is needed because the device shows
# not up directly after hotplugging it
scsi_id='4 0 0 0'
# use nocache [https://github.com/Feh/nocache] if available
nocache=/usr/local/bin/nocache


### BEGIN Functions

# debian has cryptdisks_start, but fedora doesn't
function cryptdisks_start {
    local cte keyf
    cte=($(grep "$1" /etc/crypttab))
    [ -f ${cte[2]} ] && keyf="--key-file ${cte[2]}"
    cryptsetup luksOpen ${cte[1]} ${cte[0]} $keyf
}

# debian has cryptdisks_stop, but fedora doesn't
function cryptdisks_stop {
    local cte
    cte=($(grep "$1" /etc/crypttab))
    cryptsetup luksClose ${cte[0]}
}

# wait for some file to appear, with timeout and spinning wheel
# waitfor /some/file [maxiter [delay]]
function waitfor {
    local file=$1 maxiter=${2:-60} delay=${3:-0.5}
    local i=0 pi=('\b/' '\b-' '\b\' '\b|')
    echo -n "Waiting for $file:  "
    while [ ! -e "$1" ]; do
	echo -ne ${pi[$(($i%4))]}
	sleep $delay
	let i+=1
	[ $i -ge $maxiter ] && break
    done
    local tim=$(bc <<< "($i-1)*$delay")
    if [ -e $file ]; then
	echo -e "\bok after ${tim/.0}s"
	return 0
    else
	echo -e "\bnot there after ${tim/.0}s"
	return 1
    fi
}

# check if $1 is mounted
function mounted {
    /bin/grep "$1" /proc/mounts &> /dev/null
    return $?
}
### END Functions

# TODO: maybe drop separate mount points, although this would
#	remove parallel writers
tape=$(su backup -c "amadmin $amandaconf tape")
# amadmin has multiple output variants
# 1. "The next Amanda run should go onto tape uwe-401 or a new tape."
#   ==> get #8
# 2. "The next Amanda run should go onto 1 new tape. The next new tape
#    already labelled is: uwe-a01."
#   ==> get #17
# 3. "The next Amanda run should go onto tape uwe-401 or a new
#    tape.\nThe next new tape already labelled is: uwe-a02."
#   ==> get #20

echo $tape
disk=($tape)
tape=${disk[8]} # case 1 from above
if [ "${disk[8]}" = "new" ]; then
    # case 2 from above
    tape=${disk[17]%.}
elif [ -n "${disk[20]}" ]; then
    # case 3 from above
    tape=${disk[20]%.}
fi
echo "Please make sure tape/disk $tape is in the bay."
echo "/backup/$tape will be mounted, amdump and amstatus started."
echo "Please leave this running until the backup finished."
read -p "Press enter to proceed: "

# 2015-10-10 root: need to set SELinux to Permissive for now
# TODO: create SELinux policy
sestatus=/sbin/sestatus
if [ -x $sestatus ]; then
    enabled=$($sestatus | grep '^SELinux status:' | grep enabled)
    enforcing=$($sestatus | grep '^Current mode:' | grep enforcing)
    if [ -n "$enabled" -a -n "$enforcing"  ]; then
	echo "Disabling SELinux."
	I_disabled_selinux="yeah I dare"
	setenforce permissive
    fi
fi

# Set up SATA disk, open luks, mount filesystem
cte=($(grep "$tape" /etc/crypttab))
if [ ! -e "${cte[1]}" ]; then
    echo "scsi add-single-device $scsi_id"  > /proc/scsi/scsi
    waitfor ${cte[1]}
fi

# 2016-03-12 root: work around bz1227503
systemctl start bz1227503-workaround

if [ ! -e /dev/mapper/$tape ]; then
    cryptdisks_start $tape
    waitfor /dev/mapper/$tape
fi
if ! mounted /backup/$tape; then
    mount LABEL=$tape /backup/$tape
    [ $? -ne 0 ] && { echo "mount failed, bailing out."; exit 1; }
fi

# This should be temporary until all "tapes" are through
#chown -R backup:wheel /backup/$tape

# stop smartmontools and running smart tests so backup runs faster
service smartd stop
for dev in /dev/sd?; do
    echo -n "$dev:"
    smartctl -a $dev | grep remaining \
	&& { echo -e "\tstopping..."; smartctl -X $dev > /dev/null; } \
	|| echo "no selftest running"
done

sleep 5 # some time to read what happened up to now

# present status
watch -n 5 amstatus $amandaconf &
statuspid=$!

# TODO: nocache doesn't work this way, because amanda starts tar via its
# service. Use plugin "amgtar" and property "GNUTAR-PATH" set to a
# wrapper script that calls tar with nocache. OTOH, it doesn't hurt to
# start the dumpers with it as well.
if [ -x "$nocache" ]; then
    su - backup -c "$nocache amdump $amandaconf"
else
    su - backup -c "amdump $amandaconf"
fi

kill $statuspid

# make backup of important amanda files, too
date=$(env date -u +'%Y-%m-%dT%H:%M:%S_%Z')
tar czf /backup/$tape/amandastuff-$date.tgz /{etc,var/lib,var/log}/amanda

umount /backup/$tape \
&& cryptdisks_stop $tape \
&& { echo "scsi remove-single-device $scsi_id" > /proc/scsi/scsi; }

if [ -n "$I_disabled_selinux" ]; then
    echo "Enabling SELinux."
    setenforce enforcing
fi

service smartd start

