#!/bin/bash
echo "✅ ############################ AUTO client login, disable Wayland, unlock keyring with password, and autostart for Prowatchly PWA"
CLIENT_USER="client"
CLIENT_PASSWORD="helloclient"  # Password for client user
GDM_CONF="/etc/gdm3/custom.conf"
CLIENT_HOME="/home/$CLIENT_USER"
AUTOSTART_DIR="$CLIENT_HOME/.config/autostart"
LAUNCHER_SCRIPT="$CLIENT_HOME/.local/bin/prowatchly_launcher.sh"
KEYRING_SCRIPT="$CLIENT_HOME/.local/bin/unlock_keyring.sh"
AUTOSTART_FILE="$AUTOSTART_DIR/prowatchly-check.desktop"
LOG_FILE="/tmp/prowatchly_setup.log"
AUTOSTART_LOG="/tmp/prowatchly_autostart.log"
PROWATCHLY_URL="http://127.0.0.1:15001"  # Corrected Prowatchly local URL

# Function to log messages (avoid logging password)
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Verify client user exists and is properly configured
log "🔍 Verifying client user..."
if ! id "$CLIENT_USER" &>/dev/null; then
    log "⚠️ User $CLIENT_USER does not exist. Creating..."
    sudo adduser --disabled-password --gecos "" "$CLIENT_USER"
    echo "$CLIENT_USER:$CLIENT_PASSWORD" | sudo chpasswd
    sudo usermod -s /bin/bash "$CLIENT_USER"
    sudo usermod -aG netdev "$CLIENT_USER"
else
    log "✅ User $CLIENT_USER exists."
fi

# Ensure client user has a valid shell
if ! grep -q "^$CLIENT_USER:.*:/bin/bash$" /etc/passwd; then
    log "🛠 Setting shell to /bin/bash for $CLIENT_USER..."
    sudo usermod -s /bin/bash "$CLIENT_USER"
fi

# Ensure client home directory exists
if [ ! -d "$CLIENT_HOME" ]; then
    log "⚠️ Home directory $CLIENT_HOME missing. Creating..."
    sudo mkdir -p "$CLIENT_HOME"
    sudo chown "$CLIENT_USER:$CLIENT_USER" "$CLIENT_HOME"
    sudo chmod 755 "$CLIENT_HOME"
fi

# Install libsecret-tools if not present
log "🔍 Checking for libsecret-tools..."
if ! command -v secret-tool >/dev/null; then
    log "⚠️ libsecret-tools not found. Installing..."
    sudo apt update
    sudo apt install -y libsecret-tools
fi

# Configure GNOME Keyring to unlock with client password
log "🔓 Configuring GNOME Keyring to unlock with password..."
sudo -u "$CLIENT_USER" bash -c "
    KEYRING_DIR=\"$CLIENT_HOME/.local/share/keyrings\"
    log '🛠 Clearing existing keyring data...'
    rm -rf \"\$KEYRING_DIR\"/*
    mkdir -p \"\$KEYRING_DIR\"
    chown \"$CLIENT_USER:$CLIENT_USER\" \"\$KEYRING_DIR\"
    chmod 700 \"\$KEYRING_DIR\"
    # Initialize keyring
    DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/\$(id -u) secret-tool store --label='Login keyring' login keyring <<< '$CLIENT_PASSWORD'
    log '✅ GNOME Keyring initialized.'
"

