#!/bin/bash

CURRENT_USER=$(whoami)
USER_1000=$(getent passwd 1000 | cut -d: -f1)

if [ "$USER_1000" != "mcdonalds" ]; then
    echo "ERRO: Usuario com UID 1000 nao e 'mcdonalds' (encontrado: $USER_1000)"
    exit 1
fi

if [ "$CURRENT_USER" != "mcdonalds" ]; then
    echo "ERRO: Este script deve ser executado como usuario 'mcdonalds'"
    echo "Execute: su - mcdonalds -c 'bash $0'"
    exit 1
fi

export XDG_RUNTIME_DIR=/run/user/1000
export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus

echo "=================================================="
echo "  Iniciando Configuracao do Sistema (Modo Kiosk)"
echo "=================================================="
echo "Usuario: ${CURRENT_USER}"
echo ""

echo "[1/16] Configurando sudo sem senha..."
sudo sed -i 's/^%sudo.*/%sudo   ALL=(ALL:ALL) NOPASSWD: ALL/g' /etc/sudoers

echo "[2/16] Atualizando pacotes do sistema..."
#sudo sed -i 's/br.//g' /etc/apt/sources.list
sudo apt update
sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y

echo "[3/16] Configurando DNS..."
sudo chattr -i /etc/resolv.conf
sudo tee /etc/NetworkManager/conf.d/90-dns-none.conf <<EOF
[main]
dns=none
EOF
sudo systemctl disable systemd-resolved
sudo systemctl stop systemd-resolved
sudo rm -f /etc/resolv.conf
echo 'nameserver 8.8.8.8' | sudo tee /etc/resolv.conf
sudo chattr +i /etc/resolv.conf
sudo systemctl restart NetworkManager

echo "[4/16] Instalando pacotes necessarios..."
sudo DEBIAN_FRONTEND=noninteractive apt install -y ssh curl wget rsync vim screen libcanberra-gtk-module

echo "[5/16] Configurando firewall..."
sudo ufw allow 22

echo "[6/16] Configurando SSH..."
mkdir -p ~/.ssh/
cat <<EOF | tee ~/.ssh/config
Host *
  StrictHostKeyChecking no
  UserKnownHostsFile /dev/null
  ServerAliveInterval 60
  ConnectTimeout 30
EOF

sudo mkdir -p /root/.ssh/
cat <<EOF | sudo tee /root/.ssh/config
Host *
  StrictHostKeyChecking no
  UserKnownHostsFile /dev/null
  ServerAliveInterval 60
  ConnectTimeout 30
EOF

sudo sed -i 's/.*PermitRootLogin.*/PermitRootLogin yes/g' /etc/ssh/sshd_config
sudo systemctl restart ssh

echo -e "radiob123\nradiob123" | sudo passwd mcdonalds
echo -e "radiob123\nradiob123" | sudo passwd root

echo "[7/16] Desabilitando GNOME Keyring..."
mkdir -p ~/.config/autostart
cd /etc/xdg/autostart
cp gnome-keyring-*.desktop ~/.config/autostart 2>/dev/null || true
for file in ~/.config/autostart/gnome-keyring-*.desktop
do
  [ -f "$file" ] && echo "X-GNOME-Autostart-enabled=false" | tee -a ${file}
done
cd

