#!/usr/bin/env bash
# docker-fence: filters by source the traffic to ports published by
# Docker, with a managed block in /etc/ufw/after.rules (DOCKER-USER chain).
# See README.md.

# bash version check, written to be readable by an old bash.
_fence_require_bash() {
    if [ "${1:-0}" -lt 5 ]; then
        echo "docker-fence: bash 5 or later is required (bash ${2:-?})" >&2
        exit 2
    fi
}

FENCE_VERSION=0.1.0

fence_usage_error() {
    fence_error e_usage "$1"
    exit "$FENCE_EXIT_CONFIG"
}

# Options allowed per command.
fence_allowed_flags() {
    case "$1" in
        install|apply) echo "replace-legacy force" ;;
        rollback) echo "auto" ;;
        uninstall) echo "restore-legacy" ;;
        report) echo "since" ;;
        init) echo "output force" ;;
        rules) echo "color" ;;
        *) echo "" ;;
    esac
}

fence_main() {
    set -euo pipefail
    export LC_ALL=C
    # ufw (Python gettext) reads LANGUAGE before LC_ALL: without this, a
    # localized "ufw status" would not be parsed.
    unset LANGUAGE
    umask 077

    FENCE_SELF="$(readlink -f -- "${BASH_SOURCE[0]}")"
    local libdir
    libdir="$(dirname -- "$FENCE_SELF")/lib"
    # shellcheck source=lib/messages.sh
    source "$libdir/messages.sh"
    # shellcheck source=lib/util.sh
    source "$libdir/util.sh"
    # shellcheck source=lib/config.sh
    source "$libdir/config.sh"
    # shellcheck source=lib/generate.sh
    source "$libdir/generate.sh"
    # shellcheck source=lib/rulesfile.sh
    source "$libdir/rulesfile.sh"
    # shellcheck source=lib/envcheck.sh
    source "$libdir/envcheck.sh"
    # shellcheck source=lib/commands.sh
    source "$libdir/commands.sh"
    # shellcheck source=lib/report.sh
    source "$libdir/report.sh"
    # shellcheck source=lib/template.sh
    source "$libdir/template.sh"
    # shellcheck source=lib/listing.sh
    source "$libdir/listing.sh"

    fence_config_reset
    FENCE_OVERRIDES=()
    FENCE_LEGACY_CUT=""
    OPT_CONFIG="" OPT_SINCE="" OPT_OUTPUT="" OPT_FILE="" OPT_COLOR=auto
    OPT_REPLACE_LEGACY=0 OPT_FORCE=0 OPT_AUTO=0 OPT_RESTORE_LEGACY=0
    local cmd="" help=0 version=0
    local -a flags=() positional=()

    # Language of usage messages, before any parsing.
    if [[ "${FENCE_LANG:-}" == fr ]]; then
        CFG[lang]=fr
    fi

    while (( $# > 0 )); do
        local a="$1" v=""
        if [[ "$a" == --*=* ]]; then
            v="${a#*=}"
            a="${a%%=*}"
            set -- "$a" "$v" "${@:2}"
        fi
        case "$a" in
            -c|--config|--mode|--lang|--set|--since|--output|--color)
                (( $# >= 2 )) || fence_usage_error "$a"
                v="$2"
                shift 2
                case "$a" in
                    -c|--config) OPT_CONFIG="$v" ;;
                    --mode) FENCE_OVERRIDES+=("mode=$v") ;;
                    --lang)
                        FENCE_OVERRIDES+=("lang=$v")
                        [[ "$v" == fr || "$v" == en ]] && CFG[lang]="$v"
                        ;;
                    --set) FENCE_OVERRIDES+=("$v") ;;
                    --since) OPT_SINCE="$v"; flags+=(since) ;;
                    --output) OPT_OUTPUT="$v"; flags+=(output) ;;
                    --color)
                        [[ "$v" =~ ^(auto|always|never)$ ]] || fence_usage_error "--color $v"
                        OPT_COLOR="$v"; flags+=(color)
                        ;;
                esac
                continue
                ;;
            -q|--quiet) FENCE_VERBOSITY=0 ;;
            -v|--verbose) FENCE_VERBOSITY=2 ;;
            -h|--help) help=1 ;;
            --version) version=1 ;;
            --replace-legacy) OPT_REPLACE_LEGACY=1; flags+=(replace-legacy) ;;
            --force) OPT_FORCE=1; flags+=(force) ;;
            --auto) OPT_AUTO=1; flags+=(auto) ;;
            --restore-legacy) OPT_RESTORE_LEGACY=1; flags+=(restore-legacy) ;;
            -) positional+=("$a") ;;
            -*) fence_usage_error "$a" ;;
            *) positional+=("$a") ;;
        esac
        shift
    done

    if (( help )); then
        printf '%s\n' "$(fence_fmt usage)"
        exit 0
    fi
    if (( version )); then
        printf 'docker-fence %s\n' "$FENCE_VERSION"
        exit 0
    fi
    (( ${#positional[@]} > 0 )) || fence_usage_error "<command>"
    cmd="${positional[0]}"
    positional=("${positional[@]:1}")

    local allowed fl
    allowed=" $(fence_allowed_flags "$cmd") "
    for fl in "${flags[@]}"; do
        [[ "$allowed" == *" $fl "* ]] || fence_usage_error "$cmd --$fl"
    done
    if (( ${#positional[@]} > 0 )); then
        if [[ "$cmd" == rollback && ${#positional[@]} -eq 1 && "$OPT_AUTO" -eq 0 ]]; then
            OPT_FILE="${positional[0]}"
        else
            fence_usage_error "$cmd ${positional[*]}"
        fi
    fi

    local fn
    case "$cmd" in
        check) fn=fence_cmd_check ;;
        status) fn=fence_cmd_status ;;
        install) fn=fence_cmd_install ;;
        apply) fn=fence_cmd_apply ;;
        confirm) fn=fence_cmd_confirm ;;
        rollback) fn=fence_cmd_rollback ;;
        uninstall) fn=fence_cmd_uninstall ;;
        report) fn=fence_cmd_report ;;
        ufw-plan) fn=fence_cmd_ufw_plan ;;
        rules) fn=fence_cmd_rules ;;
        init) fn=fence_cmd_init ;;
        show-config) fn=fence_cmd_show_config ;;
        *) fence_usage_error "$cmd" ;;
    esac

    if [[ "$cmd" == init ]]; then
        # No file to read: only the language and the options matter.
        fence_config_apply_overrides
        if (( ${#FENCE_ERRORS[@]} > 0 )); then
            fence_config_print_errors
            exit "$FENCE_EXIT_CONFIG"
        fi
    elif ! fence_config_load "$OPT_CONFIG"; then
        fence_config_print_errors
        exit "$FENCE_EXIT_CONFIG"
    fi

    "$fn"
    exit "$FENCE_EXIT_OK"
}

if [ "${BASH_SOURCE[0]}" = "$0" ]; then
    _fence_require_bash "${BASH_VERSINFO[0]}" "${BASH_VERSION}"
    fence_main "$@"
fi
