#!/bin/bash
#
# Copyright (C) 2013  Etersoft
# Copyright (C) 2013  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

PROGDIR=$(dirname $0)
[ "$PROGDIR" = "." ] && PROGDIR=$(pwd)

# will replaced to /usr/share/erc during install
SHAREDIR=/usr/share/erc

load_helper()
{
    local CMD="$SHAREDIR/$1"
    [ -r "$CMD" ] || fatal "Have no $CMD helper file"
    . $CMD
}

load_helper erc-sh-functions
load_helper erc-archive

check_tty

# 1.zip tar:  -> 1.tar
build_target_name()
{
	is_target_format $2 && echo $(get_archive_name "$1").${2/:/} && return
	echo "$1"
        return 1
}

phelp()
{
	echo "$Descr
$Usage
 Commands:
$(get_help HELPCMD)

 Options:
$(get_help HELPOPT)

 Examples:
    # erc a archive.zip file(s)... - pack files to archive.zip
    # erc [x] archive.zip - unpack
    # erc [repack] archive1.zip... archive2.rar 7z: - repack all to 7z
    # erc [repack] archive.zip archive.7z - repack zip to 7z
    # erc file zip: - pack file to zip
"
}

print_version()
{
        echo "Etersoft archive manager version 0.5-alt0.M70P.1"
        echo "Copyright (c) Etersoft 2013"
        echo "This program may be freely redistributed under the terms of the GNU AGPLv3."
}

progname="${0##*/}"

Usage="Usage: $progname [options] [<command>] [params]..."
Descr="erc - universal archive manager"

cmd=$1
eval lastarg=\${$#}

# if the first arg is some archive, suggest extract
if get_archive_type "$cmd" 2>/dev/null >/dev/null ; then
    if is_target_format $lastarg ; then
        cmd=repack
    else
        cmd=extract
    fi
elif test -r "$cmd" && is_target_format $2 ; then
    cmd=pack
else
    shift
fi


# Just printout help if run without args
if [ -z "$cmd" ] ; then
    print_version
    echo
    fatal "Run $ $progname --help for get help"
fi

verbose=--verbose

# TODO: Если программа-архиватор не установлена, предлагать установку с помощью epm

case $cmd in
    -h|--help|help)       # HELPOPT: this help
        phelp
        ;;
    -v|--version)            # HELPOPT: print version
        print_version
        ;;
    a|-a|create|pack)        # HELPCMD: create archive
        # TODO: realize archive addition if already exist
        if is_target_format $lastarg ; then
            [ $# = 2 ] || fatal "Need two args"
            docmd patool $verbose create "$(build_target_name "$1" "$2")" "$1"
            exit
        fi
        docmd patool $verbose create "$@"
        ;;
    e|x|-e|-x|u|-u|extract|unpack)          # HELPCMD: extract files from archive
        docmd patool $verbose extract "$@"
        ;;
# TODO: realize deletion
#    d|delete)             # HELPCMD: delete file(s) from archive
#        docmd patool delete "$@"
#        ;;
    l|-l|list)               # HELPCMD: list archive contents
        docmd patool $verbose list "$@"
        ;;
    t|-t|test|check)         # HELPCMD: test for archive integrity
        docmd patool $verbose test "$@"
        ;;
    type)                 # HELPCMD: print type of archive
        get_archive_type "$1" || fatal "Can't recognize $1 as archive"
        ;;
    diff)                 # HELPCMD: compare two archive
        # check 2 arg
        docmd patool $verbose diff "$@"
        ;;
    b|-b|bench|benchmark)    # HELPCMD: do CPU benchmark
        #assure_cmd 7z
        # TODO: can be 7za?
        docmd 7z b
        ;;
    search|grep)               # HELPCMD: search in files from archive
        docmd patool $verbose search "$@"
        ;;
    repack|conv)          # HELPCMD: convert source archive to target
        # TODO: need repack remove source file?
        # TODO: check for 2 arg
        if ! is_target_format $lastarg ; then
            [ $# = 2 ] || fatal "Need two args"
            docmd patool $verbose repack "$1" "$2"
            exit
        fi

        # add support for target zip:
        for i in "$@" ; do
            [ "$i" = "$lastarg" ] && continue
            docmd patool $verbose repack "$i" "$(build_target_name "$i" "$lastarg")"
        done

        ;;
    formats)              # HELPCMD: lists supported archive formats
        # TODO: print allowed with current programs separately
        docmd patool formats "$@"
        ;;
    *)
        # TODO: If we have archive in parameter, just unpack it
        fatal "Unknown command $1"
        ;;
esac

