#!/usr/bin/bash
# -*- mode: sh; sh-basic-offset: 3; indent-tabs-mode: nil; -*-
# vim: set filetype=sh sw=3 sts=3 expandtab autoindent:

# This file contains functions shared between ninjahelper and backupninja.

#####################################################
## MISC FUNCTIONS

#
# create a temporary file in a secure way.
#
function maketemp() {
   local tempfile=`mktemp /tmp/$1.XXXXXXXX`
   echo $tempfile
}

#
# compare version numbers.
# returns 0 if equal, 1 if $1>$2, and 2 if $1<$2
#

function compare_versions() {
   if [[ "$1" == "$2" ]]; then
      return 0
   fi
   local IFS=.
   local i version_1=($1) version_2=($2)
   for ((i=${#version_1[@]}; i<${#version_2[@]}; i++)); do
      version_1[i]=0
   done
   for ((i=0; i<${#version_1[@]}; i++)); do
      if [[ -z ${version_2[i]} ]]; then
         version_2[i]=0
      fi
      if ((10#${version_1[i]} > 10#${version_2[i]})); then
         return 1
      fi
      if ((10#${version_1[i]} < 10#${version_2[i]})); then
         return 2
      fi
   done
   return 0
}

#
# compare version numbers: >=
#

function version_ge() {
   compare_versions "$1" "$2"
   comp=$?
   [ $comp -eq 0 ] || [ $comp -eq 1 ]
}

#####################################################
## CONFIG-FILE RELATED FUNCTIONS

function setfile() {
   CURRENT_CONF_FILE=$1
}

function setsection() {
   CURRENT_SECTION=$1
}

#
# sets a global var with name equal to $1
# to the value of the configuration parameter $1
# $2 is the default.
#
function getconf() {
   CURRENT_PARAM=$1
   ret=`/usr/bin/awk -f $libdirectory/parseini S=$CURRENT_SECTION P=$CURRENT_PARAM $CURRENT_CONF_FILE`
   # if nothing is returned, set the default
   if [ "$ret" == "" -a "$2" != "" ]; then
      ret="$2"
   fi

   # replace * with %, so that it is not globbed.
   ret="${ret//\\*/__star__}"

   # this is weird, but single quotes are needed to
   # allow for returned values with spaces. $ret is still expanded
   # because it is in an 'eval' statement.
   eval $1='$ret'
}

function keeponly() {
    AMOUNT=$2
    DIRECTORY=$1

    # If directory exists
    if [ -d "${DIRECTORY}" ] && [ "${AMOUNT}" -gt 0 ]
    then
        # List directory in time sorting
        # Tail from amount (+1) which we remove as they are
        # too much
        LISTING=$(ls -1 -t "${DIRECTORY}" | tail -n +$((AMOUNT + 1)))
        for file in ${LISTING}
        do
            REMOVEFILE="${DIRECTORY}/${file}"
            if [ -f "${REMOVEFILE}" ]
            then
                rm -f "${REMOVEFILE}"
            fi
        done
    fi
}

function keeptimely() {
    AMOUNT=$3
    FROMDIR="$1"
    TODIR="$2"
    TIMECHAR=$4

    # Try to create directory where to store
    # stuff
    if [ ! -d "${TODIR}" ]
    then
        mkdir -p "${TODIR}"
        if [ ! -d "${TODIR}" ]
        then
            echo "Can't create: ${TODIR}"
            return 1
        fi
    fi

    # if from directory exist and amount is greater
    # than zero
    if [ -d "${FROMDIR}" ] && [ "${AMOUNT}" -gt 0 ]
    then
        LISTING=$(ls -1 -t "${FROMDIR}")
        OLDTIMELY=0
        OUTPUTDIR=""

        for file in ${LISTING}
        do
            FILELOCATION="${FROMDIR}/${file}"

            if [ -f "${FILELOCATION}" ]
            then
                # Get file epoch edit modify which likely is creation time
                FILEEPOCH=$(stat --format "%Z" "${FILELOCATION}")
                # Get out of week or month
                FILETIMELY=$(date -d @"${FILEEPOCH}" +%"${TIMECHAR}")
                # Create directory for that month or week
                OUTPUTDIR="${TODIR}/${FILETIMELY}"
                mkdir -p "${OUTPUTDIR}"

                if [ -d "${OUTPUTDIR}" ]
                then
                    # Copy stuff
                    cp -a "${FILELOCATION}" "${OUTPUTDIR}"
                else
                    echo "Can't create directory: ${OUTPUTDIR}"
                    continue
                fi

                if [ "${FILETIMELY}" -ne "${OLDTIMELY}" ]
                then
                    if [ "${OLDTIMELY}" -gt 0 ]
                    then
                        OLDLOCATION="${TODIR}/${OLDTIMELY}"
                        keeponly "${OLDLOCATION}" "${AMOUNT}"
                    fi
                    OLDTIMELY=${FILETIMELY}
                fi
            fi
        done

        # Make sure we run this at the end
        if [ -n "${OUTPUTDIR}" ] && [ -d "${OUTPUTDIR}" ]
        then
            keeponly "${OUTPUTDIR}" "${AMOUNT}"
        fi
    fi
}

function keepweekly() {
    keeptimely "$1" "$2" "$3" "W"
}

function keepmonthly() {
    keeptimely "$1" "$2" "$3" "m"
}

