#!/bin/bash

    << CHANGELOG
    2021-03-05: Initial Creation
    2021-03-07: Add to GIT
    2021-03-08: Minor bug fixes & visual changes
    2021-04-18: Bug Fix - Append PowerControl to sudoers file via tee command instead. Also added visual check.
    2021-08-03: Moved PowerControl sudoers modification to variables
    2023-10-08: Bug fix for Debian 12 - Remove reference to deb cd in apt/sources.list
    2023-10-09: Adapt support for PowerShell installations for Debian 10/11/12
    2024-03-07: Reload systemd for it to recognize changes to /etc/fstab
    2024-03-09: Add fallback for installing powershell via Direct Download (ex: Debian 12)
CHANGELOG


if [[ "$EUID" -ne 0 ]]; then
	echo "This installer needs to be run with superuser privileges."
	exit
fi




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-01] - Basic Dependencies (apt upgrade). This also removes any reference to 'deb cdrom'.
$(tput sgr 0)
"

sed -i.bak "s@deb cdrom@## deb cdrom@g" /etc/apt/sources.list && \
apt -qq update && apt -qq upgrade -y




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-02] - Install VMWare Tools
$(tput sgr 0)
"

apt -qq install open-vm-tools open-vm-tools-desktop -y




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-03] - Allow all users to Shutdown / Reboot
$(tput sgr 0)
"
    ## 'head -1' is to select only first result.
    ## '-F:' means split on ':' character


NewGroup=PowerControl && \
Description="execute halt and reboot" && \
Binaries="/sbin/halt, /sbin/reboot, /sbin/poweroff, /sbin/shutdown" && \
Acct=$(getent passwd {1000..60000} | head -1 | awk  -F: '{ print $1 }') && echo "Account: ${Acct}" && \
File=/etc/sudoers && \
sudo groupadd ${NewGroup} && sudo usermod -aG ${NewGroup} ${Acct} && \
sudo usermod -aG sudo ${Acct} && \
echo "Found group '${NewGroup}' for user '${Acct}': $((sudo -u ${Acct} id -nG) | grep -c "${NewGroup}")" && \
{
cat << EOF | sudo tee -a ${File}

## User Group allowed to ${Description}
%${NewGroup} ALL=NOPASSWD: ${Binaries}
EOF
} && \
echo "Visual sanity check of sudoers file for ${NewGroup} (hardcoded name): " && \
echo -e "$(tput setaf 7; tput setab 0)" && \
(sudo cat /etc/sudoers | grep ${NewGroup}) && \
echo -e "$(tput sgr 0)"

    #reboot




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-04] - Enable Auto-login
$(tput sgr 0)
"

autologinFile=/usr/share/lightdm/lightdm.conf.d/01_debian.conf
cat >> ${autologinFile} << EOF

