#!/bin/bash
username=smg
password=1q2w3e
architecture=""
myhostname="smglinux"
zeronetwork=6c48a17611349433
chinaDevice=0
if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

function package_exists() {
    return dpkg -l "$1" &> /dev/null
}

function installTinkerboardRTC(){
apt update -y
sed -i 's/#intf:i2c1/intf:i2c1/' /boot/config.txt
sed -i 's/intf:i2c1=off/intf:i2c1=on/' /boot/config.txt

sed -i 's/#intf:spi0/intf:spi0/' /boot/config.txt
sed -i 's/intf:spi0=off/intf:spi0=on/' /boot/config.txt

sed -i 's/#intf:pcm_i2s/intf:pcm_i2s/' /boot/config.txt
sed -i 's/intf:pcm_i2s=off/intf:pcm_i2s=on/' /boot/config.txt

if grep -q ds1307 "/etc/rc.local"; then
    echo "patch applied to rc.local"
else
    echo "patching rc.local"
    sed -i "s#^exit 0*#echo ds1307 0x68 > /sys/class/i2c-adapter/i2c-1/new-device\nexit 0#g" /etc/rc.local
    sed -i "s#^exit 0*#echo 'ds1307 0x68' | sudo tee /sys/class/i2c-adapter/i2c-1/new_device\nexit 0#g" /etc/rc.local
fi

if grep -q ds1307 "/etc/modules"; then
    echo "patch applied to etc/modules"
else
   echo "patching /etc/modules"
    echo 'rtc-ds1307' >> /etc/modules
fi

if grep -q '#exit' "/lib/udev/hwclock-set"; then
    echo "patch applied to hwclock-set"
else
    echo "patching hwclock-set"
    sed -i 's/exit 0/#exit 0/' /lib/udev/hwclock-set
fi


if package_exists fake-hwclock ; then
  sudo apt -y remove fake-hwclock
  sudo update-rc.d -f fake-hwclock remove
fi
sed -i 's/rtc0/rtc1/' /lib/udev/rules.d/50-udev-default.rules
sed -i 's/rtc0/rtc1/' /lib/udev/rules.d/85-hwclock.rules
sed -i 's/rtc0/rtc1/' /etc/default/hwclock
sed -i 's/rtc0/rtc1/' /lib/udev/hwclock-set

if [ -f "/etc/rtc" ]; then
 echo "/etc/rtc exists"
else
 echo "creating /etc/rtc"
tee -a /etc/rtc <<EOF
#!/bin/bash
#this is the script to be executed at boot to create the rtc interface
echo 'ds1307 0x68' | sudo tee /sys/class/i2c-adapter/i2c-1/new_device
sudo hwclock -s
sudo hwclock --rtc /dev/rtc1 --hctosys
sudo hwclock -w
EOF
chmod 755 /etc/rtc
fi

if [ -f "/etc/systemd/system/rtc.service" ]; then
 echo "rtc service exists"
else
echo "creating rtc service"
tee -a /etc/systemd/system/rtc.service <<EOF
[Unit]
Description=RTC Clock
Before=cloud-init-local.service
Requires=systemd-modules-load.service
After=systemd-modules-load.service
[Type]
Type=oneshot
[Service]
ExecStart=/etc/rtc
[Install]
WantedBy=multi-user.target
EOF

chmod a+x /etc/systemd/system/rtc.service
systemctl enable rtc.service
systemctl start rtc.service
fi

systemctl set-default multi-user.target
rm -f /etc/systemd/system/getty@tty1.service.d/override.conf


if ! package_exists sqlite3 ; then
 wget http://ftp.debian.org/debian/pool/main/s/sqlite3/sqlite3_3.27.2-3+deb10u1_armhf.deb
 apt install ./sqlite3_3.27.2-3+deb10u1_armhf.deb
 rm -rf sqlite3_3.27.2-3+deb10u1_armhf.deb
fi

}

function checklinaro(){
OSNAME=$(uname -n)
if [[ $OSNAME == "linaro-alip" ]]
  then
  echo "this system is tinkerboard linaro"
  installTinkerboardRTC
else
  echo "this is $OSNAME, not tinkerboard linaro"
fi

}


function checkos(){
 case $(uname -m) in
    i386)   architecture="386" ;;
    i686)   architecture="386" ;;
    x86_64) architecture="amd64" ;;
    arm)    dpkg --print-architecture | grep -q "arm64" && architecture="arm64" || architecture="arm" ;;
    armv7l)  architecture="armhf" ;;
    aarch64) architecture="arm64"
 esac
 echo "cpu type is $architecture"  
}

