#!/usr/bin/env bash

export TERM="xterm-256color"

WWW_USER="www-data"
WWW_DIR="/var/www/motionui"
DATA_DIR="/var/lib/motionui"
CONFIRM=""
PWD=$(pwd)

# Colors
GREEN=$(tput setaf 2)
RED=$(tput setaf 1)
YELLOW=$(tput setaf 3)
RESET=$(tput sgr0)

# Detecting user
if [ "$(id -u)" -ne "0" ];then
    echo -e "\n${YELLOW}Must be executed with sudo ${RESET}\n"
    exit
fi


# Print help
function help
{
    echo -e "\n   Available parameters:"
    echo -e "   -p | --set-permissions  ➤  Set necessary permissions on Motion-UI directories and files."
}

# Set correct permissions on all directories and files used by motionui
function permissions
{
    echo -e "\n${YELLOW} Setting permissions... ${RESET}"

    # Set permissions for video devices, if any
    if ls /dev/video* > /dev/null 2>&1; then
        chown root:motionui /dev/video*
    fi

    # Permissions on web directory
    chmod 750 "$WWW_DIR/bin/motionui"
    chmod 750 "$WWW_DIR/bin/on_event"*
    chmod 750 "$WWW_DIR"
    chown -R $WWW_USER "$WWW_DIR"
    chgrp -R $WWW_USER "$WWW_DIR"
    # Set 660 permissions on all files and directories except scripts in bin:
    find "$WWW_DIR" -type f -not -not \( -path bin -prune \) -exec chmod 0660 {} \;
    find "$WWW_DIR" -type d -exec chmod 0750 {} \;

    # Permissions on data directory
    chown -R ${WWW_USER}:motionui "$DATA_DIR"
    find "$DATA_DIR" -type f -exec chmod 0660 {} \;
    find "$DATA_DIR" -type d -exec chmod 0770 {} \;
    chmod 770 "$DATA_DIR"

    # Set permissions on motion captures dir
    mkdir -p /var/lib/motion
    chown -R www-data:motionui /var/lib/motion
    find "/var/lib/motion" -type f -exec chmod 0660 {} \;
    find "/var/lib/motion" -type d -exec chmod 0770 {} \;

    chmod 550 ${WWW_DIR}/bin/motionui

    find "/usr/var/lib/motion" -type f -exec chmod 0660 {} \;
    find "/usr/var/lib/motion" -type d -exec chmod 0770 {} \;
    chown -R ${WWW_USER}:motionui /usr/var/lib/motion
    chmod 770 /usr/var/lib/motion
}

echo '
                 __  .__                              .__ 
   _____   _____/  |_|__| ____   ____            __ __|__|
  /     \ /  _ \   __\  |/  _ \ /    \   ______ |  |  \  |
 |  Y Y  (  <_> )  | |  (  <_> )   |  \ /_____/ |  |  /  |
 |__|_|  /\____/|__| |__|\____/|___|  /         |____/|__|
       \/                           \/                    

'

if [ $# -eq 0 ];then
    help
    exit
fi

while [ $# -ge 1 ];do
    case "$1" in
        --help|-help|-h)
            help
            exit
        ;;
        --set-permissions|--permissions|-p)
            permissions
            exit
        ;;
        *)
    esac
    shift
done

exit