[SeatDefaults]
autologin-user=${Acct}
autologin-user-timeout=0
EOF
cat ${autologinFile}




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-05] - Workaround: Cinnamon not sourcing /etc/profile.d/* files on Debian Jessie
$(tput sgr 0)
"

WorkAroundProfileScript=/etc/X11/Xsession.d/70fix_lightdm_gpv && \
echo ${WorkAroundProfileScript} && \
cat << 'EOF' > ${WorkAroundProfileScript}
# GPV: 2-May-2015, lightdm + cinnamon forgets to source ANY profiles!!

# First read /etc/profile and .profile
test -f /etc/profile && . /etc/profile
test -f "$HOME/.profile" && . "$HOME/.profile"
# Second read /etc/xprofile and .xprofile for X specific setup
test -f /etc/xprofile && . /etc/xprofile
test -f "$HOME/.xprofile" && . "$HOME/.xprofile"

# Local Variables:
# mode: shell-script
# sh-indentation: 2
# indent-tabs-mode: nil
# End:

# vim:set ai et sts=2 sw=2 tw=80:
EOF
cat ${WorkAroundProfileScript}




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-06] - Disable Screen Saver (via logon script)
$(tput sgr 0)
"
    ## Used "dconf watch /" to find the matching settings
    # Sources - https://askubuntu.com/a/359601


    # Comment block using :<space>'...'. The space after the colon is important!!!
    # Source - https://stackoverflow.com/a/43158193/11295787
    : '
    Start > System Settings (first icon on left side of start menu) > Screensaver > Settings >
        Delay before starting the screensaver           =   $Never
        Lock the computer when put to sleep             =   $OFF
        Lock the computer after the screensaver starts  =   $OFF
    '

    # Create script that runs on first login for EACH user
    # Source - https://www.attosol.com/login-script-that-runs-only-once-per-user/

DeploymentScript_Screensaver=/etc/profile.d/deploy-screensaver.sh && \
cat << 'EOF' > ${DeploymentScript_Screensaver}
#!/bin/bash

if [ -e $HOME/.deployed-screensaver ]
then
    echo "Skipping... Deployment configuration of screensaver already completed"
else
    echo "$(tput setaf 3; tput setab 0)Disabling screensaver...$(tput sgr 0)"
    gsettings set org.cinnamon.desktop.screensaver lock-enabled false
    gsettings set org.cinnamon.desktop.session idle-delay 0
    gsettings set org.cinnamon.settings-daemon.plugins.power lock-on-suspend false
    date >> $HOME/.deployed-screensaver
fi

EOF
ls /etc/profile.d/deploy-* && cat ${DeploymentScript_Screensaver} && bash ${DeploymentScript_Screensaver}




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-07] - Change Default Screen Resolution (via logon script)
$(tput sgr 0)
"

    # Sources - https://unix.stackexchange.com/a/67716

    : '
    Start > System Settings > Display > 

        Resolution      =   1280 x 800 (16:10)
        $Apply
    '

    ## 'head -1' is to select only first result.
    ## "-F' '" means split on ' ' character
    

DeploymentScript_Resolution=/etc/profile.d/deploy-resolution.sh && \
cat << 'EOF' > ${DeploymentScript_Resolution}
#!/bin/bash


if [ -e $HOME/.deployed-resolution ]
then
    echo "Skipping... Deployment configuration of default resolution already completed"
else
    # ** This is intended for Cinnamon desktop **
    echo "$(tput setaf 3; tput setab 0)Changing resolution... This will take effect on NEXT login$(tput sgr 0)"
    mkdir -p $HOME/.config
    MonitorConfigFile=$HOME/.config/monitors.xml
    cat << 'XML_MONITORS_FILE' > ${MonitorConfigFile}
<monitors version="1">
  <configuration>
      <clone>no</clone>
      <output name="Virtual1">
          <vendor>???</vendor>
          <product>0x0000</product>
          <serial>0x00000000</serial>
          <width>1280</width>
          <height>800</height>
          <rate>60</rate>
          <x>0</x>
          <y>0</y>
          <rotation>normal</rotation>
          <reflect_x>no</reflect_x>
          <reflect_y>no</reflect_y>
          <primary>yes</primary>
      </output>
      <output name="Virtual2">
      </output>
      <output name="Virtual3">
      </output>
      <output name="Virtual4">
      </output>
      <output name="Virtual5">
      </output>
      <output name="Virtual6">
      </output>
      <output name="Virtual7">
      </output>
      <output name="Virtual8">
      </output>
  </configuration>
</monitors>

XML_MONITORS_FILE

    chmod 644 ${MonitorConfigFile}
    date >> $HOME/.deployed-resolution
fi


EOF
ls /etc/profile.d/deploy-* && cat ${DeploymentScript_Resolution} && bash ${DeploymentScript_Resolution}




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-08] - Allow Root login on ssh
$(tput sgr 0)
"

sed -i.bak "s@#PermitRootLogin prohibit-password@#PermitRootLogin prohibit-password\nPermitRootLogin yes@g" /etc/ssh/sshd_config
cat /etc/ssh/sshd_config | grep -e "PermitRootLogin"
service sshd restart




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-09] - Install PowerShell on Linux
$(tput sgr 0)
"

# Import variables to determine version of Debian
source /etc/os-release
if [[ "$VERSION_ID" == 9 ]]
then
    # What this does:
    # A) Install system components
    # B) Import the public repository GPG keys
    # C) Register the Microsoft Product feed
    # D) Update the list of products & Install PowerShell
    # E) Get PowerShell path
    # $Sample_Output:
    #   /usr/bin/pwsh
    sudo apt -qq update && sudo apt -qq install -y curl gnupg apt-transport-https && \
    (curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -) && \
    sudo sh -c 'echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-debian-stretch-prod stretch main" > /etc/apt/sources.list.d/microsoft.list' && \
    sudo apt -qq update && sudo apt -qq install -y powershell && \
    echo -e "$(tput setaf 7; tput setab 0)" && \
    echo "PowerShell Path: " && \
    which pwsh && \
    echo -e "$(tput sgr 0)"
elif [[ $VERSION_ID -ge 10 ]]
then
    # What this does:
    # A) Install pre-requisite packages.
    # B) Get the version of Debian (via `source /etc/os-release` done at the start)
    # C) Download the Microsoft repository GPG keys
    # D) Register the Microsoft repository GPG keys (dpkg install)
    # E) Update the list of packages after we added packages.microsoft.com
    # F) Install PowerShell
    # G) Get PowerShell path
    sudo apt -qq update && sudo apt -qq install -y wget && \
    wget -q https://packages.microsoft.com/config/debian/$VERSION_ID/packages-microsoft-prod.deb && \
    sudo dpkg -i packages-microsoft-prod.deb && \
    sudo apt -qq update && \
    sudo apt -qq install -y powershell
    if [ $? -eq 0 ]; then
        echo "Success! PowerShell was successfully installed (most likely)." && \
        echo -e "$(tput setaf 7; tput setab 0)" && \
        echo "PowerShell Path: " && \
        which pwsh && \
        echo -e "$(tput sgr 0)"
    else
        # What this does:
        # A) Downloads the PowerShell package file
        # B) Extracts original filename / basename from github release URL
        # C) Installs PowerShell
        # D) Resolve missing dependencies and finish the install (if necessary)
        # E) Get PowerShell path
        echo "Failed! PowerShell failed to install for some reason." && \
        echo "FALLBACK: Manually installing PowerShell from direct download from github release now..." && \
        ReleaseURL=https://github.com/PowerShell/PowerShell/releases/download/v7.4.1/powershell_7.4.1-1.deb_amd64.deb
        wget ${ReleaseURL} && \
        sudo dpkg -i $(basename ${ReleaseURL}) && \
        sudo apt-get install -f && \
        echo -e "$(tput setaf 7; tput setab 0)" && \
        echo "PowerShell Path: " && \
        which pwsh && \
        echo "In future, to manually remove powershell, use the command 'sudo apt-get remove powershell'" && \
        echo -e "$(tput sgr 0)"
    fi
else
    echo -e "$(tput setaf 1; tput setab 0)ERR: Unsupported version of debian! Skipping PowerShell installation...$(tput sgr 0)"
fi



echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-10] - Install NFS tools & Mount Public Share
$(tput sgr 0)
"

    : '
        ** Must reload systemd after making changes to fstab
        Source - https://news.ycombinator.com/item?id=23030121
    '

NAS_Host=N40L && \
NAS_Share=/volume1/Public && \
PublicFolder=/mnt/Public && \
sudo apt -qq install nfs-common -y && \
sudo mkdir -p ${PublicFolder} && \
sudo chmod 755 ${PublicFolder} && \
touch ${PublicFolder}/NOT_MOUNTED && \
echo -e "$(tput setaf 7; tput setab 0)" && \
echo "# <file system>  <dir>  <type>  <options>  <dump>  <pass>" | sudo tee -a /etc/fstab && \
echo "${NAS_Host}:${NAS_Share}   /mnt/Public  nfs   defaults,nofail   0   0" | sudo tee -a /etc/fstab && \
echo "Reloading systemd/systemctl to re-read changes to fstab" && \
sudo systemctl daemon-reload && \
echo -e "$(tput sgr 0)" && \
if ping -c 1 ${NAS_Host} &> /dev/null
then
  echo -e "$(tput setaf 7; tput setab 0)Host ${NAS_Host} is online! Mounting ${NAS_Host}:${NAS_Share}...$(tput sgr 0)"
  sudo mount -av;
else
  echo -e "$(tput setaf 7; tput setab 0)Host ${NAS_Host} is OFFLINE! Skipping mount...$(tput sgr 0)"
fi



echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-11] - Show if Deployment Settings were done
$(tput sgr 0)
"

echo -e "$(tput setaf 7; tput setab 0)" && \
echo "Deployment Configs that were run: " && \
ls -a .deploy* && \
echo -e "$(tput sgr 0)"




echo -e "
$(tput setaf 3; tput setab 0)
    >> # [Deploy-12] - Deployment Script Cleanup
$(tput sgr 0)
"

if ! command -v realpath &> /dev/null
then
    echo -e "COMMAND 'realpath' could not be found. $(tput setaf 3; tput setab 0)Please move script manually.$(tput sgr 0)"
else
    SCRIPT=`realpath -s $0` && \
    DESTINATION=~/Deploy && \
    mkdir -p ${DESTINATION} && \
    mv ${SCRIPT} ${DESTINATION} && \
    ls -laR ${DESTINATION}
fi