# Create keyring unlock script for autostart
log "📜 Creating keyring unlock script at $KEYRING_SCRIPT..."
sudo bash -c "cat > '$KEYRING_SCRIPT'" <<EOF
#!/bin/bash
LOG_FILE="/tmp/prowatchly_keyring.log"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Unlocking GNOME Keyring..." >> "\$LOG_FILE"
DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/\$(id -u) secret-tool lookup login keyring <<< '$CLIENT_PASSWORD' >> "\$LOG_FILE" 2>&1
if [ \$? -eq 0 ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Keyring unlocked successfully." >> "\$LOG_FILE"
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Keyring unlock failed. Setting blank password as fallback." >> "\$LOG_FILE"
    DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/\$(id -u) echo -n '' | gnome-keyring-daemon --replace --unlock --components=secrets,pkcs11,ssh,gpg >> "\$LOG_FILE" 2>&1
fi
# Secondary unlock attempt after delay
sleep 10
DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/\$(id -u) secret-tool lookup login keyring <<< '$CLIENT_PASSWORD' >> "\$LOG_FILE" 2>&1
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Secondary keyring unlock attempted." >> "\$LOG_FILE"
EOF
sudo chmod 600 "$KEYRING_SCRIPT"  # Strict permissions to protect password
sudo chown "$CLIENT_USER:$CLIENT_USER" "$KEYRING_SCRIPT"
log "✅ Keyring unlock script created with strict permissions."

# Ensure PAM configuration allows auto-unlock
log "🛠 Configuring PAM for keyring auto-unlock..."
if ! grep -q "auth.*pam_gnome_keyring.so" /etc/pam.d/gdm-autologin; then
    log "🛠 Adding pam_gnome_keyring to /etc/pam.d/gdm-autologin..."
    sudo bash -c "echo 'auth optional pam_gnome_keyring.so' >> /etc/pam.d/gdm-autologin"
fi
if ! grep -q "session.*pam_gnome_keyring.so" /etc/pam.d/gdm-autologin; then
    log "🛠 Adding pam_gnome_keyring to session in مرحله /etc/pam.d/gdm-autologin..."
    sudo bash -c "echo 'session optional pam_gnome_keyring.so auto_start' >> /etc/pam.d/gdm-autologin"
fi
if ! grep -q "auth.*pam_gnome_keyring.so" /etc/pam.d/gdm-password; then
    log "🛠 Adding pam_gnome_keyring to /etc/pam.d/gdm-password..."
    sudo bash -c "echo 'auth optional pam_gnome_keyring.so' >> /etc/pam.d/gdm-password"
fi
if ! grep -q "session.*pam_gnome_keyring.so" /etc/pam.d/gdm-password; then
    log "🛠 Adding pam_gnome_keyring to session in /etc/pam.d/gdm-password..."
    sudo bash -c "echo 'session optional pam_gnome_keyring.so auto_start' >> /etc/pam.d/gdm-password"
fi

# Secure the client user
log "🔐 Securing $CLIENT_USER account..."
sudo usermod -L "$CLIENT_USER"  # Lock account to prevent manual login
sudo bash -c "echo '$CLIENT_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart gdm3' > /etc/sudoers.d/client"
sudo chmod 440 /etc/sudoers.d/client
log "✅ Client user secured."

# Backup existing GDM3 configuration
if [ -f "$GDM_CONF" ]; then
    log "🛠 Backing up $GDM_CONF..."
    sudo cp "$GDM_CONF" "$GDM_CONF.bak"
fi

# Configure GDM3 for auto-login and disable Wayland
log "🔧 Configuring GDM3 for auto-login and disabling Wayland..."
echo "🛑 Disabling Wayland... for RUSTDESK LOGIN SCREEN ACCESS"
if command -v gdm3 >/dev/null && [ -d "/etc/gdm3" ]; then
    log "🛠 Writing GDM3 configuration to $GDM_CONF..."
    sudo bash -c "cat > $GDM_CONF" <<EOF
[daemon]
AutomaticLoginEnable=true
AutomaticLogin=$CLIENT_USER
WaylandEnable=false
EOF
    sudo chmod 644 "$GDM_CONF"
    sudo chown root:root "$GDM_CONF"
    log "✅ Auto-login and Wayland disable configuration written."
else
    log "⚠️ GDM3 not found or $GDM_CONF directory missing."
    exit 1
fi

# Verify GDM3 configuration
log "🔍 Verifying GDM3 configuration..."
if grep -q "AutomaticLoginEnable=true" "$GDM_CONF" && grep -q "AutomaticLogin=$CLIENT_USER" "$GDM_CONF" && grep -q "WaylandEnable=false" "$GDM_CONF"; then
    log "✅ GDM3 configuration verified."
else
    log "❌ GDM3 configuration invalid. Restoring backup..."
    sudo mv "$GDM_CONF.bak" "$GDM_CONF" 2>/dev/null
    exit 1
fi

# Create directories for launcher and autostart
log "📁 Creating directories for launcher and autostart..."
sudo mkdir -p "$CLIENT_HOME/.local/bin" "$AUTOSTART_DIR"
sudo chown "$CLIENT_USER:$CLIENT_USER" "$CLIENT_HOME/.local/bin" "$AUTOSTART_DIR"
sudo chmod 755 "$CLIENT_HOME/.local/bin" "$AUTOSTART_DIR"

# Create the launcher script to dynamically find and run Prowatchly PWA
log "📜 Creating launcher script at $LAUNCHER_SCRIPT..."
sudo bash -c "cat > '$LAUNCHER_SCRIPT'" <<EOF
#!/bin/bash
LOG_FILE="/tmp/prowatchly_launcher.log"
AUTOSTART_LOG="/tmp/prowatchly_autostart.log"

# Function to log messages
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] \$1" >> "\$LOG_FILE"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] \$1" >> "\$AUTOSTART_LOG"
}

# Log autostart attempt
log "Starting Prowatchly launcher script..."

