#!/bin/bash

################################################################################
# Script name:  free_space_v1.0.sh                                             #
# Author:       SoD                                                            #
# Contact:      SoD- @ EFNet                                                   #
# Releasedate:  2001-05-01                                                     #
#                                                                              #
# This script runs in crontab at an approperiate interval and then deletes     #
# directorys until a specified amount of space is free. This script only       #
# deletes directly inside the specified incomingpath, thus it cannot be used   #
# were you have "nested" dirs (CD1, CD2, sample and such does not qualify as   #
# nested). If you have a dated dir structure you should use my other script,   #
# free_space_dated_dirs_v1.0.sh. This script is meant for iso/vcd/divx/ and    #
# sections were you normally dont have dated dirs. You can specify how much    #
# space the section is allowed to contain, letting you have multiple sections  #
# on one device. The script deletes the dirs by their modification time and    #
# writes to glftpd.log so that a botscript can announce it (see below on how   #
# to configure the botscripts). The script does something like this:           #
# * Deleting any nuked directorys inside incomingpath if they are older than   #
#   specified by $DELETE_NUKES_TIME                                            #
# * Deleting oldest directory inside incomingpath                              #
# * Repeats above in the "next" dated dir until enough space is free           #
#                                                                              #
# Installation: -Put this file in some approperiate place, for example         #
#                /glftpd/bin/free_space_v1.0.sh                                #
#               -Make it executable (chmod 755 /glftpd/bin/free_space_v1.0.sh) #
#               -Edit your crontab (crontab -e) and write something like:      #
#                0,20,40 * * * * /glftpd/bin/free_space_v1.0.sh                #
#               -Edit this script to suit your setup                           #
#               -Test the script -ADViCE: EXECUTE THiS SCRiPT MANUALLY (ROW BY #
#                ROW) THE FiRST TiME (use /bin/ls instead of just ls)          #
#               -If you are using Darkheart's botscript you should add the     #
#                following 4 lines to sitebot-glftpd.api and then rehash it.:  #
#                set chans(sectionname-AUTODEL) " #channelname "               #
#                               ^-edit                 ^-edit                  #
#                set echovars(AUTODEL) "size section deldir"                   #
#                set enabled_announce(AUTODEL) 1                               #
#                set mask(AUTODEL) "[b]\[%sitein AUTO-DELETE\][b] system freed [b]%size MB[b] in [b]%section[b] by deleting [b]%deldir[b]"
#               -If you are using vShit's botscript you should add the         #
#                following line in the scanlog proc and then rehash it.:       #
#                AUTODEL: {sndall "[b]\[$sitename AUTO-DELETE\][b] system freed [b][lindex $args 0] MB[b] in [b][lindex $args 1][b] by deleting [b][lindex $args 2][b]"}
#               -If you are using vrpack (1.6.0 Beta) botscript you should add #
#                the following line in the scanlog proc and then rehash it.:   #
#                AUTODEL: {sndall "\002\[$sns AUTO-DELETE\]\002 system freed \002[lindex $args 0] MB\002 in \002[lindex $args 1]\002 by deleting \002[lindex $args 2]\002"}
#                                                                              #
# Requirements: awk, cut, date, df, du, echo, expand, expr, grep, ls, rm,      #
#               tail, tr                                                       #
#                                                                              #
# Limitations:  -Can only handle dirnames without spaces.                      #
#               -Only one section can be handled, use multiple instances of    #
#                this script, 1 per section if you have multiple sections.     #
#                                                                              #
################################################################################

# How many Megabyte shall be kept free? ( free space when script exits )
MIN_FREE_SPACE=500

# If you only want to use a part of the device for the section this script keeps
# free you can set that amount (in MB) here. If you want to use the entire
# device, set this to 0 (zero). The above setting is nescessary too.
# WARNING! This setting forces the script to use this value as the capacity of
# the device, so make shure there's at least this much space free.
MAX_SPACE_ALLOWED=0

# Where are the dirs to be freed located? ( eg, /glftpd/site/iso/ )
# Use a trailing frontslash (/).
INCOMINGPATH="/glftpd/site/iso/"