function deletemyuser(){
    echo 'user $username found'
    read -p "do you want to delete $username? " -n 1 -r
    echo    # (optional) move to a new line
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
    # do dangerous stuff
      echo "delete user $username"
      userdel -r $username
    else
      echo "user $username NOT DELETED"
    fi

}

function addpermissions(){
  echo "adding $username to required groups"
  usermod -a -G sudo,root,pulse,audio,tty,plugdev,bluetooth,video,netdev,dialout,systemd-journal $username
}

function addmyuser(){
 if id "$username" &>/dev/null; then
     echo "$username exists"
     addpermissions
 else
   echo 'user not exists,creating'
   read -sp 'Password:' newpassword
   password=$newpassword
   echo "adding user $username"
   adduser --gecos "" --disabled-password $username
   chpasswd <<<"$username:$password"
   addpermissions
 fi
}




function askuser(){
  read -e -p "which user will be used to install? " -i "$username" newuser
  username=$newuser
  addmyuser
}

function checkmeson(){

 if [[ $(uname -a) == *meson64-amedia* ]];
 then
   chinaDevice=1
   echo "This device is chinese soc device, installing default features"
    echo "setting zeronetwork to chinese devices"
	zeronetwork=6c48a1761121108d
   sudo tee /etc/apt/sources.list<<EOF
deb http://deb.debian.org/debian bullseye main
deb-src http://deb.debian.org/debian bullseye main

deb http://security.debian.org/debian-security bullseye-security main
deb-src http://security.debian.org/debian-security bullseye-security main

deb http://deb.debian.org/debian bullseye-updates main
deb-src http://deb.debian.org/debian bullseye-updates main

deb http://deb.debian.org/debian bullseye-backports main
deb-src http://deb.debian.org/debian bullseye-backports main
EOF
   apt update -y
   apt install nano acl alsa-utils usbutils build-essential git curl sqlite3 bluetooth bluez bluez-tools alsa-ucm-conf mc unzip htop openssh-server -y
   groupadd audio
   groupadd pulse
   alsactl init
   sudo setfacl -m u:$username:rw /dev/snd/*
   FILE=/usr/bin/hwclock
   if [ -f "$FILE" ]; then
    echo "hwclock permission exists.."
   else
    echo "$FILE does not exist.setting permission for normal user"
    ln -s /usr/sbin/hwclock /usr/bin
   fi
    if [[ $(timedatectl | grep "Time zone") == *Europe/Istanbul* ]];
    then
       echo "timezone already set"
    else
       echo "setting timezone"
       timedatectl set-timezone Europe/Istanbul
	   hwclock -w
    fi
 else
   echo "No Match"
 fi
}

function checkfileversion(){
while :; do
  read -p "Enter a number between 1 and 5: " number
  [[ $number =~ ^[0-9]+$ ]] || { echo "Enter a valid number"; continue; }
  if [ "$number" -ge 1 ] && [ "$number" -le 5 ]; then
    echo >&2 "valid number"
    break
  else
    echo >&2 "number out of range, try again"
  fi
done
  echo "$number"
}

function installzerotier(){
 curl -s https://install.zerotier.com | sudo bash
 zerotier-cli info
 zerotier-cli join $zeronetwork
}

function installteamviewer(){
 dpkg --add-architecture armhf
 apt-get update -y
 apt-get install libqt5gui5 libqt5qml5 libqt5quick5 libqt5webkit5 libqt5qml5 libqt5core5a qml-module-qtquick-controls qml-module-qtquick2 libqt5widgets5 -y
 apt-get install libxtst6:armhf -y
 wget https://download.teamviewer.com/download/linux/teamviewer-host_armhf.deb
 apt install ./teamviewer-host_armhf.deb
 teamviewer --daemon enable
 rm -rf teamviewer-host_armhf.deb
}

function installArm64(){
  url=http://install.smg.com.tr/arm64/
  filename=smgplayerArm64.zip
  playerversion=nodeplayer8.7.17.zip
  v8711=nodeplayer8.7.11.zip
  v8712=nodeplayer8.7.12.zip
  v8713=nodeplayer8.7.13.zip
  v8714=nodeplayer8.7.14.zip
  v8717=nodeplayer8.7.17.zip
  echo "Please select player version"
  echo "1- $v8711"
  echo "2- $v8712"
  echo "3- $v8713"
  echo "4- $v8714"
  echo "5- $v8717"
  selectedversion=$(checkfileversion)
  case $selectedversion in
    1)   playerversion=$v8711 ;;
    2)   playerversion=$v8712 ;;
    3)   playerversion=$v8713 ;;
    4)   playerversion=$v8714 ;;
    5)   playerversion=$v8717 ;;
 esac
  echo "selection:$selectedversion - $playerversion"
  if [ -f "$(pwd)/$playerversion" ]; then
     echo "$playerversion exists"
  else
    echo "downloading $url$playerversion"
    wget $url$playerversion
  fi

  if [ -f "$(pwd)/$filename" ]; then
     echo "$filename exists"
  else
    echo "downloading $url$filename"
    wget $url$filename
  fi
  servicestatus=$(systemctl show --type service --property Names 'smg*'|cut -d "=" -f 2)
  if [[ $servicestatus == "smg.service" ]]; then
    echo "smg service exists"
    systemctl stop smg
    killall SMGPlayer
    killall watchdog
    killall nodeplayer
  else
    echo "smg service NOT exists"
  fi
  rm -rf smgplayer
  rm -rf nodeplayer
  unzip $filename
  unzip $playerversion
  mv nodeplayer $(pwd)/smgplayer
  echo "modifying permissions"
  chmod a+x "$(pwd)/smgplayer/smg.service"
  chmod +x "$(pwd)/smgplayer/smgstats"
  chmod +x "$(pwd)/smgplayer/SMGPlayer"
  chmod +x "$(pwd)/smgplayer/watchdog"
  chmod +x "$(pwd)/smgplayer/nodeplayer"
  chown -R $username:$username "$(pwd)/smgplayer"
  runpath=/home/$username/smgplayer/SMGPlayer
  rootpath=/
  echo "modifying files for user $username"
  sed -i "s/^User=.*/User=$username/g" smgplayer/smg.service
  sed -i "s#^ExecStart=.*#ExecStart=$runpath#g" smgplayer/smg.service
  sed -i "s#^APP_DIR=.*#APP_DIR=/home/$username/smgplayer#g" smgplayer/SMGPlayer
  sed -i "s#^exePath=.*#exePath=/home/$username/smgplayer/nodeplayer#g" smgplayer/config.ini
  sed -i "s#^updatePath=.*#updatePath=/home/$username/smgplayer/update#g" smgplayer/config.ini
  sed -i "s#^playerpath=.*#playerpath=/home/$username/smgplayer#g" smgplayer/smgstats
  sed -i "s#^rootpath=.*#rootpath=$rootpath#g" smgplayer/smgstats
  if [[ $chinaDevice == 1 ]];
  then
    echo "setting sound card to 2 on chinese device"
    sed -i "s#^soundCard=.*#soundCard=2#g" smgplayer/config.ini
    sed -i "s#^deviceID=.*#deviceID=1#g" smgplayer/config.ini
  fi
  mv $(pwd)/smgplayer/smgstats /usr/bin
  mv $(pwd)/smgplayer/smg.service /etc/systemd/system
  rm -rf /home/$username/smgplayer
  mv $(pwd)/smgplayer /home/$username
  systemctl enable smg
  rm -rf nodeplayer8.7*
  rm -rf $filename
  if [[ $chinaDevice == 1 ]];
  then
    echo "this is china Device, installing audio.sh"
	sudo tee /home/$username/smgplayer/audio.sh<<EOF
#!/bin/bash
amixer -c 0 set 'TOACODEC OUT EN' 'on'
amixer -c 0 set 'TOACODEC SRC' 'I2S B'
amixer -c 0 set 'TDMOUT_B SRC SEL' 'IN 0'
amixer -c 0 set 'FRDDR_A SRC 2 EN' 'on'
amixer -c 0 set 'FRDDR_A SINK 1 SEL' 'OUT 0'
amixer -c 0 set 'FRDDR_A SINK 2 SEL' 'OUT 1'
amixer -c 0 set 'FRDDR_A SINK 3 SEL' 'OUT 2'
amixer -c 0 set 'ACODEC' '100%'
amixer -c 0 set 'PCM' '100%'
EOF
  chmod +x /home/$username/smgplayer/audio.sh
  chown $username:$username /home/$username/smgplayer/audio.sh
	if grep -q "$APP_DIR/audio.sh" /home/$username/smgplayer/SMGPlayer
	then
	  echo "audio.sh already patched"
	else
	  echo "no patch applied"
	  sed -i '/startdate="/a $APP_DIR/audio.sh' /home/$username/smgplayer/SMGPlayer
	fi
  fi
  echo "player installation finished"
  echo "please start service after editing config.ini"
  echo "run sudo systemctl start smg"

}

function checkarch(){
  if [ $architecture == "arm64" ]; then
    echo "Operating system is Arm64"
    echo "checking chinese device"
    checkmeson
    installArm64
	installzerotier
  elif [ $architecture == "armhf" ]; then
    echo "system is armhf"
	checklinaro
  else
    echo "not ready.."
  fi
}


checkos
askuser
checkarch
addpermissions

