#!/bin/bash

did=debian12
version=8.2.1

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-$did-$version.tgz
gunzip mongodb-linux-x86_64-$did-$version.tgz
tar xvf mongodb-linux-x86_64-$did-$version.tar
mv mongodb-linux-x86_64-$did-$version /usr/local/mongodb
rm -r mongodb-linux-x86_64-$did-$version.tar

wget https://downloads.mongodb.com/compass/mongosh-$shVersion\-linux-x64-openssl3.tgz
gunzip mongosh-$shVersion\-linux-x64-openssl3.tgz
tar xvf mongosh-$shVersion\-linux-x64-openssl3.tar
mv mongosh-$shVersion\-linux-x64-openssl3/bin/mongosh /usr/bin

mkdir /usr/local/mongodb/db
chmod -R 755 /usr/local/mongodb
/usr/local/mongodb/bin/mongod --dbpath /usr/local/mongodb/db --bind_ip_all &
echo $! > /usr/local/mongodb/pid

ln -fs /usr/local/mongodb/bin/* /usr/bin

reset

read -p 'Username: ' username
read -p 'Password: ' password

[[ -z $username ]] || [[ -z $password ]] && exit

# Connect
# mongosh --port 27017 -u $username -p $password --authenticationDatabase 'admin'

# Create user
## Global perms
use admin
db.createUser(
  {
    user: $username,
    pwd: $password,
    roles: [ { role: "root", db: "admin" } ]
  }
)

# For all keys see
# https://www.mongodb.com/docs/manual/reference/configuration-file-settings-command-line-options-mapping/?tck=mongodb_ai_chatbot
cat << EOF > /etc/mongod.conf
net:
  bindIp: 0.0.0.0
  port: 27017
storage:
  dbPath: /usr/local/mongo
security:
  authorization: enabled
systemLog:
  destination: file
  path: "/var/log/mongodb/mongod.log"
  logAppend: true
EOF

cat << EOF > /root/.mongoshrc.js
db.auth($username, $password)
EOF