#!/bin/sh

usage() {
  cat <<__EOF__
firewall [ status | enable | disable | list | add | remove | blockall | help ]

commands:
  [s]tatus                - Show status
  enable                  - Enable firewall
  disable                 - Disable firewall
  ls | list               - List applications handled by firewall
  add /path/to/file       - Add app to firewall
  remove /path/to/file    - Remove app frofirewall
  blockall [ on | off ]   - Block all connections (State 2)

__EOF__
}

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

case "$1" in
  --help | -h | help)
    usage
    exit 0
    ;;
  s | status)
    /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
    ;;
  enable)
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
    ;;
  disable)
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off
    ;;
  ls | list)
    /usr/libexec/ApplicationFirewall/socketfilterfw --list
    ;;
  add)
    [ -z "$2" ] && help && exit 1
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add "$2"
    ;;
  remove)
    [ -z "$2" ] && help && exit 1
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --remove "$2"
    ;;
  blockall)
    [ "$2" != "on" ] && [ "$2" != "off" ] || [ -z "$2" ] && help && exit 1
    sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall "$2"
    ;;
  *)
    usage
    exit 1
    ;;
esac
