#!/bin/sh
# ----------------------------------------------------------------------
# /var/install/config.d/rsnapshot-update.sh -- paramater update script
#
# Creation:     2009-10-25 alex
# Last update:  $Id$
#
# Copyright (c) 2009,2011 the eisfair team, team(at)eisfair(dot)org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# ----------------------------------------------------------------------

#exec 2> /tmp/rsnapshot-update-trace_$$.log
#set -x

_PACKAGE_NAME='rsnapshot'

# includes
. /var/install/include/configlib
. /var/install/include/eislib
. /etc/default/${_PACKAGE_NAME}

# local variables
_ASK_FOR_EDIT=false
_TRIGGER_ANYKEY_AFTER_MIGRATION=false
_RSNAPSHOT_EIS_CONF_FILE="/etc/config.d/${_PACKAGE_NAME}"

# ----------------------------------------------------------------------
# Set the default values for configuration
# ----------------------------------------------------------------------
START_RSNAPSHOT='no'
RSNAPSHOT_BACKUP_TO_DIR='/data/backup/'
RSNAPSHOT_CREATE_ROOT='yes'

RSNAPSHOT_BACKUPS_PER_DAY='6'
RSNAPSHOT_WEEKLY_BACKUP_DAY='sat'
RSNAPSHOT_MONTHLY_BACKUPS_TO_KEEP='3'

RSNAPSHOT_BACKUP_LOCAL_N='2'
RSNAPSHOT_BACKUP_LOCAL_1_ACTIVE='no'
RSNAPSHOT_BACKUP_LOCAL_1_DIR='/etc/config.d'
RSNAPSHOT_BACKUP_LOCAL_2_ACTIVE='no'
RSNAPSHOT_BACKUP_LOCAL_2_DIR='/home'

# ----------------------------------------------------------------------
# Internal functions
# ----------------------------------------------------------------------

# working on variables sourced from config file in this script but
# outside of the _add_variables function
_add_variables()
{
    _added=false

    # v0.1.1
    if ! grep -q '^RSNAPSHOT_CREATE_ROOT' ${_RSNAPSHOT_EIS_CONF_FILE}
    then
        _echo_addvar_msg ${_added}
        mecho -std '- RSNAPSHOT_CREATE_ROOT'
        _added=true
    fi

    if ${_added}
    then
        mecho -warn '... read documentation for new parameter(s)!'
        _TRIGGER_ANYKEY_AFTER_MIGRATION=true
    fi
}

_delete_variables()
{
    _deleted=false

    if ${_deleted}
    then
        mecho -info '... no more parameters to delete ... ;-)'
        _TRIGGER_ANYKEY_AFTER_MIGRATION=true
    fi
}

# working on variables sourced from config file in this script but
# outside of the _modify_variables function
_modify_variables()
{
    _modified=false

    if ${_modified}
    then
        mecho -warn '... read documentation for modified parameter(s)!'
        _TRIGGER_ANYKEY_AFTER_MIGRATION=true
    fi
}

_rename_variables()
{
    _renamed=false

    if ${_renamed}
    then
        mecho -warn '... read documentation for renamed parameter(s)!'
        _TRIGGER_ANYKEY_AFTER_MIGRATION=true
    fi
}

# the following functions should only echo if the first argument
# is false, preventing double output of the message 
_echo_addvar_msg()
{
    if ! ${1}
    then
        mecho -info 'Adding new parameter(s) ...'
    fi
}

_echo_delvar_msg()
{
    if ! ${1}
    then
        mecho -info 'Deleting old parameter(s) ...'
    fi
}

_echo_modvar_msg()
{
    if ! ${1}
    then
        mecho -info 'Modifying parameter(s) ...'
    fi
}

_echo_renamevar_msg()
{
    if ! ${1}
    then
        mecho -info 'Renaming parameter(s) ...'
    fi
}