rm -f ~/.local/share/keyrings/*
mkdir -p ~/.local/share/keyrings
cat <<EOF > /home/mcdonalds/.local/share/keyrings/default
Chaveiro
EOF
cat <<EOF > /home/mcdonalds/.local/share/keyrings/Chaveiro.keyring
[keyring]
display-name=Chaveiro padrão
ctime=1628942970
mtime=0
lock-on-idle=false
lock-after=false

[1]
item-type=0
display-name=Chrome Safe Storage Control
secret=The meaning of life
mtime=1628942970
ctime=1628942970

[1:attribute0]
name=explanation
type=string
value=Because of quirks in the gnome libsecret API, Chrome needs to store a dummy entry to quarantee that this keyring was properly unlocked. More details at http://crbug.com/66000

[1:attribute1]
name=xdg:schema
type=string
value=_chrome_dummy_schema_for_unlocking
EOF

echo "[8/16] Desabilitando bloqueio de tela e modos de suspensao..."
gsettings set org.gnome.desktop.screensaver lock-enabled false
gsettings set org.gnome.desktop.lockdown disable-lock-screen 'true'
gsettings set org.gnome.desktop.screensaver idle-activation-enabled false
gsettings set org.gnome.desktop.session idle-delay 0
gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-battery-timeout 0
gsettings set org.gnome.settings-daemon.plugins.power sleep-inactive-ac-timeout 0
gsettings set org.gnome.settings-daemon.plugins.power idle-dim false
gsettings set org.gnome.desktop.notifications show-banners false

echo "[9/16] Ocultando dock..."
gsettings set org.gnome.shell.extensions.dash-to-dock autohide false
gsettings set org.gnome.shell.extensions.dash-to-dock dock-fixed false
gsettings set org.gnome.shell.extensions.dash-to-dock intellihide false
gsettings set org.gnome.settings-daemon.plugins.orientation active false

echo "[10/16] Desabilitando alvos de suspensao do sistema..."
sudo systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target

echo "[11/16] Desabilitando atualizacoes automaticas..."
sudo sed -i 's/"1"/"0"/g' /etc/apt/apt.conf.d/20auto-upgrades
sudo sed -i 's/"1"/"0"/g' /etc/apt/apt.conf.d/10periodic
sudo systemctl mask snapd.service
sudo systemctl disable --now apt-daily{,-upgrade}.{timer,service}
sudo DEBIAN_FRONTEND=noninteractive apt purge -yq update-notifier-common
sudo DEBIAN_FRONTEND=noninteractive apt autoremove -yq

echo "[12/16] Configurando GDM para login automatico..."
cat <<EOF | sudo tee /etc/gdm3/custom.conf
[daemon]
InitialSetupEnable=false
AutomaticLoginEnable=true
AutomaticLogin=mcdonalds
WaylandEnable=false
[security]
[xdmcp]
[chooser]
[debug]
EOF

echo "[13/16] Removendo ferramentas antigas de gerenciamento remoto..."
sudo pkill -f 4you
sudo pkill -f Robot
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus systemctl --user stop 4youseeRobot 2>/dev/null || true
sudo find /home/ -iname '*.4yousee*' -exec rm -rf {} \; 2>/dev/null || true
sudo find /home/ -iname '*4yousee*' -exec rm -rf {} \; 2>/dev/null || true
sudo rm -f /etc/systemd/user/4youseeRobot.service
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus systemctl --user daemon-reload
sudo systemctl daemon-reload

rm -rf anydesk*
sudo systemctl stop remotely-agent 2>/dev/null || true
sudo rm -r -f /usr/local/bin/Remotely
sudo rm -f /etc/systemd/system/remotely-agent.service
sudo systemctl daemon-reload
sudo DEBIAN_FRONTEND=noninteractive apt purge -yqf anydesk

echo "[14/16] Instalando sistema de sinalização digital 4YouSee..."
#curl -L -H 'Cache-Control: no-cache' https://files.megamidia.site/jose-4yousee-script.sh | bash
#curl -L -H 'Cache-Control: no-cache' http://files.4yousee.com.br/players/new/robot/installRobot.sh | bash

echo "[15/16] Configurando politica de reinicio do servico 4YouSee..."
sudo [ -z "$(cat /etc/systemd/user/4youseeRobot.service 2>/dev/null | grep 'Restart=')" ] && sudo sed -i '/^KillMode.*/a Restart=on-failure' /etc/systemd/user/4youseeRobot.service
sudo [ -z "$(cat /etc/systemd/user/4youseeRobot.service 2>/dev/null | grep 'RestartSec=30s')" ] && sudo sed -i '/^Restart=.*/a RestartSec=30s' /etc/systemd/user/4youseeRobot.service
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus systemctl --user daemon-reload
sudo systemctl daemon-reload
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus systemctl --user enable --now 4youseeRobot

echo "[16/16] Configurando sincronizacao de horario e finalizando..."
if [ -z "$(command -v ntpdate)" ]
then
  sudo wget -O /tmp/ntpdate.deb https://files.megamidia.site/ntpdate_4.2.8p10+dfsg-5ubuntu7.3_amd64.deb
  sudo dpkg -i /tmp/ntpdate.deb
fi
sudo ntpdate -u 200.160.0.8
sudo [ -z "$(cat /etc/crontab | grep ntpdate)" ] && (echo '0 */4 * * * root ntpdate -u 200.160.0.8' | sudo tee -a /etc/crontab) && sudo systemctl restart cron

wget -O /home/mcdonalds/megamidia.png https://files.megamidia.site/megamidia2.png
mkdir -p /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/
cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo.png
cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo2.png
cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo3.png
cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo-white.png

sudo [ -z "$(crontab -u mcdonalds -l 2>/dev/null | grep megamidia.png)" ] && (crontab -u mcdonalds -l 2>/dev/null; echo '0 * * * * [ -f /home/mcdonalds/megamidia.png ] && cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo.png && cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo2.png && cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo3.png && cp /home/mcdonalds/megamidia.png /home/mcdonalds/.4yousee/player/4YouSeeChromeApp/images/logo-white.png') | crontab -u mcdonalds -

wget "https://mesh.megamidia.com.br/meshagents?script=1" --no-check-certificate -O ./meshinstall.sh
sudo chmod 755 ./meshinstall.sh && sudo -E ./meshinstall.sh https://mesh.megamidia.com.br '5XDvcPWo1lHoCAd$frhUGX6SFfg3J66edWUhwtqEE8sRotiO7A4GTm6p15HDP6mL'

echo ""
echo "=================================================="
echo "       Configuracao do Sistema Concluida!"
echo "=================================================="
echo " ✓ Bloqueio de tela e suspensao desabilitados"
echo " ✓ Atualizacoes automaticas desabilitadas"
echo " ✓ Sistema de sinalizacao digital 4YouSee instalado"
echo " ✓ Gerenciamento remoto MeshCentral instalado"
echo "=================================================="
echo " Aguarde confirmacao do suporte antes de reiniciar"
echo "=================================================="
