#!/bin/bash
##################################
# UNIFI SOFTWARE - OPENFW UTM
##################################

UNIFISET="/var/efw/unifi/settings"
STARTLOCAL="/var/efw/inithooks/start.local"

log() { echo -e "\e[1;32m[ UniFi ] $*\e[0m"; }
fail() { echo -e "\e[1;31m[ UniFi ] $*\e[0m"; exit 1; }

set -a
. "$UNIFISET"
set +a

: "${unifi:?unifi not set}"

enabled="$unifi"

#########################################
# Service Control
#########################################
start_unifi() {
    /etc/init.d/unifi start
}

stop_unifi() {
    /etc/init.d/unifi stop
}

#########################################
# Boot persistence (start.local)
#########################################
persist_boot() {

    if [ ! -f "$STARTLOCAL" ]; then
        echo "#!/bin/bash" > "$STARTLOCAL"
        chmod 755 "$STARTLOCAL"
    fi

    sed -i '/unifi/d' "$STARTLOCAL"
    echo "/usr/local/bin/unifi-software --apply" >> "$STARTLOCAL"

    log "Added UniFi to boot (start.local)"
}

remove_boot() {

    [ -f "$STARTLOCAL" ] && sed -i '/unifi/d' "$STARTLOCAL"

    log "Removed UniFi from boot (start.local)"
}

#########################################
# MAIN
#########################################
case "$1" in

    --apply)

        if [ "$enabled" = "on" ]; then
            log "UniFi enabled"

            start_unifi
            persist_boot

            log "UniFi service started and enabled on boot"

        else
            log "UniFi disabled"

            stop_unifi
            remove_boot

            log "UniFi service stopped and removed from boot"
        fi
        ;;

    *)
        echo "Usage: unifi-software --apply"
        ;;
esac
