#!/bin/sh

################################################################################
# Script name:  dated_dir_creator_v1.2beta.sh                                  #
# Author:       SoD                                                            #
# Contact:      SoD- @ EFNet                                                   #
# Releasedate:  2001-08-09                                                     #
#                                                                              #
# This script is labeled as beta since I haven't tested it that much.          #
# This script is executed from crontab every midnight and then creates new     #
# dated dirs in the paths you've specified. It chmods them and if you want,    #
# creates symlinks to them. It lets you set the "closing-time" of yesterdays   #
# dir and it writes to glftpd.log in such a way that a bot can announce it.    #
# It also announces the total DAYUP and the DAYUP winner for every section.    #
#                                                                              #
# Installation: -Put this file in some approperiate place, for example         #
#                /glftpd/bin/dated_dir_creator.sh                              #
#               -Make it executable                                            #
#                (chmod 755 /glftpd/bin/dated_dir_creator_v1.1.beta2.sh)       #
#               -Make an entry in your crontab so that ths script is run at    #
#                midnight every day:                                           #
#                59 23 * * * /glftpd/bin/dated_dir_creator_v1.1.beta2.sh       #
#               -Edit this script to suit your needs                           #
#               -If you are using Darkheart's botscript you should add the     #
#                following 12 lines to sitebot-glftpd.api and then rehash it.: #
#                set chans(sectionname-NEW_DATED_DIR) " #channelname "         #
#                               ^-edit                       ^-edit            #
#                set chans(sectionname-CLOSED_DATED_DIR) " #channelname "      #
#                               ^-edit                          ^-edit         #
#                set chans(sectionname-TODAY_STATS) " #channelname "           #
#                               ^-edit                     ^-edit              #
#                set echovars(NEW_DATED_DIR) "name section archive_close_time" #
#                set echovars(CLOSED_DATED_DIR) "name section"                 #
#                set echovars(TODAY_STATS) "section dayup_user dayupuser_bytes dayup_section_bytes"
#                set enabled_announce(NEW_DATED_DIR) 1                         #
#                set enabled_announce(CLOSED_DATED_DIR) 1                      #
#                set enabled_announce(TODAY_STATS) 1                           #
#                set mask(NEW_DATED_DIR) "[b]\[%sitein NEW DATED DIR\][b] [b]%name[b] created in [b]%section[b] %archive_close_time"
#                set mask(CLOSED_DATED_DIR) "[b]\[%sitein CLOSED DIR\][b] [b]%name[b] in [b]%section[b] has been closed"
#                set mask(YESTERDAY_STATS) "[b]\[%sitein TODAY STATS\][b] Total uploaded in %section:[b]%dayup_section_bytes[b]MB. DAYUP winner:[b]%dayup_user[b] with [b]%dayupuser_bytes[b]MB."
#               -If you are using vShit's botscript you should add the         #
#                following 3 lines in the scanlog proc and then rehash it.:    #
#                NEW_DATED_DIR: {sndall "[b]\[$sitename NEW DATED DIR\][b] [b][lindex $args 0][b] created in [b][lindex $args 1][b] [lindex $args 2]"}
#                CLOSED_DATED_DIR: {sndall "[b]\[$sitename CLOSED DIR\][b] [b][lindex $args 0][b] in [b][lindex $args 1][b] has been closed"}
#                TODAY_STATS: {sndall "[b]\[$sitename TODAY STATS\][b] Total uploaded in [lindex $args 0]:[b][lindex $args 3][b]. DAYUP winner:[b][lindex $args 1][b] with [b][lindex $args 2][b]MB."}
#               -If you are using vrpack (1.6.0 Beta) botscript you should add #
#                the following 3 lines in the scanlog proc and then rehash it.:#
#                NEW_DATED_DIR: {sndall "\002\[$sns NEW DATED DIR\]\002 \002[lindex $args 0]\002 created in \002[lindex $args 1]\002 [lindex $args 2]"}
#                CLOSED_DATED_DIR: {sndall "\002\[$sns CLOSED DIR\]\002 \002[lindex $args 0]\002 in \002[lindex $args 1]\002 has been closed"}
#                TODAY_STATS: {sndall "\002\[$sns TODAY STATS\]\002 Total uploaded in [lindex $args 0]:\002[lindex $args 3]\002. DAYUP winner:\002[lindex $args 1]\002 with \002[lindex $args 2]\002MB."}
#                                                                              #
# Requirements: awk, chmod, cut, date, du, echo, expr, grep, let, ln, ls,      #
#               mkdir, rm, sleep, tr                                           #
#                                                                              #
# Limitations:  -Can't handle dirnames with spaces in them.                    #
#               -You might also wanna check the rules for symlinks inside      #
#                glftpd (glftpd.docs).                                         #
#                                                                              #
# Changelog:    v1.0 -> v1.1.beta:      Now handles an $ARCHIVE_CLOSING_TIME   #
#                                       of an infinite amount of hours.        #
#               v1.1.beta -> v1.2beta:  Fixed a bug that messed up the chmod   #
#                                       of yesterdays dir. Announcing also got #
#                                       fucked due to that. Also added a new   #
#                                       feature that lets you announce the     #
#                                       DAYUP winner for yesterdays dir, the   #
#                                       amount he has uploaded and the total   #
#                                       amount in yesterdays dir for every     #
#                                       section.                               #
# Changes in settings: Update botscript so it triggers on "YESTERDAY_STATS:"   #
#                      and edit crontab so this scrpt is executed at 23:59.    #
################################################################################