# create config and default file based on variables either declared as
# default here or sourced from some config file
_make_config_file()
{
    _internal_conf_file=${1}

    {
        # --------------------------------------------------------------
        printgpl -conf ${_PACKAGE_NAME} '2009-10-25' 'alex'
        # --------------------------------------------------------------

        # --------------------------------------------------------------
        printgroup 'Basic configuration'
        # --------------------------------------------------------------
        printvar 'START_RSNAPSHOT'          'Use: yes or no'
        printvar 'RSNAPSHOT_BACKUP_TO_DIR'  'Directory to store all backups in'
        printvar 'RSNAPSHOT_CREATE_ROOT'    'Create backup root dir if not present?'

        # --------------------------------------------------------------
        printgroup 'Backup times and amounts'
        # --------------------------------------------------------------
        printvar 'RSNAPSHOT_BACKUPS_PER_DAY'            '2, 3, 4, 6, 8 or 12 backups per day'
        printvar 'RSNAPSHOT_WEEKLY_BACKUP_DAY'          'First three letters of english weekdays'
        printvar 'RSNAPSHOT_MONTHLY_BACKUPS_TO_KEEP'    'How many month keep backups'

        # --------------------------------------------------------------
        printgroup 'Local backup jobs'
        # --------------------------------------------------------------
        printvar 'RSNAPSHOT_BACKUP_LOCAL_N' 'Number of local folders to backup'

        # Print at least two default values independent of N
        for _idx in 1 2
        do
            echo ''
            printvar "RSNAPSHOT_BACKUP_LOCAL_${_idx}_ACTIVE"    'Job active or not'
            printvar "RSNAPSHOT_BACKUP_LOCAL_${_idx}_DIR"       'Folder to backup'
        done

        # Now print possible additional values from real config. Note
        # that `seq 3 N` would give an empty list if N is less than 3
        # and the loop is not executed then. (inner lines just copied
        # from above!)
        for _idx in `seq 3 ${RSNAPSHOT_BACKUP_LOCAL_N}`
        do
            echo ''
            printvar "RSNAPSHOT_BACKUP_LOCAL_${_idx}_ACTIVE"    'Job active or not'
            printvar "RSNAPSHOT_BACKUP_LOCAL_${_idx}_DIR"       'Folder to backup'
        done

        # --------------------------------------------------------------
        printend
        # --------------------------------------------------------------
    } > ${_internal_conf_file}

    # Set rights
    chmod 0600 ${_internal_conf_file}
    chown root ${_internal_conf_file}
}

_make_check_files()
{
    # /etc/check.d/rsnapshot
    printgpl -check ${_PACKAGE_NAME} '2009-10-25' 'alex' > /etc/check.d/${_PACKAGE_NAME}
    cat >> /etc/check.d/${_PACKAGE_NAME} << EOFG
# Variable                          OPT_VARIABLE    VARIABLE_N                  VALUE
#
START_RSNAPSHOT                     -               -                           YESNO
RSNAPSHOT_BACKUP_TO_DIR             START_RSNAPSHOT -                           ABS_PATH
RSNAPSHOT_CREATE_ROOT               START_RSNAPSHOT -                           YESNO
#
RSNAPSHOT_BACKUPS_PER_DAY           START_RSNAPSHOT -                           RSNAPSHOT_BACKUPS_PER_DAY_CUI
RSNAPSHOT_WEEKLY_BACKUP_DAY         START_RSNAPSHOT -                           RSNAPSHOT_WEEKLY_BACKUP_DAY_CUI
RSNAPSHOT_MONTHLY_BACKUPS_TO_KEEP   START_RSNAPSHOT -                           NUMERIC
#
RSNAPSHOT_BACKUP_LOCAL_N            START_RSNAPSHOT -                           NUMERIC
RSNAPSHOT_BACKUP_LOCAL_%_ACTIVE     START_RSNAPSHOT RSNAPSHOT_BACKUP_LOCAL_N    YESNO
RSNAPSHOT_BACKUP_LOCAL_%_DIR        START_RSNAPSHOT RSNAPSHOT_BACKUP_LOCAL_N    ABS_PATH
EOFG

    # Set rights for check.d file
    chmod 0600 /etc/check.d/${_PACKAGE_NAME}
    chown root /etc/check.d/${_PACKAGE_NAME}

    # /etc/check.d/rsnapshot.exp
    printgpl -check_exp ${_PACKAGE_NAME} '2009-10-25' 'alex' > /etc/check.d/${_PACKAGE_NAME}.exp
    cat >> /etc/check.d/${_PACKAGE_NAME}.exp << EOFG
RSNAPSHOT_BACKUPS_PER_DAY_CUI   = '2|3|4|6|8|12'
                                : 'Choose between 2, 3, 4, 6, 8 and 12!'
RSNAPSHOT_WEEKLY_BACKUP_DAY_CUI = 'mon|tue|wed|thu|fri|sat|sun'
                                : 'Enter first three letters of english weekdays, e.g. "sat"!'
EOFG

    # Set rights for check.exp file
    chmod 0600 /etc/check.d/${_PACKAGE_NAME}.exp
    chown root /etc/check.d/${_PACKAGE_NAME}.exp

#    printgpl -check_ext ${_PACKAGE_NAME} '2009-10-25' 'alex' >/etc/check.d/${_PACKAGE_NAME}.ext
#    cat >> /etc/check.d/${_PACKAGE_NAME}.ext <<EOFG
#
#
#EOFG

    # Set rights for check.ext file
#    chmod 0600 /etc/check.d/${_PACKAGE_NAME}.ext
#    chown root /etc/check.d/${_PACKAGE_NAME}.ext
}

