#!/bin/sh

check_available() {
  # Function to check if a program is installed
  which $1 &> /dev/null

  if [ $? = 1 ]; then
    echo "$1 is not available, please install it before running the script"
    exit 1
  fi
}

gen_password() {
  check_available openssl
  openssl rand -base64 32
}

read -p "Redis password: (press enter to randomize): " redis_password
redis_password=${redis_password:-`gen_password`}

read -p "Session secret: (press enter to randomize): " session_secret
session_secret=${session_secret:-`gen_password`}

read -p "MongoDB password: (press enter to randomize): " mongo_password
mongo_password=${mongo_password:-`gen_password`}


if [ ! -f "./.env" ]; then
  echo "Copying ./env.example to ./.env"
  cp ./env.example ./.env
fi

sed -i -e "s#REDIS_PASSWORD=.*#REDIS_PASSWORD=${redis_password}#g" \
       "$(dirname "$0")/.env"

sed -i -e "s#SESSION_SECRET=.*#SESSION_SECRET=${session_secret}#g" \
       "$(dirname "$0")/.env"

sed -i -e "s#MONGODB_PASSWORD=.*#MONGODB_PASSWORD=${mongo_password}#g" \
       "$(dirname "$0")/.env"

read -p "Start docker containers? (requires docker-compose) [Y/n] " start_docker
start_docker=${start_docker:-Y}

if [[ $start_docker =~ [yY] ]]; then
  check_available docker-compose
  sudo docker-compose up -d
fi