# Put any dirs you don't want deleted here (directly inside INCOMINGPATH). Put
# a dash directly followed by a capitol "i" (I) before every dirname. Also, 
# separate them with space and DON'T use a trailing frontslash (/).
EXCLUDE_DIRS="-I temp -I lost+found -I pics.of.my.gf(doing_it_with_the_dog)"

# Do you want the script to write to glftpd.log? (for announcing) [y/n]
ANNOUNCE=y

# How long shall a nuked dir stay on site (in hours) before it's deleted?
DELETE_NUKES_TIME=48

# What do you want the botscript to call the section? ( eg, MP3, iSO, DivX )
SECTION_NAME=iSO

# What's the location of glftpd.conf?
GL_CONFIG_FILE="/etc/glftpd.conf"

# What's the location of glftpd.log?
GL_LOG_FILE="/glftpd/ftp-data/logs/glftpd.log"

################################################################################
# No more specifications needed below,just some editing if the script won't work
################################################################################

# Abort the script at first error ( when a command exits with non-zero status )
set -e

# Scan glftpd.conf for the nukestyle
NUKED_DIR_NAMES=`grep nukedir_style -i $GL_CONFIG_FILE | grep -v '#' | \
awk '{print $2}' | awk -F "-%" '{print $1}'`

# Check for disk usage/free space
if [ $MAX_SPACE_ALLOWED -eq 0 ]; then
    FREE_ON_DEVICE=`df -m $INCOMINGPATH | grep "/dev/" | awk '{print $4}'`
else
    SPACE_USED=`du -sm $INCOMINGPATH | awk '{print $1}'`
    FREE_ON_DEVICE=`expr $MAX_SPACE_ALLOWED - $SPACE_USED`
fi

# Loop until enough space has been freed
until [ $FREE_ON_DEVICE -gt $MIN_FREE_SPACE ]; do

    # Find oldest nuked dir and its modification time
    DEL_DIR=`ls -lt $EXCLUDE_DIRS $INCOMINGPATH | grep $NUKED_DIR_NAMES | \
    tail -n 1 | awk '{print $9}' | tr -d '/'`
    TMP=`date -d "\`ls -lt --full-time $EXCLUDE_DIRS $INCOMINGPATH | \
    grep $NUKED_DIR_NAMES | tail -n 1 | expand | tr -s " " | \
    cut -d " " -f6-10\`" +%s`

    # Delete oldest nuked dir if it's older then $DELETE_NUKES_TIME. Otherwise
    # delete the oldest dir. Also get the size for the botscript.
    if [ `expr '(' \`date +%s\` - $TMP ')' / 3600` -gt $DELETE_NUKES_TIME ] \
    && [ $DEL_DIR ]; then
        DEL_DIR_SIZE=`du -sm $INCOMINGPATH$DEL_DIR | awk '{print $1}'`
        rm -fr $INCOMINGPATH$DEL_DIR
    else
        DEL_DIR=`ls -lt $EXCLUDE_DIRS $INCOMINGPATH | tail -n1 | \
        awk '{print $9}' | tr -d '/'`
        if [ $DEL_DIR ]; then
            DEL_DIR_SIZE=`du -sm $INCOMINGPATH$DEL_DIR | awk '{print $1}'`
            rm -fr $INCOMINGPATH$DEL_DIR
        fi
    fi

    # Announce deletion if $ANNOUNCE is set to "y"
    if [ $ANNOUNCE = y ]; then
        echo `date +"%a %b %d %T %Y"` AUTODEL: "$DEL_DIR_SIZE" "$SECTION_NAME" \
        "$DEL_DIR" >> $GL_LOG_FILE
    fi

    # Are enough files deleted?
    if [ $MAX_SPACE_ALLOWED -eq 0 ]; then
        FREE_ON_DEVICE=`df -m $INCOMINGPATH | grep "/dev/" | awk '{print $4}'`
    else
        SPACE_USED=`du -sm $INCOMINGPATH | awk '{print $1}'`
        FREE_ON_DEVICE=`expr $MAX_SPACE_ALLOWED - $SPACE_USED`
    fi
done
exit