# Check if Chrome has been initialized (profile exists)
CHROME_PROFILE="$CLIENT_HOME/.config/google-chrome/Default"
if [ ! -d "\$CHROME_PROFILE" ]; then
    log "Google Chrome profile not initialized at \$CHROME_PROFILE. Please open Chrome manually first. Exiting."
    exit 0
fi

# Wait for desktop to load
sleep 20

# Search for Prowatchly .desktop file
APP_DIR="\$HOME/.local/share/applications"
DESKTOP_FILE=\$(find "\$APP_DIR" -name "chrome-*-Default.desktop" -exec grep -l 'Name=Prowatchly' {} + 2>/dev/null)

if [[ -z "\$DESKTOP_FILE" ]]; then
    log "Prowatchly PWA not found in \$APP_DIR. Please install Prowatchly PWA in Chrome. Exiting."
    exit 0
fi

# Verify Chrome exists
if [ ! -x "/opt/google/chrome/google-chrome" ]; then
    log "Error: Google Chrome not found at /opt/google/chrome/google-chrome"
    exit 1
fi

# Extract APP_ID from .desktop file
APP_ID=\$(basename "\$DESKTOP_FILE" | sed -n 's/^chrome-\(.*\)-Default.desktop\$/\1/p')
if [[ -z "\$APP_ID" ]]; then
    log "Error: Could not extract APP_ID from \$DESKTOP_FILE"
    exit 1
fi

# Launch Prowatchly PWA
log "Found Prowatchly .desktop file: \$DESKTOP_FILE"
log "Launching Prowatchly with APP_ID: \$APP_ID"
/opt/google/chrome/google-chrome --no-sandbox --password-store=basic --kiosk --profile-directory=Default --app-id="\$APP_ID" 2>> "\$LOG_FILE" &

# Verify launch
sleep 5
if ! pgrep -f "chrome.*--app-id=\$APP_ID" >/dev/null; then
    log "Error: Prowatchly failed to launch."
    exit 1
fi
EOF

# Set permissions for launcher script
sudo chmod +x "$LAUNCHER_SCRIPT"
sudo chown "$CLIENT_USER:$CLIENT_USER" "$LAUNCHER_SCRIPT"
log "✅ Launcher script created and permissions set."

# Create the autostart .desktop file for keyring unlock
log "📄 Creating autostart file for keyring unlock..."
sudo bash -c "cat > '$AUTOSTART_DIR/unlock-keyring.desktop'" <<EOF
[Desktop Entry]
Type=Application
Exec=$KEYRING_SCRIPT
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Unlock Keyring
Comment=Unlocks GNOME Keyring on login
EOF
sudo chmod +x "$AUTOSTART_DIR/unlock-keyring.desktop"
sudo chown "$CLIENT_USER:$CLIENT_USER" "$AUTOSTART_DIR/unlock-keyring.desktop"
log "✅ Keyring unlock autostart file created."

# Create the autostart .desktop file for Prowatchly
log "📄 Creating autostart file at $AUTOSTART_FILE..."
sudo bash -c "cat > '$AUTOSTART_FILE'" <<EOF
[Desktop Entry]
Type=Application
Exec=$LAUNCHER_SCRIPT
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Prowatchly Checker
Comment=Launches Prowatchly PWA if available
EOF

# Set permissions for autostart file
sudo chmod +x "$AUTOSTART_FILE"
sudo chown "$CLIENT_USER:$CLIENT_USER" "$AUTOSTART_FILE"
log "✅ Prowatchly autostart file created and permissions set."

# Test GDM3 service status
log "🔍 Testing GDM3 service..."
if sudo systemctl is-active gdm3 >/dev/null; then
    log "✅ GDM3 is running."
else
    log "❌ GDM3 is not running. Attempting to start..."
    sudo systemctl start gdm3
fi

# Test autostart configuration
log "🔍 Testing autostart configuration..."
sudo -u "$CLIENT_USER" bash -c "if [ -f '$AUTOSTART_FILE' ]; then echo 'Autostart file exists' >> '$AUTOSTART_LOG'; fi"
sudo -u "$CLIENT_USER" bash -c "if [ -f '$AUTOSTART_DIR/unlock-keyring.desktop' ]; then echo 'Keyring autostart file exists' >> '$AUTOSTART_LOG'; fi"

log "✅ Setup complete. Reboot to test auto-login, Wayland disable, keyring unlock, and Prowatchly PWA autostart."
echo "ℹ️ Check $LOG_FILE, /tmp/prowatchly_launcher.log, /tmp/prowatchly_keyring.log, and $AUTOSTART_LOG for details."
echo "ℹ️ Wayland is disabled for RustDesk compatibility. GNOME Keyring is unlocked with client password."
echo "ℹ️ Prowatchly will only auto-launch after Chrome is manually opened once to initialize the profile."
echo "🔁 Reboot now to apply changes (run 'sudo reboot')."
