#!/bin/bash

cd /home/develop/BD

# Check if username argument is provided
if [ -z "$3" ]
then
  echo "Please provide a containername, username, password as an argument"
  exit 1
fi

# Create new folder with username
mkdir "back/$1"

# Copy files from "./to_copy" to new folder
cp -r ./back/db/* "back/$1/"

# Find free port greater than 1000
port=$(shuf -i 1001-65535 -n 1)

# Create new docker-compose.yml file
cat > "all_containers/$1.yml" << EOF
  $1:
    image: back-master:0.0.1
    build: .
    volumes:
      - ./$1:/app/db
      - ./$1:/app/images
    ports:
      - "$port:8000"
    container_name: $1
    command: ./runserver.sh $1

EOF

ln -f "all_containers/$1.yml" "enabled_containers/$1.yml"

echo "New folder with name $1 has been created, files have been copied, and docker-compose.yml file has been created with port $port."

# setup nginx proxy
cat > "/home/develop/BD/student_services/$1.conf" << EOF
location /$1/images/images {
	rewrite ^/$1/images/images/(.*)$ /$1/$1/images/images/\$1;
	proxy_pass http://localhost:$port/$1/$1/images/images/;
}

location /$1 {
	proxy_pass http://localhost:$port/;
}
EOF

sudo service nginx restart

./scripts/docker_compose.sh

cd back 

docker-compose exec "$1" python3 manage.py createsuperuserwithpassword --username "$2" --password "$3" --email admin@example.org --preserve