#!/bin/bash -e

function usage() {
    cat << EOF
Usage: $0 [-hcCviIna]
Prune $RUNTIME resources.
If no option provided, defaults to -Cvn
Options:
    -h  Show this help and exits
    -c  Remove stopped containers
    -C  Remove all containers
    -v  Remove unused volumes
    -i  Remove build images
    -I  Remove unused images
    -n  Remove unused networks
    -a  All of the above, equivalent of -CvIn
    -r  Run as root
EOF
    exit 0
}

function add_opt() {
    local RESULT

    RESULT="$1"
    for o in "$@"; do
        if [ "$((RESULT & o))" == 0 ]; then
            RESULT="$((RESULT + o))"
        fi
    done
    echo "$RESULT"
}

RUNTIME="$(command -v podman || command -v docker)"

c=1
# C=2
v=4
i=8
# I=16
n=32
# a="$((c + C + v + I + n))"

CLEAN=0
while getopts hcCviInar o; do
    case "$o" in
        h)
            usage
            ;;
        c)
            CLEAN="$(add_opt "$CLEAN" "$c")"
            ;;
        C)
            CLEAN="$(add_opt "$CLEAN" "$c")"
            CON_OPT='-f'
            ;;
        v)
            CLEAN="$(add_opt "$CLEAN" "$v")"
            ;;
        i)
            CLEAN="$(add_opt "$CLEAN" "$i")"
            ;;
        I)
            CLEAN="$(add_opt "$CLEAN" "$i")"
            IMG_OPT='-a'
            ;;
        n)
            CLEAN="$(add_opt "$CLEAN" "$n")"
            ;;
        a)
            CLEAN="$(add_opt "$CLEAN" "$c" "$v" "$i" "$n")"
            CON_OPT='-f'
            IMG_OPT='-a'
            ;;
        r)
            exec sudo -- "$0" "$(sed 's/r//' <<< "${@:1}")"
            ;;
        *)
            exit 1
            ;;
    esac
done

if [ "$CLEAN" == 0 ]; then
    CLEAN="$((c + v + n))"
    CON_OPT="-f"
fi

VALUES=(
    "$((c + i + v + n))"
    "$((c + i + n))"
    "$v"
    "$i"
    "$n"
)

CON='container'
PRUNE='prune -f'
COMMANDS=(
    "$RUNTIME system  $PRUNE $IMG_OPT --volumes"
    "$RUNTIME system  $PRUNE $IMG_OPT"
    "$RUNTIME volume  $PRUNE"
    "$RUNTIME image   $PRUNE $IMG_OPT"
    "$RUNTIME network $PRUNE"
)

if [ "$((CLEAN & "$c"))" == "$c" ]; then
    $RUNTIME "$CON" ls -aq | xargs "$RUNTIME" "$CON" rm "$CON_OPT" 2> /dev/null
fi

for idx in "${!VALUES[@]}"; do
    mask="${VALUES[$idx]}"

    if [ "$((CLEAN & mask))" == "$mask" ]; then
        bash -c "${COMMANDS[$idx]}"
        CLEAN="$((CLEAN - mask))"
    fi
done
