#!/bin/sh
#------------------------------------------------------------------------------
# /tmp/nextcloud-cleanup-archive.sh - extract and repackage owncloud/nextcloud
#                                     distribution archive
#
# Copyright (c) 2013-2017 The Eisfair Team, team(at)eisfair(dot)org
#
# Creation:     2013-01-26  jed
# Last Update:  $Id$
#
# Parameters:   nextcloud-cleanup-archive.sh [-appsonly|-progonly|-norepack][-nochecksum] archive-name
#
# 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> ./nextcloud-cleanup-archive-trace-$$.log
#set -x

EXEC_CMD="$0 $*"

currdir=`pwd`
appsonly=0
nochecksum=0
norepack=0
progonly=1

# z - tgz, j - bz2, J - txz
default_cmd='J'
default_ext='txz'
module_abbr='oc'
module_name='owncloud'

if [ $# -gt 0 ]
then
    while [ 1 ]
    do
        case "$1" in
            *-appsonly )
                if [ ${norepack} -eq 0 -a ${progonly} -eq 0 ]
                then
                    appsonly=1
                fi
                shift
                ;;
            *-nochecksum )
                nochecksum=1
                shift
                ;;
            *-norepack )
                if [ ${appsonly} -eq 0 -o ${progonly} -eq 0 ]
                then
                    norepack=1
                fi
                shift
                ;;
            *-progonly )
                if [ ${appsonly} -eq 0 -a ${norepack} -eq 0 ]
                then
                    progonly=1
                fi
                shift
                ;;
            * )
                if [ -z "$1" ]
                then
                    archname=${currdir}/${module_abbr}_bin_prog.${default_ext}
                else
                    echo "$1" | grep -q 'nextcloud'

                    if [ $? -eq 0 ]
                    then
                        module_abbr='nc'
                        module_name='nextcloud'
                    else
                        module_abbr='oc'
                        module_name='owncloud'
                    fi

                    archname=$1
                fi
                break
                ;;
        esac
    done
else
    archname=${currdir}/${module_abbr}_bin_prog.${default_ext}
fi


if [ "${currdir}" = '/' ]
then
    echo "Error: not possible to run it from '/'."
    echo "       Change to the package directory first!"
