#!/bin/bash


ask_yn () {
    echo "$@"
    while true; do
        read yn
        case $yn in
            [Yy]*) return 0;;
            [Nn]*) return 1;;
            *) echo "Enter yes or no";;
        esac
    done
}


putaway ()
{
    local method dir_to_save
    method=${1:?"Needs compression method"}
    dir_to_save=${2:?"Needs a dir to save"}

    local archive_base archive command
    local date_suffix
    date_suffix=$(newest_date "$dir_to_save")
    [[ $date_suffix ]] || date_suffix=$(date +%F)
    archive_base=__warehouse/"$(basename "$dir_to_save")-$date_suffix"

    # TODO: zip -o sets the mtime of the zip file to the mtime of the newest file inside it;
    #       there's no equivalent in tar so do it by hand
    case $method in

        tar)   archive=$archive_base.tar.xz
                command="tar -cpf - \"$dir_to_save\" | xz -z - > \"$archive\""
                ;;

        zip)   archive=$archive_base.zip
                command="zip -yor \"$archive\" \"$dir_to_save\""
                ;;

        *)     echo "Invalid compression method $method: must be tar or zip"
                return 2
                ;;

    esac

    [[ -e $archive ]] && { echo "target already exists!" ; return 1; }

    du -hs "$dir_to_save"
    echo '->' "$archive"
    $NOCONFIRM || ask_yn "do putaway?" || return 0

    mkdir -p __warehouse || return 1

    echo compressing
    eval $command || return 1

    du -h "$archive"
    $NOCONFIRM || ask_yn "$dir_to_save put away... delete?" || return 0

    echo deleting...
    chmod -R u+w "$dir_to_save"
    rm -rf "$dir_to_save"
}


usage () {
    echo "${0##*/} [options] [--] DIRS..."
    echo
    echo "Compress and put away directories into a __warehouse subdir"
    echo
    echo "Options:"
    echo
    echo "      -h  Show this help message"
    echo "      -y  Do not ask confirmation"
    echo "      -t  Use tar"
    echo "      -z  Use zip"
    echo "Default is $method"
}


newest_date () {
    # find the newest file (by mtime, return the YYYY-MM-DD)
    find "$1" -printf '%TF\n' | sort | tail -n 1
}


method=zip
NOCONFIRM=false


while getopts ':htyz' OPT; do
    case $OPT in
        h) usage
            exit 0
            ;;
        t) method=tar
            ;;
        y) NOCONFIRM=true
            ;;
        z) method=zip
            ;;
        \?) echo Bad option $OPT; usage
            exit 2
    esac
done
shift $(( OPTIND - 1 ))
OPTIND=1

if [[ $# -eq 0 ]]; then
    usage; exit 2
fi

for dir_to_save; do
    putaway $method "$dir_to_save"
done

