#!/bin/bash

echo "Please select the version of MSSQL Server you want to install："
echo "1. SQL Server 2022 Express"
echo "2. SQL Server 2019 Express"
echo -n "Please input（1 or 2）: "
read mssql_version

if [ "$mssql_version" != "1" ] && [ "$mssql_version" != "2" ]; then
    echo "Invalid option. Please re-run the script and select a valid version"
    exit 1
fi

export MSSQL_SA_PASSWORD=$(openssl rand -base64 12)

curl https://packages.microsoft.com/keys/microsoft.asc | tee /etc/apt/trusted.gpg.d/microsoft.asc
add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/prod.list)"


if [ "$mssql_version" == "1" ]; then
    add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/mssql-server-2022.list)"
elif [ "$mssql_version" == "2" ]; then
    add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/mssql-server-2019.list)"
fi

#install 2022 Express Version
#add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/mssql-server-2022.list)"
#install 2019 Express Version
#add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/mssql-server-2019.list)"

apt-get update

sudo ACCEPT_EULA=Y sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mssql-server
sudo ACCEPT_EULA=Y sudo apt-get install -y mssql-tools unixodbc-dev

echo '3' | sudo MSSQL_SA_PASSWORD=$MSSQL_SA_PASSWORD /opt/mssql/bin/mssql-conf setup accept-eula

echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
echo 'export PATH="$PATH:/opt/mssql/bin"' >> ~/.bashrc
source ~/.bashrc

systemctl start mssql-server

systemctl enable mssql-server

if [ "$mssql_version" == "1" ]; then
echo "SQL Server 2022 Express install success"
echo "SA password is: $MSSQL_SA_PASSWORD" >> /opt/mssql/password.txt 
elif [ "$mssql_version" == "2" ]; then
echo "SQL Server 2019 Express install success"
echo "SA password is: $MSSQL_SA_PASSWORD" >> /opt/mssql/password.txt 
fi
