#!/bin/bash

if [ "$EUID" -ne 0 ]; then
  echo "Please run as root!"
  exit
fi

echo "Creating user if not exists"
useradd -p $(openssl passwd -1 iTender2022) itender || true
mkdir /home/itender/
usermod -d /home/itender/ itender || true
chown itender:itender /home/itender

echo "Updating indexes"
apt update

echo "Installing xserver xinit openbox ufw xserver-xorg x11 unclutter make chromium-browser crontab cmake g++ gcc and git..."
apt install --no-install-recommends ufw xserver-xorg x11-xserver-utils xinit openbox -y || exit
apt install git gcc g++ make cmake chromium-browser unclutter iptables cron pigpio -y || exit
echo "Try to uninstall node and npm... (Can fail)"
apt purge node -y || true
apt purge npm -y || true

echo "Setup xserver..."
# XServer
echo "allowed_users=anybody" >/etc/X11/Xwrapper.config
#no-uncomment cp autostart.config /etc/xdg/openbox/autostart

echo "Adding apt keys..."
# Keys and stuff ---
# Nodejs
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash

# Yarn
curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | gpg --dearmor | sudo tee /usr/share/keyrings/yarnkey.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/yarnkey.gpg] https://dl.yarnpkg.com/debian stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

# MongoDB
wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

# End Keys and stuff ---

echo "Updating firewall..."
# Firewall
ufw allow ssh
ufw allow 3000/tcp
ufw allow 3015/tcp
ufw --force enable

echo "Updating indexes..."
# Final update
apt update
echo "Installing mongodb and yarn..."
apt install nodejs yarn mongodb-org -y
apt upgrade -y

adduser itender gpio
adduser itender sudo
chown itender:itender /home/itender/ -R

# V2: Arduino CLI
echo "Installing arduino-cli..."
sudo -u itender mkdir -p /home/itender/bin
sudo -u itender sh -c 'curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/home/itender/bin/ sh'
sudo -u itender /home/itender/bin/arduino-cli config init
sudo -u itender /home/itender/bin/arduino-cli core update-index || true
sudo -u itender /home/itender/bin/arduino-cli lib install ArduinoJson || true
sudo -u itender /home/itender/bin/arduino-cli lib install HX711 || true

echo "Installing autostart..."
# Autostart
cat <<EOT >/etc/xdg/openbox/autostart
xset s off
xset s noblank
xset -dpms
setxkbmap -option terminate:ctrl_alt_bksp

# Start Chromium in kiosk mode
sed -i 's/"exited_cleanly":false/"exited_cleanly":true/' ~/.config/chromium/'Local State'
sed -i 's/"exited_cleanly":false/"exited_cleanly":true/; s/"exit_type":"[^"]\+"/"exit_type":"Normal"/' ~/.config/chromium/Default/Preferences

/usr/bin/chromium-browser --disable-infobars --kiosk --incognito --disable-pinch --overscroll-history-navigation=0 "http://127.0.0.1:3000/" &
EOT

echo "Setting to console autologin..."
raspi-config nonint do_boot_behaviour B2

echo "Installing bashrc"
echo "clear" >>/home/itender/.bashrc
echo "[[ -z \$DISPLAY && \$XDG_VTNR -eq 1 ]] && startx -- -nocursor >/dev/null 2>&1" >>/home/itender/.bashrc

DIR="/home/itender/itender/"
if [ -d "$DIR" ]; then
  # Take action if $DIR exists. #
  cd "$DIR" || exit
  echo "Updating..."
  git pull
else
  echo "Cloning..."
  sudo -u itender git config --global credential.helper store
  git config --global credential.helper store
  git clone "https://tobiash:!IwedwrimmVeudiweN!@git.gaminggeneration.de/tobiash/itender.git" --quiet
fi
cd "$DIR" || exit
yarn install
echo "Compiling..."
yarn run compile

