#!/bin/bash

WWW_DIR="/var/www/motionui"
DATA_DIR="/var/lib/motionui"
GO2RTC_DIR="/var/lib/motionui/go2rtc"

# 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"

    # Set permissions
    chown www-data:motionui "$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"
    chown www-data:www-data "$GO2RTC_DIR/.htpasswd"
    chmod 600 "$GO2RTC_DIR/.htpasswd"

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

# Set permissions
/bin/bash $WWW_DIR/bin/motionui -p &
chown -R www-data:motionui $DATA_DIR

# Docker run options
# when
# -e FQDN=server.example.com
# are set, the following settings are changed:
if [ ! -z "$FQDN" ];then
    # Postfix/mail configuration
    postconf -e "myhostname = $FQDN"
    echo $FQDN > /etc/mailname

    # motion-UI configuration
    echo $FQDN > "$WWW_DIR/.fqdn"
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

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

# Initialize and update database (if needed)
/bin/su -s /bin/bash -c "php $WWW_DIR/tools/database/initialize.php" www-data

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

/bin/su -s /bin/bash -c "php $WWW_DIR/tools/database/update.php" www-data

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

# Make sure go2rtc service is started
/usr/sbin/service go2rtc start

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

# Start motionui service
/bin/su -s /bin/bash -c "php $WWW_DIR/tools/service.php" www-data

/bin/bash