#!/bin/bash

WWW_DIR="/var/www/motionui"
DATA_DIR="/var/lib/motionui"
GO2RTC_DIR="/var/lib/motionui/go2rtc"
GROUPS="www-data"

# Docker environment variables
#  - FQDN=server.example.com
#  - PUID=xxxx
#  - PGID=xxxx

# Quit if FQDN is not set
if [ -z "$FQDN" ];then
    echo "FQDN environment variable must be set"
    exit 1
fi

# If no branch is set in environment, use main
if [ -z "$BRANCH" ];then
    BRANCH="main"
fi

# If custom PUID is set
if [ ! -z "$PUID" ];then
    # PUID must be >= 1000
    if [ "$PUID" -lt 1000 ];then
        echo "PUID must be greater than or equal to 1000"
        exit 1
    fi

    usermod -u "$PUID" www-data
fi

# If custom PGID is set
if [ ! -z "$PGID" ];then
    # PGID must be >= 1000
    if [ "$PGID" -lt 1000 ];then
        echo "PGID must be greater than or equal to 1000"
        exit 1
    fi

    groupmod -g "$PGID" www-data
fi

# Set FQDN
# Postfix/mail configuration
postconf -e "myhostname = $FQDN"
echo "$FQDN" > /etc/mailname
# Motion-UI configuration
echo "$FQDN" > "$WWW_DIR/.fqdn"

# Make sure motion service is stopped
/usr/sbin/service motion stop > /dev/null

if [ -f /run/motion/motion.pid ]; then
    rm -f /run/motion/motion.pid
fi

# Copy go2rtc template config file if not exists
if [ ! -f "$GO2RTC_DIR/go2rtc.yml" ]; then
    mkdir -p "$DATA_DIR/go2rtc"
    cp "$WWW_DIR/templates/go2rtc/go2rtc.yml" "$GO2RTC_DIR/go2rtc.yml"

    # Generate random password to protect go2rtc streams
    GO2RTC_PASSWORD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
    sed -i "s#__PASSWORD__#$GO2RTC_PASSWORD#" "$GO2RTC_DIR/go2rtc.yml"
fi

# Generate go2rtc .htpasswd file if not exists
if [ ! -f "$GO2RTC_DIR/.htpasswd" ]; then
    PASSWORD=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
    printf "go2rtc:$(openssl passwd -5 $PASSWORD)\n" >> "$GO2RTC_DIR/.htpasswd"

    echo "Generated password for /go2rtc web interface:"
    echo "Username: go2rtc"
    echo "Password: $PASSWORD"
fi

# If branch is devel
if [ "$BRANCH" == "devel" ];then
    # Create directory for XDebug
    mkdir -p /tmp/xdebug
    chown www-data:www-data /tmp/xdebug
    chmod 770 /tmp/xdebug

    # Create .devel file
    touch "$WWW_DIR/.devel"
fi

# Set permissions
/bin/bash $WWW_DIR/bin/motionui -p

if [ $? -ne 0 ];then
    exit 1
fi

# Start services
/usr/sbin/service php8.3-fpm start > /dev/null
/usr/sbin/service nginx start > /dev/null
/usr/sbin/service postfix start > /dev/null
/usr/sbin/service go2rtc start > /dev/null

# Initialize database
setpriv --reuid www-data --regid www-data --groups $GROUPS /usr/bin/php "$WWW_DIR/tools/database/initialize.php"

# Update database (if needed)
setpriv --reuid www-data --regid www-data --groups $GROUPS /usr/bin/php "$WWW_DIR/tools/database/update.php"

# Start shell service in background
/bin/bash "$WWW_DIR/bin/service.sh" &

# Start motionui service
setpriv --reuid www-data --regid www-data --groups $GROUPS /usr/bin/php "$WWW_DIR/tools/service.php" &

# Retrieve service.php PID
main_pid=$!

terminate() {
    # Stop motionui service (service.php) by sending SIGTERM
    echo "Stopping Motion-UI service..."
    kill -s SIGTERM $main_pid

    echo "Stopping go2rtc..."
    /usr/sbin/service go2rtc stop > /dev/null

    echo "Stopping motion..."
    /usr/sbin/service motion stop > /dev/null

    echo "Stopping postfix..."
    /usr/sbin/service postfix stop > /dev/null

    echo "Stopping nginx..."
    /usr/sbin/service nginx stop > /dev/null

    echo "Stopping php-fpm..."
    /usr/sbin/service php8.3-fpm stop > /dev/null
    exit
}

# Catch termination signals and execute terminate() function
trap terminate TERM
wait
