#!/bin/sh

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check for Git
if ! command_exists git; then
    echo "Error: Git is not installed. Please install Git and try again."
    exit 1
fi

# Check for Docker
if ! command_exists docker; then
    echo "Error: Docker is not installed. Please install Docker and try again."
    exit 1
fi

# Check for Docker Compose
if docker compose version >/dev/null 2>&1; then
    echo "Docker Compose plugin ('docker compose') is installed."
    DOCKER_COMPOSE_COMMAND="docker compose"
elif command_exists docker-compose; then
    echo "Standalone Docker Compose ('docker-compose') is installed."
    DOCKER_COMPOSE_COMMAND="docker-compose"
else
    echo "Error: Neither 'docker compose' nor 'docker-compose' is installed. Please install Docker Compose and try again."
    exit 1
fi

echo "Docker and Docker Compose are installed."

ROOT_DIR="$HOME/.dsql"

if [ ! -d "$ROOT_DIR" ]; then
    echo "Creating root directory: $ROOT_DIR"
    mkdir -p "$ROOT_DIR"
fi

# Function to generate a random string of a given length
generate_random_string() {
    length=$1
    tr -dc A-Za-z0-9 </dev/urandom | head -c "$length"
}

DEPLOYMENT_NAME_DEFAULT="dsql_$(generate_random_string 8)"

echo "What do you want to name this deployment? (default: $DEPLOYMENT_NAME_DEFAULT). Enter an existing deployment name to update:"
read ENTERED_DEPLOYMENT_NAME

if [ -z "$ENTERED_DEPLOYMENT_NAME" ]; then
    DEPLOYMENT_NAME=$DEPLOYMENT_NAME_DEFAULT
else
    DEPLOYMENT_NAME=$ENTERED_DEPLOYMENT_NAME
fi

ADMIN_DIR="$ROOT_DIR/$DEPLOYMENT_NAME"