# Here you specify the dirs in were you want new dated dirs created. Sort them
# according to your stat_section in glftpd.conf (the first one from the top goes
# to the left here and so on). Use a trailing frontslash (/) for every path and
# separate them with a space.
PATHS="/glftpd/site/mp3/ /glftpd/site/0-day/"

# What do you want the botscript to call the sections, put in same order as
# $PATHS and separate them with a space ( eg, MP3, 0-DAY, DivX )
SECTION_NAMES="MP3 0-DAY"

# Whats the name and location of the symlinks to the "today"-dirs? Set it to "a"
# if you don't want a "today"-symlink. Put in same order as $PATHS and separate
# them with a space. Don't use a trailing frontslash (/).
SYMLINKS="/glftpd/site/today-mp3 /glftpd/site/today-0day"

# What name do you want the dated dirs to get? (eg, %m%d, %m-%d, %Y.%d.%m). This
# applies to all sections. These are a few options (taken from dates man-page):
# %a  -  locale's abbreviated weekday name (Sun..Sat)
# %b  -  locale's abbreviated month name (Jan..Dec)
# %d  -  day of month (01..31)
# %m  -  month (01..12)
# %Y  -  last two digits of year (00..99)
DIR_NAME="%m%d"

# How long after the creation of the new dated dirs shall creation of dirs be
# allowed in old dirs. (ie, for how long past midnight shall the users be
# allowed to upload in yesterdays dir). Put in same order as $PATHS and separate
# them with a space. Time in full hours (no 0.5, 2.5, ...).
ARCHIVE_CLOSING_TIME="0 1"

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

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

# What's the location of glftpds userfiles?
GL_USER_FILES="/glftpd/ftp-data/users/"

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

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

TODAY_DIR=`date -d '1 day' +$DIR_NAME`
YESTERDAY_DIR=`date +$DIR_NAME`
COUNTER=1

# This function writes DAYUP winner, the amount he uploaded and the total amount
# uploaded in every section to glftpd.log.
get_stats () {
    COUNT1=1
    COUNT3=0
    declare -a DAYUP_ARRAY
    declare -a SECTION_DAYUP_ARRAY
    # How many sections are there?
    NUM_OF_SECTIONS=`grep -c "^stat_section" $GL_CONF_FILE`

    # Loop through all sections
    until [ $NUM_OF_SECTIONS -eq 0 ]; do
        # Store all DAYUP values for the current section into an array
        DAYUP_ARRAY=(`grep "^DAYUP" $GL_USER_FILES* | \
        cut -d " " -f\`expr $COUNT1 + 2\` | tr -s '\n' ' '`)

        COUNT2=0
        # Find the DAYUP user and the amount he has uploaded and store the info
        # in the array $SECTION_DAYUP_ARRAY
        if [ ${DAYUP_ARRAY[$COUNT2]} -ge ${DAYUP_ARRAY[$COUNT2+1]} ]; then
            DAYUP="${DAYUP_ARRAY[$COUNT2]}"
            DAYUP_USER=`ls -l $GL_USER_FILES* | awk '{print $9}' | 
            awk -F "/" '{print $NF}' | tr -s '\n' ' ' | cut -d " " -f1`
        fi
        while [ ${DAYUP_ARRAY[$COUNT2]} ] && [ ${DAYUP_ARRAY[$COUNT2+1]} ]; do
            # Compare the elements with eachother and find the highest value
            if [ ${DAYUP_ARRAY[$COUNT2]} -lt ${DAYUP_ARRAY[$COUNT2+1]} ]; then
                DAYUP="${DAYUP_ARRAY[$COUNT2+1]}"
                DAYUP_USER=`ls -l $GL_USER_FILES* | awk '{print $9}' | \
                awk -F "/" '{print $NF}' | tr -s '\n' ' ' | 
                cut -d " " -f \`expr $COUNT2 + 2\``
            fi
            let COUNT2=$COUNT2+1
        done
        if [ $DAYUP -eq 0 ];then
            DAYUP_USER="NA"
        fi
        SECTION_DAYUP_ARRAY[$COUNT3]=$DAYUP_USER
        SECTION_DAYUP_ARRAY[$COUNT3+1]=$DAYUP
        let COUNT1=$COUNT1+3
        let COUNT3=$COUNT3+2
        let NUM_OF_SECTIONS=$NUM_OF_SECTIONS-1
    done

    COUNT1=0
    COUNT2=1
    # Write yesterdays DAYUP and DAYDN to glftpd.log (for announcing).
    while [ ${SECTION_DAYUP_ARRAY[$COUNT1]} ]; do
        YUIOP=`du -sm \`echo $PATHS | cut -d " " -f$COUNT2\`$YESTERDAY_DIR | \
        awk '{print $1}'`
        ASDF=`echo \`date +"%a %b %d %T %Y"\` TODAY_STATS: \
        \`echo $SECTION_NAMES | cut -d " " -f$COUNT2\` \
        ${SECTION_DAYUP_ARRAY[$COUNT1]} \
        \`expr ${SECTION_DAYUP_ARRAY[$COUNT1+1]} / 1024\` $YUIOP`
        echo $ASDF >> $GL_LOG_FILE
        let COUNT1=$COUNT1+2
        let COUNT2=$COUNT2+1
    done
    sleep 1m
}

