#!/bin/sh

set -e

usage() {
cat <<EOH
USAGE: $(basename "$0") [OPTIONS]

Mirror specified remote directory to local directory using lftp

Options:
    -l  Local directory     (default: '$LOCAL_DIR')
    -r  Remote directory    (default: '$REMOTE_DIR')
    -R  Reverse mirroring   (default: $REVERSE)
    -u  FTP username        (default: '$USERNAME')
    -p  FTP password        (default: '$PASSWORD')
    -P  FTP port            (default: '$PORT')
    -n  Dry-run mode        (default: $DRYRUN)
    -v  Verbose mode        (default: $VERBOSE)
EOH
}

LOCAL_DIR=
REMOTE_DIR=
REVERSE=0
USERNAME="anonymous"
PASSWORD="${USER}@$(dnsdomainname)"
PORT=21
DRYRUN=0
VERBOSE=0

while getopts "l:r:u:p:P:nvRh" OPT ; do
    case "$OPT" in 
        \?|h)
            usage
            exit 0
            ;;
        l)
            LOCAL_DIR="$OPTARG"
            ;;
        r)
            REMOTE_DIR="$OPTARG"
            ;;
        R)
            REVERSE=1
            ;;
        u)
            USERNAME="$OPTARG"
            ;;
        p)
            PASSWORD="$OPTARG"
            ;;
        P)
            PORT="$OPTARG"
            ;;
        n)
            DRYRUN=1
            ;;
        v)
            VERBOSE=1
            ;;
    esac
done

if [ -z "$LOCAL_DIR" ]; then
    printf "ERR: Local path is not defined (option -l)\n"
    usage
    exit 1
fi

if [ -z "$REMOTE_DIR" ]; then
    printf "ERR: Remote path is not defined (option -r)\n"
    usage
    exit 1
fi

if [ "$REVERSE" = 0 ] && [ ! -d "$LOCAL_DIR" ]; then
    mkdir -p "$LOCAL_DIR"
fi

MIRROR_OPTIONS="--delete-first --reverse --only-newer --no-perms --no-umask --ignore-time"
if [ "$REVERSE" = 1 ]; then
    MIRROR_OPTIONS="$MIRROR_OPTIONS --reverse"
fi
if [ "$DRYRUN" = 1 ]; then
    MIRROR_OPTIONS="$MIRROR_OPTIONS --dry-run"
fi
if [ "$VERBOSE" = 1 ]; then
    MIRROR_OPTIONS="$MIRROR_OPTIONS --verbose"
fi

lftp -c "\
    set ftp:list-options -a; \
    lcd $LOCAL_DIR ; \
    open -u $USERNAME,$PASSWORD -p $PORT $REMOTE_DIR ; \
    mirror $MIRROR_OPTIONS \
"

exit 0