if [ ! -d "$ADMIN_DIR" ]; then
    echo "Creating new deployment directory: $ADMIN_DIR"

    mkdir -p $ADMIN_DIR
    cd $ADMIN_DIR

    git clone https://git.tben.me/Moduletrace/dsql-admin.git .

    cd $ADMIN_DIR/dsql-app

    # Set Admin HOST
    echo "Optional: Enter the Admin HOST (default: http://localhost:7070):"
    read HOST_INPUT

    HOST=${HOST_INPUT:-http://localhost:7070}

    # Set Static HOST
    echo "Optional: Enter the Stacic host (default: http://localhost:7072):"
    read STATIC_HOST_INPUT

    STATIC_HOST=${STATIC_HOST_INPUT:-http://localhost:7072}

    # Set Super User Info
    echo "Enter Super User First Name:"
    read SUPER_USER_FIRST_NAME
    echo "Enter Super User Last Name:"
    read SUPER_USER_LAST_NAME
    echo "Enter Super User Email:"
    read SUPER_USER_EMAIL
    echo "Enter Super User Password:"
    read SUPER_USER_PASSWORD
    echo "Enter Super User Username:"
    read SUPER_USER_USERNAME

    echo "What is the IP address of this admin instance? (default: 172.72.0.24):"
    read ADMIN_SERVER_IP
    echo "Do you have an external database you want to use? If so provide the server IP address (default: 172.72.0.24):"
    read DATABASE_SERVER_HOST
    echo "External Database root user password (required if external database IP is set):"
    read DATABASE_SERVER_ROOT_PASSWORD

    echo "What local PORT would you like the admin server to run on? (default: 7070):"
    read ADMIN_PORT_INPUT
    echo "What local PORT would you like the static server to run on? (default: 7072):"
    read STATIC_PORT_INPUT

    DEFAULT_DATABASE_ROOT_PASSWORD=$(generate_random_string 48)
    DEFAULT_SU_PASS=$(generate_random_string 22)

    cat >.env <<EOF
# Environment Variables
DSQL_HOST=$HOST
NEXT_PUBLIC_DSQL_HOST=$HOST
DSQL_STATIC_HOST=$STATIC_HOST
NEXT_PUBLIC_DSQL_STATIC_HOST=$STATIC_HOST
DSQL_SOCKET_DOMAIN=$HOST
DSQL_HOST_ENV=prod_prod
NEXT_PUBLIC_DSQL_HOST_ENV=prod_prod
DSQL_PORT=${ADMIN_PORT_INPUT:-7070}
DSQL_PRODUCTION_PORT=${ADMIN_PORT_INPUT:-7070}
DSQL_STATIC_SERVER_PORT=${STATIC_PORT_INPUT:-7072}
DSQL_STATIC_SERVER_DIR=/static
DSQL_SITE_URL=
NEXT_PUBLIC_DSQL_REMOTE_SQL_HOST=${ADMIN_SERVER_IP:-172.72.0.24}
DSQL_DB_TARGET_IP_ADDRESS=${ADMIN_SERVER_IP:-172.72.0.24}
NEXT_PUBLIC_DSQL_LOCAL=true
DSQL_USER_DB_PREFIX=datasquirel_user_
DSQL_USER_DELEGATED_DB_COOKIE_PREFIX=datasquirelDelegatedUserDbToken_
DSQL_NETWORK_GATEWAY=172.72.0.1
DSQL_DB_HOST=${DATABASE_SERVER_HOST:-172.72.0.24}
DSQL_DB_USERNAME=root
DSQL_DB_PASSWORD=${DATABASE_SERVER_ROOT_PASSWORD:-$DEFAULT_DATABASE_ROOT_PASSWORD}
DSQL_MARIADB_ROOT_PASSWORD=$(generate_random_string 48)
DSQL_DB_NAME=datasquirel
DSQL_DB_READ_ONLY_USERNAME=read_only
DSQL_DB_READ_ONLY_PASSWORD=$(generate_random_string 48)
DSQL_DB_FULL_ACCESS_USERNAME=datasquirel_full_access
DSQL_DB_FULL_ACCESS_PASSWORD=$(generate_random_string 48)
DSQL_DB_EXPOSED_PORT=3317

DSQL_ENCRYPTION_PASSWORD=$(generate_random_string 64)
DSQL_ENCRYPTION_SALT=$(generate_random_string 48)

DSQL_SU_EMAIL=${SUPER_USER_EMAIL:-user@dsql.com}
DSQL_USER_KEY=$(generate_random_string 48)
DSQL_SPECIAL_KEY=$(generate_random_string 48)

DSQL_GOOGLE_API_KEY=
NEXT_PUBLIC_DSQL_GOOGLE_CLIENT_ID=
DSQL_GOOGLE_CLIENT_ID=
DSQL_GOOGLE_CLIENT_SECRET=
DSQL_GMAIL_PASSWORD=

NEXT_PUBLIC_DSQL_FACEBOOK_APP_ID=
DSQL_FACEBOOK_SECRET=

DSQL_MAIL_HOST=
DSQL_MAIL_EMAIL=
DSQL_MAIL_PASSWORD=

NEXT_PUBLIC_DSQL_TINY_MCE_API_KEY=

DSQL_GITHUB_ID=
NEXT_PUBLIC_DSQL_GITHUB_ID=
DSQL_GITHUB_SECRET=

DSQL_GITHUB_WEBHOOK_SECRET=
DSQL_GITHUB_WEBHOOK_URL=

DSQL_DEPLOY_SERVER_PORT=3092

DSQL_DOCKERFILE=Dockerfile

DSQL_VOLUME_APP=
DSQL_VOLUME_STATIC=
DSQL_VOLUME_STATIC_CONFIGURATION_FILE=
DSQL_VOLUME_DB=
DSQL_VOLUME_DB_CONFIG=
DSQL_VOLUME_DB_SETUP=
DSQL_VOLUME_DB_SSL=

DSQL_USER_LOGIN_KEYS_PATH=/app/apiKeys/allowed-logins
DSQL_API_KEYS_PATH=/app/apiKeys/allowed-signatures
DSQL_USER_DB_SCHEMA_PATH=/app/jsonData/dbSchemas/users

DSQL_LOCAL_SU_FIRST_NAME=${SUPER_USER_FIRST_NAME:-dsql}
DSQL_LOCAL_SU_LAST_NAME=${SUPER_USER_LAST_NAME:-user}
DSQL_LOCAL_SU_EMAIL=${SUPER_USER_EMAIL:-user@dsql.com}
DSQL_LOCAL_SU_USERNAME=${SUPER_USER_USERNAME:-dsql_su}
DSQL_LOCAL_SU_PASSWORD=${SUPER_USER_PASSWORD:-$DEFAULT_SU_PASS}

DSQL_CONTACT_EMAIL=${SUPER_USER_EMAIL:-user@dsql.com}
DSQL_SSL_DIR=/ssl

DSQL_DEPLOYMENT_NAME=${DEPLOYMENT_NAME}
DSQL_COOKIES_PREFIX=${DEPLOYMENT_NAME}_
DSQL_COOKIES_KEY_NAME=key
DSQL_COOKIES_CSRF_NAME=csrf

DSQL_SESSION_EXPIRY_TIME=36000000

EOF
else
    cd $ADMIN_DIR/dsql-app
    $DOCKER_COMPOSE_COMMAND down
    cd $ADMIN_DIR
    git pull
fi

ENV_FILE="$ADMIN_DIR/dsql-app/.env"

if [ -f "$ENV_FILE" ]; then
    . "$ENV_FILE"
    echo ".env file loaded successfully."
    cd $ADMIN_DIR/dsql-app
    $DOCKER_COMPOSE_COMMAND up -d --build
    echo "All Done! Navigate to http://localhost:${DSQL_PORT} to get started."
else
    echo "Error: .env file not found at $ENV_FILE"
    exit 1
fi