echo "Updating Cron..."
# Add line to cron
echo "@reboot sudo chmod g+rw /dev/tty?" >/tmp/currentCron
#echo "@reboot cd /home/itender/itender/ && /usr/bin/yarn run start &" >> /tmp/currentCron
chown itender:itender /tmp/currentCron
#install new cron file
sudo -u itender crontab /tmp/currentCron

echo "Installing systemd service..."
cat <<EOT >/etc/systemd/system/itender.service
[Unit]
Description=iTender App
After=network.target mongod.service
StartLimitIntervalSec=1
StartLimitBurst=1000

[Service]
Type=simple
Restart=always
RestartSec=1s
User=itender
ExecStartPre=sleep 3
WorkingDirectory=/home/itender/itender/
ExecStart=/usr/bin/yarn run start
StandardOutput=append:/var/log/itender.log
StandardError=append:/var/log/itender.log

[Install]
WantedBy=multi-user.target

EOT
#sh -c "git pull --quiet || true"

echo "Activating systemctl daemons..."
systemctl daemon-reload
systemctl enable mongod
systemctl enable itender

echo "Backing up /boot/config.txt to /root/config.txt.bak"
cp /boot/config.txt /root/config.txt.bak
echo "Updating Boot config..."
if ! grep -w "hdmi_group=2" /boot/config.txt; then
  echo "hdmi_group=2" >>/boot/config.txt
fi
if ! grep -w "hdmi_mode=87" /boot/config.txt; then
  echo "hdmi_mode=87" >>/boot/config.txt
fi
if ! grep -w "hdmi_cvt 1024 600 60 0 0 0 0" /boot/config.txt; then
  echo "hdmi_cvt 1024 600 60 0 0 0 0" >>/boot/config.txt
fi
if ! grep -w "hdmi_drive=1" /boot/config.txt; then
  echo "hdmi_drive=1" >>/boot/config.txt
fi
if ! grep -w "disable_splash=1" /boot/config.txt; then
  echo "disable_splash=1" >>/boot/config.txt
fi
if ! grep -w "vc4-fkms-v3d" /boot/config.txt; then
  sed -i 's/dtoverlay=vc4-kms-v3d/dtoverlay=vc4-fkms-v3d,disable-bt/' /boot/config.txt
fi
if ! grep -w "boot_delay=0" /boot/config.txt; then
  echo "boot_delay=0" >>/boot/config.txt
fi
if ! grep -w "over_voltage=6" /boot/config.txt; then
  echo "over_voltage=6" >>/boot/config.txt
fi
if ! grep -w "arm_freq=1300" /boot/config.txt; then
  echo "arm_freq=1300" >>/boot/config.txt
fi
if ! grep -w "gpu_freq=700" /boot/config.txt; then
  echo "gpu_freq=700" >>/boot/config.txt
fi

echo "Setting no-logo..."
systemctl disable getty@tty1.service

if ! grep -w "logo.nologo" /boot/cmdline.txt; then
  echo "Backing up /boot/cmdline.txt to /root/cmdline.txt.bak"
  cp /boot/cmdline.txt /root/cmdline.txt.bak
  sed -i '1 s_$_ loglevel=3 logo.nologo disable\_splash=1 splash quiet plymouth.ignore-serial-consoles logo.nologo vt.global\_cursor_default=0_' /boot/cmdline.txt
  #cp /tmp/cmdline.txt /boot/cmdline.txt
  sed -i "1 s|$| vt.global_cursor_default=0|" /boot/cmdline.txt

  sed -i 's/console=tty0/console=tty3/' /boot/cmdline.txt
fi

echo "iTender© 2022-2023 - Official licensed software
Programmed by Tobias Hopp" >/etc/motd

echo "[Service]
      ExecStart=/usr/sbin/dhcpcd -q" >/etc/systemd/system/dhcpcd.service.d/wait.conf

chown itender:itender -R /home/itender/

echo "Installation finished!"

reboot now
