#!/bin/bash

set -e  # Stop script on error

IPTV_SOURCE_URL="${IPTV_SOURCE_URL:-https://iptv.mrk.ovh/get_source}"
IPTV_DEST="/home/pi/Documents/IPTV.py"
CONFIG_DB_SOURCE_URL="${CONFIG_DB_SOURCE_URL:-https://iptv.mrk.ovh/static/config_init.db}"
CONFIG_DB_DEST="/home/pi/Documents/config.db"
RC_LOCAL="/etc/rc.local"
RC_LOCAL_CMD='sudo -u pi DISPLAY=:0 python3 /home/pi/Documents/IPTV.py &'
CURL_CMD=(curl -fsSL)

if [ "${CURL_INSECURE:-0}" = "1" ]; then
    CURL_CMD+=( -k )
fi

echo "Updating system"
sudo apt update

echo "Installing packages"
sudo apt -y install vim openvpn vsftpd curl ca-certificates python3-pil.imagetk python3-tk
sudo update-ca-certificates

echo "Configuring vsftpd"
VSFTPD_CONF="/etc/vsftpd.conf"

sudo sed -i 's/^#write_enable=YES/write_enable=YES/' $VSFTPD_CONF

echo "Restarting vsftpd service"
sudo systemctl restart vsftpd

PYTHON_STDLIB_DIR="$(python3 -c 'import sysconfig; print(sysconfig.get_path("stdlib"))')"

echo "Fixing Python externally-managed restriction"
sudo rm -f "$PYTHON_STDLIB_DIR/EXTERNALLY-MANAGED"

echo "Installing Python packages"
sudo pip3 install python-vlc python-socketio wifi aiohttp websocket-client

echo "Downloading IPTV.py"
sudo mkdir -p /home/pi/Documents
sudo "${CURL_CMD[@]}" "$IPTV_SOURCE_URL" -o "$IPTV_DEST"
sudo chown pi:pi "$IPTV_DEST"
sudo chmod 755 "$IPTV_DEST"

echo "Downloading config database"
sudo "${CURL_CMD[@]}" "$CONFIG_DB_SOURCE_URL" -o "$CONFIG_DB_DEST"
sudo chown pi:pi "$CONFIG_DB_DEST"
sudo chmod 644 "$CONFIG_DB_DEST"

echo "Configuring rc.local"
if [ ! -f "$RC_LOCAL" ]; then
    sudo tee "$RC_LOCAL" >/dev/null <<'EOF'
#!/bin/sh -e

exit 0
EOF
fi

if ! sudo grep -Fq "$RC_LOCAL_CMD" "$RC_LOCAL"; then
    sudo sed -i "\$i\\
$RC_LOCAL_CMD
" "$RC_LOCAL"
fi

if ! sudo tail -n 1 "$RC_LOCAL" | grep -Fxq "exit 0"; then
    echo "rc.local must end with 'exit 0'" >&2
    exit 1
fi

sudo chmod 755 "$RC_LOCAL"

echo "All tasks completed successfully!"
