#!/bin/sh -efu

. shell-error
. shell-quote

# definitions
bacula_db_name=bacula
bacula_daemon_list='dir fd sd'
bacula_magic_string='#generated by bacula-sh-functions'

# directories
bacula_sysconf_dir=/etc/bacula
bacula_localstate_dir=/var/lib/bacula
bacula_pid_dir=/var/run/bacula
bacula_script_dir=/usr/share/bacula/scripts

# files
bacula_db_file="$bacula_localstate_dir/$bacula_db_name.db"
bacula_dir_file="$bacula_sysconf_dir/bacula-dir.conf"
bacula_fd_file="$bacula_sysconf_dir/bacula-fd.conf"
bacula_sd_file="$bacula_sysconf_dir/bacula-sd.conf"
bacula_console_file="$bacula_sysconf_dir/bconsole.conf"

bacula_fileset_file="$bacula_sysconf_dir/fileset/fullset.conf"
bacula_device_file="$bacula_sysconf_dir/device/filestorage.conf"

bacula_fullset_schedule_file="$bacula_sysconf_dir/schedule/weeklycycle.conf"
bacula_catalog_schedule_file="$bacula_sysconf_dir/schedule/weeklycycleafterbackup.conf"

### common daemon work

bacula_daemon_status()
{
    local IFS=' '
    local runlevel="$(/sbin/runlevel | cut -c3)"
    for i in $bacula_daemon_list; do
	LANG=C LC_ALL=C /sbin/chkconfig --list bacula-$i|grep -qs "${runlevel}:on" || return 1
	/sbin/service bacula-$i status >/dev/null || return 1
    done
    return 0
}

bacula_daemon_on()
{
    bacula_daemon_status ||
	for i in $bacula_daemon_list; do
	    /sbin/chkconfig bacula-$i on
	    /sbin/service bacula-$i start >&2
	done
}

bacula_daemon_off()
{
    for i in $bacula_daemon_list; do
	/sbin/service bacula-$i stop >&2
	/sbin/chkconfig bacula-$i off
    done
}

bacula_daemon_condreload()
{

    for i in $bacula_daemon_list; do
	/sbin/service bacula-$i condreload >&2
    done
}

### jobs
chomp()
{
    #clear spaces and tabs
    echo "$1"|sed -e 's/^[[:space:]]\+//' -e 's/[[:space:]]\+$//'
}

bacula_list_jobs()
{
    bacula_daemon_status || return 0

    echo "list jobs"|
	bconsole -c "$bacula_console_file"|
	while IFS='|' read start jobid jobname jobtime jobtype joblevel jobfiles jobbytes jobstatus; do
	    echo "$jobid"|grep -qs '[[:space:]]*[[:digit:]]\+[[:space:]]' || continue
	    printf '%s\t%s\t%s\n' "$(chomp "$jobname")" "$(chomp "$jobstatus")" "$(chomp "$jobtime")"
	done
}

bacula_run_job()
{
    bacula_daemon_status || return 0

    bconsole -c "$bacula_console_file"<<EOF
run $1
yes
EOF
}

bacula_mark_path()
{
    local dir="${1%/*}"
    local base="${1##*/}"

    [ "$dir" != "$1" ] || return 0

    local IFS='/'
    for i in $dir; do
	[ -n "$i" ] || continue
	printf 'cd %s\n' "$i"
    done

    printf 'mark %s\n' "$base"
}

bacula_restore_file()
{
    bacula_daemon_status || return 0

    local date="$1";shift
    local file="$1";shift

    bconsole -c "$bacula_console_file"<<EOF
restore
6
$date 23:59:00
$(bacula_mark_path "$file")
done
mod
9
/
yes
EOF
}

bacula_purge_volume()
{
    bacula_daemon_status || return 0

    local pool_id="$(bacula_list_pools| sed -n 's/\([[:digit:]]\+\)[[:space:]]\+Default$/\1/p')"
    [ -n "$pool_id" ] || return 0
    bconsole -c "$bacula_console_file"<<EOF
purge
3
$pool_id
b0001
EOF
}

### setup path

bacula_list_local_fs()
{
     mount -t ext2,ext3,ext4,xfs,ntfs-3g,vfat,msdos,jfs|cut -f3 -d' '
}

bacula_set_path()
{
    local backup_path="$1";shift
    local exclude_path="$1";shift

    local backup_dir="$backup_path/backup"

    [ -d "$backup_dir" ] ||
	install -d  -m750 --owner bacula --group root "$backup_dir"

    cat>"$bacula_fileset_file"<<EOF
FileSet {
  Name = "Full Set"
  Include {
    Options {
      signature = MD5
    }
$(bacula_list_local_fs|sed 's/.*/    File = &/')
  }

  Exclude {
    File = $backup_dir
$([ -z "$exclude_path" ] || printf '    File = %s\n' "$exclude_path")
    File = /proc
    File = /sys
    File = /dev
    File = /tmp
    File = /.journal
    File = /.fsck
  }
}
EOF

    cat>"$bacula_device_file"<<EOF
Device {
  Name = FileStorage
  Media Type = File
  Archive Device = "$backup_dir"
  LabelMedia = yes;
  Random Access = Yes;
  AutomaticMount = yes;
  RemovableMedia = no;
  AlwaysOpen = no;
}
EOF
    bacula_daemon_condreload
}

### setup time

bacula_catalog_time()
{
    export IFS=':'
    set -- $1
    local full="$(($1*3600 + $2*60 + $3 + 60))"
    local hour="$(( ($full / 3600) % 24 ))"
    local rest="$(( $full % 3600 ))"
    printf '%02d:%02d:%02d\n' "$hour" "$(( $rest / 60 ))" "$(( $rest % 60))"
}


bacula_set_time()
{
    local fullset_time="$1";shift
    local catalog_time="$(bacula_catalog_time "$fullset_time")"

    fullset_time="${fullset_time%:*}"
    catalog_time="${catalog_time%:*}"

    cat >"$bacula_fullset_schedule_file"<<EOF
Schedule {
  Name = "WeeklyCycle"
  Run = Full 1st sun at $fullset_time
  Run = Differential 2nd-5th sun at $fullset_time
  Run = Incremental mon-sat at $fullset_time
}
EOF

    cat>"$bacula_catalog_schedule_file"<<EOF
Schedule {
  Name = "WeeklyCycleAfterBackup"
  Run = Full sun-sat at $catalog_time
}
EOF
    bacula_daemon_condreload
}

### more high level job processing

bacula_list_backup()
{
    bacula_list_jobs|
	grep '^BackupFullSet[[:space:]]\+'|
	sort -r -k3,4
}

bacula_run_backup()
{
    bacula_run_job BackupFullSet >&2
}

bacula_oldest_backup()
{
    bacula_list_backup|
	grep -v '0$'|
	tail -n1|
	cut -f3
}

bacula_latest_backup()
{
    bacula_list_backup|
	grep -v '0$'|
	head -n1|
	cut -f3
}

bacula_list_pools()
{
    echo "list pools"|
	bconsole -c "$bacula_console_file"|
	sed -n 's/|[[:space:]]*\([[:digit:]]\+\)[[:space:]]*|[[:space:]]*\([[:alnum:]]\+\)[[:space:]].*/\1	\2/p'
}