# Write stats-info to glftpd.log if $ANNOUNCE=y
if [ $ANNOUNCE = y ]; then
    get_stats
else
    # Wait until its past midnight
    sleep 1m
fi

# This function chmod's the yesterday dir (and announces it)
chmod_yesterday_dir () {
    sleep `echo $ARCHIVE_CLOSING_TIME | cut -d " " -f$1`h
    chmod 555 `echo $PATHS | cut -d " " -f$1`$YESTERDAY_DIR
    if [ $ANNOUNCE = y ] && [ $ARCHIVE_CLOSE_TIME -gt 0 ]; then
        echo `date +"%a %b %d %T %Y"` CLOSED_DATED_DIR: \
        "`date -d "\`echo $ARCHIVE_CLOSING_TIME | \
        cut -d " " -f$1\` hour 1 min ago" +$DIR_NAME`" `echo $SECTION_NAMES | \
        cut -d " " -f$1` >> $GL_LOG_FILE
    fi
}

# Loop through all $PATHS.
for PATHH in $PATHS; do
    # Make the new dated dir and change its and yesterday dirs permissions
    if [ ! -e "$PATHH$TODAY_DIR" ]; then
        mkdir $PATHH$TODAY_DIR
        chmod 777 $PATHH$TODAY_DIR
    fi
    ARCHIVE_CLOSE_TIME=`echo $ARCHIVE_CLOSING_TIME | cut -d " " -f$COUNTER`
    SECTION_NAME=`echo $SECTION_NAMES | cut -d " " -f$COUNTER`
    chmod_yesterday_dir `echo $COUNTER` &

    # Remove old symlink, get the name of the one to create and create it
    if [ `echo $SYMLINKS | cut -d " " -f$COUNTER` != "a" ]; then
        rm -f `echo $SYMLINKS | cut -d " " -f$COUNTER`
        COUNT=1
        # Compare path to dir with path to symlink char by char,stop at mismatch
        while [ `echo $PATHH | cut -c$COUNT` = `echo $SYMLINKS | \
            cut -d " " -f$COUNTER | cut -c$COUNT` ]; do
            let COUNT=$COUNT+1
        done;
        let COUNT=$COUNT-1
        # Fix so that the last char in the path to the dir is a '/'
        while [ `echo $PATHH | cut -c$COUNT` != "/" ]; do
            let COUNT=$COUNT-1
        done
        # Remove the trailing '/'
        let COUNT=$COUNT-1
        COMMON_PATH=`echo $PATHH | cut -c1-$COUNT`
        DIFFERENCE=`echo ${PATHH#${COMMON_PATH}}`
        SYMLINK_SOURCE=`echo "./"$DIFFERENCE$TODAY_DIR`
        SYMLINK_DESTINATION=`echo $SYMLINKS | cut -d " " -f$COUNTER`
        ln -s $SYMLINK_SOURCE $SYMLINK_DESTINATION
      fi

    # Write new-dir-info to glftpd.log and call get_stats() if $ANNOUNCE=y
    if [ $ANNOUNCE = y ]; then
        if [ $ARCHIVE_CLOSE_TIME -eq 0 ]; then
            echo `date +"%a %b %d %T %Y"` NEW_DATED_DIR: "`date +$DIR_NAME`" \
            "$SECTION_NAME" \"\(archive has been closed\)\" >> $GL_LOG_FILE
        elif [ $ARCHIVE_CLOSE_TIME -eq 1 ]; then
            echo `date +"%a %b %d %T %Y"` NEW_DATED_DIR: "`date +$DIR_NAME`" \
            "$SECTION_NAME" \"\(archive will be closed in 1 hour\)\" >> \
            $GL_LOG_FILE
        elif [ $ARCHIVE_CLOSE_TIME -gt 1 ]; then
            echo `date +"%a %b %d %T %Y"` NEW_DATED_DIR: "`date +$DIR_NAME`" \
            "$SECTION_NAME" \"\(archive will be closed in $ARCHIVE_CLOSE_TIME \
            hours\)\" >> $GL_LOG_FILE
        fi
    fi
    let COUNTER=$COUNTER+1
done;
wait
exit