_make_logrotate_file()
{
    _creation_time=`date --iso-8601='seconds'`

    {
        echo '# -------------------------------------------------------'
        echo "# /etc/logrotate.d/${_PACKAGE_NAME} created by ${0}"
        echo '#'
        echo '# DO NOT EDIT THIS FILE BY HAND! (use eisfair setup!)'
        echo '#'
        echo "# Created: ${_creation_time}"
        echo '# -------------------------------------------------------'
        echo "${RSNAPSHOT_LOGFILE} {"
    } > /etc/logrotate.d/${_PACKAGE_NAME}

    cat >> /etc/logrotate.d/${_PACKAGE_NAME} << EOFG
    rotate 6
    monthly
    compress
    missingok
}
EOFG

    chmod 0600 /etc/logrotate.d/${_PACKAGE_NAME}
    chown root /etc/logrotate.d/${_PACKAGE_NAME}
}

# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------

# Create default config (/etc/config.d/$_PACKAGE_NAME not sourced yet),
# just using default values defined before in this script. Do this
# always, regardless if it already exists
_make_config_file /etc/default.d/${_PACKAGE_NAME}

# source config file if it exists and trigger variables update
# else just print that config will be created
if [ -f ${_RSNAPSHOT_EIS_CONF_FILE} ]
then
    # Updating config variables if old config exists
    mecho -info 'Updating configuration ...'
    . ${_RSNAPSHOT_EIS_CONF_FILE}

    #_rename_variables
    _modify_variables

    # add and delete variables just trigger some warnings, but so be it
    _add_variables
    #_delete_variables

    if ${_TRIGGER_ANYKEY_AFTER_MIGRATION}
    then
        anykey
    fi
else
    # Just rely on default values declared before in this script
    # and assuming an update trigger question for edit
    mecho -info 'Creating configuration ...'
    _ASK_FOR_EDIT=true
fi

# Write new config file in both cases
_make_config_file ${_RSNAPSHOT_EIS_CONF_FILE}

# Write check.d file and maybe check.exp and check.ext
_make_check_files

# Write logrotate file
_make_logrotate_file

mecho -info 'eisfair config update finished.'

# Write configuration, either after editing config or automatically when
# this is an update or config variables changed
if ${_ASK_FOR_EDIT}
then
    if /var/install/bin/ask "Edit ${_PACKAGE_NAME} configuration now?"
    then
        /var/install/bin/edit -apply ${_PACKAGE_NAME} "Edit ${_PACKAGE_NAME} configuration ..."
    else
        /var/install/config.d/${_PACKAGE_NAME}.sh --quiet
    fi
fi

exit 0
# ----------------------------------------------------------------------
# End
# ----------------------------------------------------------------------
