#!/bin/bash

# Usage: autologin_cookies.sh [MODE] [--exc_comb] [SITE_LIST...]
#   MODE: deployment mode (e.g., 'demo_vwebarena', 'demo_webarena', etc.)
#   --exc_comb: optional flag to exclude combinations of sites
#   SITE_LIST: optional list of sites to pass to the Python script,
#              which will be used to login only for the specified sites.

# Define the auth directory
AUTH_DIR="./.auth"

# Extend PYTHONPATH as needed
PYTHONPATH=$PYTHONPATH:.

# Add the directory from which the script is called to PYTHONPATH
PYTHONPATH=$PYTHONPATH:$(dirname "$0")

# Default value for exc_comb
EXC_COMB=""

# If MODE argument is provided, source the environment variables
if [ -n "$1" ] && [[ "$1" != "--exc_comb" ]] && [[ "$1" != -* ]]; then
  MODE=$1
  source ./scripts/environments/set_env_variables.sh "$MODE"
  shift
fi

# Check for --exc_comb flag
if [[ "$1" == "--exc_comb" ]]; then
  EXC_COMB="--exc_comb"
  shift
fi

# Create the folder if it doesn't already exist.
mkdir -p "$AUTH_DIR"

# Enable nullglob so that non-matching globs expand to nothing
shopt -s nullglob

if [ "$#" -gt 0 ]; then
  # If a site list is provided, loop through each site and delete matching files
  for site in "$@"; do
    rm -f "$AUTH_DIR"/*"$site"*
  done
else
  # If no site_list is provided, delete all files in the .auth directory
  rm -f "$AUTH_DIR"/*
fi

# If additional arguments are provided, assume they are for site_list and pass them to the Python script
if [ "$#" -gt 0 ]; then
    python -m browser_env.auto_login $EXC_COMB --site_list "$@"
else
    python -m browser_env.auto_login $EXC_COMB
fi

