#!/bin/zsh
START_TIME=$(date -u +"%H:%M") 
STOP_TIME="N/A"
UPLOAD_START_TIME="N/A"
UPLOAD_STOP_TIME="N/A"

if [ "$2" != "" ]; then
    export LANG=$2
else
    export LANG=en_US.ISO8859-1
fi

export SP=$(dirname $0)
export CFG_NAME=$1
source $SP/setup initial
source $SP/mail

#-- Update sources -----------------------------------------------------------
printi "Starting $LANG nightly build on $CFG_NAME..."
zsh $SP/update
if [ $? != 0 ]; then
    printe "Updating sources FAILED! ABORTING SCRIPT!"
    
    STOP_TIME=$(date -u +"%H:%M")
    
    mail_start "FAILED COMPLETELY"
    mail_write ""
    mail_write "Updating sources FAILED! Please see attached log."
    
    mail_send "-a$LOG_BASE/update.log"
    
    mail_stop
    
    exit 5
fi

#-- Pre-build crosstools -----------------------------------------------------
if [ "$CFG_PREBUILD_TOOLCHAIN_PACKAGE" != "none" ]; then
    # Place the package indicated as crosstools as first package
    CFG_PACKAGES=($CFG_PREBUILD_TOOLCHAIN_PACKAGE ${CFG_PACKAGES[@]})
fi

#-- Build packages -----------------------------------------------------------
failed=()
succeeded=()
for package in $CFG_PACKAGES; do
    printe "package $package[(ws:.:)1]-$package[(ws:.:)3]"
    zsh $SP/pkg/$package[(ws:.:)1]-$package[(ws:.:)3]
    if [ $? != 0 ]; then
        printe "Build of package '"$package[(ws:.:)1]-$package[(ws:.:)3]"' FAILED."
        failed=( $failed $package[(ws:.:)1]-$package[(ws:.:)3] )
    else
        printi "Build of package '"$package[(ws:.:)1]-$package[(ws:.:)3]"' completed successfully."
        succeeded=( $succeeded $package[(ws:.:)1]-$package[(ws:.:)3] )
    fi
done

#-- Cleanup ------------------------------------------------------------------
setl cleanup.log
source $SP/cleanup
resetl

#-- Compress log files -------------------------------------------------------
printi "Compressing log files..."
pushd
cd $LOG_BASE
for file in *.log; do
    bzip2 $file
    md5sum $file.bz2 >$file.bz2.md5
done
popd

STOP_TIME=$(date -u +"%H:%M")

#-- Fix permissions ----------------------------------------------------------
chmod -R o-wx,g+wr Archive/
find Archive/ -type d | xargs chmod a+s,g+rwx,o+x

#-- Upload (backup and distribution) -----------------------------------------
printi "Uploading archives..."
if [ "$CFG_UPLOAD_ENABLE" = "yes" ]; then
    UPLOAD_START_TIME=$(date -u +"%H:%M")
    if [ "$CFG_BACKUP_ENABLE" = "yes" ]; then
        rsync -avz -e "ssh -i $CFG_BS_KEY" Archive/ $CFG_BS_USER@$CFG_BS:$CFG_BS_DIRECTORY
        if [ $? != 0 ]; then
            CFG_UPLOAD_PRUNE="no"
        fi
    fi
    rsync -avz -e "ssh -i $CFG_DS_KEY" Archive/ $CFG_DS_USER@$CFG_DS:$CFG_DS_DIRECTORY
    if [ $? != 0 ]; then
        CFG_UPLOAD_PRUNE="no"
    fi
    UPLOAD_STOP_TIME=$(date -u +"%H:%M")
fi

#-- Generate report ----------------------------------------------------------
if [ "$CFG_MAIL_ENABLE" = "yes" ]; then
    if   [ -z "$failed" ]; then
        RESULT="completed successfully"
    elif [ -z "$succeeded" ]; then
        RESULT="FAILED COMPLETELY"
    else
        RESULT="FAILED PARTLY"
    fi
    
    mail_start $RESULT
    
    ATTACH=()
    if [ ! -z "$failed" ]; then
        mail_write ""
        mail_write "The following packages FAILED to build completely:"
        for package in $failed; do
            mail_write $package
            bzcat $LOG_BASE/$package.log.bz2 | tail -100 >/tmp/_aros_build_log_$package
            ATTACH=( $ATTACH -a/tmp/_aros_build_log_$package )
        done
        mail_write ""
        mail_write "Please see the attached shortened logs or the full logs at"
        NIGHTLY=$(basename $CFG_DS_DIRECTORY)
        mail_write "http://www.aros.org/downloads/$NIGHTLY/$VERSION/logs/ for details."
    fi
    if [ ! -z "$succeeded" ]; then
        mail_write ""
        mail_write "The following packages were built successfully:"
        for package in $succeeded; do
            mail_write "$package"
        done
        mail_write ""
        mail_write "The following archives were created:"
        mail_write "$( find $ARCHIVE_BASE -type f -not -path '*/logs/*' -not -name '*.md5' | xargs -n 1 basename )"
        mail_write ""
        mail_write "The archives will be available for download from http://www.aros.org/download.php."
    fi
    
    mail_send $ATTACH
    
    if [ ! -z "$failed" ]; then
        rm -rf /tmp/_aros_build_log_*
    fi
    mail_stop
fi

#-- Remove uploaded files ----------------------------------------------------
if [[ "$CFG_UPLOAD_ENABLE" = "yes" && "$CFG_UPLOAD_PRUNE" = "yes" ]]; then
    # This is the old way.
    rm -rf Archive/*
    # The rm below is UNSAFE. If ARCHIVE_ROOT is undefined somehow, bye-bye 
    # to everything the build user can delete, from / on down.
    #rm -rf $(ARCHIVE_ROOT)/*
fi