else
    archiver=`echo "${archname}" | sed 's#^.*\.##'`

    case ${archiver} in
        bz2 )
            cmd='j'
            ;;
        tgz|tar.gz )
            cmd=z
            ;;
        txz|tar.xz )
            cmd=J
            ;;
    esac

    if [ ${nochecksum} -eq 0 ]
    then
        # check archive checksum before starting any activities
        checksum_found=0
        for SUM in 512 256 5
        do
            if [ -f ${archname}.sha${SUM} ]
            then
                if [ -x /usr/bin/sha${SUM}sum ]
                then
                    checksum_found=1

                    /usr/bin/sha${SUM}sum --check ${archname}.sha${SUM}

                    if [ $? -ne 0 ]
                    then
                        echo "Error: SHA${SUM} checksum doesn't match, aborting!"
                        exit 1
                    fi
                else
                    echo "Error: required program '/usr/bin/sha${SUM}sum' doesn't exist!"
                    exit 1
                fi

                break
            fi
        done
        if [ ${checksum_found} -eq 0 ]
        then
            echo "Error: A SHA checksum file couldn't be found, aborting!"
            echo "Add a SHA checksum file or use the --nochecksum command line switch!"
            exit 1
        fi
    fi

    if [ ${norepack} -eq 0 ]
    then
        # create all archives from scratch
        if [ ${appsonly} -eq 0 ]
        then
            # create owncloud/nextcloud prog archive
            echo "Archive '${archname}' will be re-packaged."
            sleep 5

            if [ -d ${currdir}/${module_name} ]
            then
                echo "Error: directory ${currdir}/${module_name} already exists."
                echo "       remove the directory first."
                exit 1
            fi

            if [ -f ${archname} ]
            then
                if [ ! -d ${module_abbr} ]
                then
                    # create path
                    mkdir -p ${module_abbr}
                fi

                echo "- extracting archive..."
                tar x${cmd}f ${archname} -C ${module_abbr}/

                if [ -f ${currdir}/${module_abbr}_bin_prog.${default_ext} ]
                then
                    mv ${currdir}/${module_abbr}_bin_prog.${default_ext} ${currdir}/${module_abbr}_bin_prog-old.${default_ext}
                fi

                if [ -d ${currdir}/${module_abbr}/${module_name} ]
                then
                    cd ${currdir}/${module_abbr}/${module_name}
                elif [ -d ${currdir}/${module_abbr} ]
                then
                    cd ${currdir}/${module_abbr}/
                fi

                # repackage archive
                echo "- creating new archive..."
                tar c${default_cmd}f ${currdir}/${module_abbr}_bin_prog.${default_ext} --exclude .svn --owner=root --group=root .

                if [ -d ${currdir}/${module_abbr} ]
                then
                    rm -rf ${currdir}/${module_abbr}
                fi
            fi
        fi

        if [ ${progonly} -eq 0 ]
        then
            # create owncloud/nextcloud apps archive
            echo "Apps archive will be re-packaged."
            sleep 5

            echo "- creating apps archive..."
            if [ -f ${currdir}/${module_abbr}_bin_apps.${default_ext} ]
            then
                mv ${currdir}/${module_abbr}_bin_apps.${default_ext} ${currdir}/${module_abbr}_bin_apps-old.${default_ext}
            fi

            if [ -d ${currdir}/../../bin_${module_name}_apps/ ]
            then
                apps_path="${currdir}/../../bin_${module_name}_apps"
            elif [ -d ${currdir}/../../bin_owncloud_apps/ ]
            then
                apps_path="${currdir}/../../bin_owncloud_apps"
            elif [ -d ${currdir}/../../bin_cloud_apps/ ]
            then
                apps_path="${currdir}/../../bin_cloud_apps"
            else
                echo "Error: the svn cloud apps path '${currdir}/../../bin_${module_name}_apps' doesn't exist."
                exit 1
            fi

            echo "Using svn cloud apps path '${apps_path}' ..."
            cd ${apps_path}/

            # package apps
            echo "- creating apps archive..."
            tar c${default_cmd}f ${currdir}/${module_abbr}_bin_apps.${default_ext} --exclude .svn --exclude .\[a-z\]* --owner=root --group=root .
        fi
    fi

    # create file list
    echo "Creating file list."
    cd ${currdir}/

    if [ -f ${currdir}/${module_abbr}-filelist-org.txt ]
    then
        mv ${currdir}/${module_abbr}-filelist-org.txt ${currdir}/${module_abbr}-filelist-org-old.txt
    fi

    {
        if [ -f ${currdir}/${module_abbr}_bin_prog.${default_ext} ]
        then
            tar tv${default_cmd}f ${currdir}/${module_abbr}_bin_prog.${default_ext} | tr -s ' ' | cut -d' ' -f6- | cut -c3- | sort -r | grep -v "^ *$" | grep -E -v "^config/|^data/"
        fi

        if [ -f ${currdir}/${module_abbr}_bin_apps.${default_ext} ]
        then
            tar tv${default_cmd}f ${currdir}/${module_abbr}_bin_apps.${default_ext} | cut -c 51- | sort -r | grep -v "^ *$" | sed 's#^#ADDAPPS/#g'
        fi
    } | sort -r | uniq > ${currdir}/${module_abbr}-filelist-org.txt

    # ask if the directory should be cleaned-up
    if [ -f ${currdir}/${module_abbr}_bin_prog-old.${default_ext} -o \
         -f ${currdir}/${module_abbr}_bin_apps-old.${default_ext} -o \
         -f ${currdir}/${module_abbr}-filelist-org-old.txt        -o \
         -f ${archname}                                           -o \
         -f ${archname}.sha* ]
    then
        echo
        echo "Delete original ${module_abbr} archive and all backup files?"
        read answer
        answer=`printf "${answer}" | tr '[:upper:]' '[:lower:]'`

        case ${answer} in
            y|yes )
                rm -f ${currdir}/${module_abbr}_bin_prog-old.${default_ext} \
                      ${currdir}/${module_abbr}_bin_apps-old.${default_ext} \
                      ${currdir}/${module_abbr}-filelist-org-old.txt        \
                      ${currdir}/*.metadata                                 \
                      ${archname} ${archname}.sha*
                ;;
            * )
                ;;
        esac
    fi
fi
