#!/bin/bash

WP_CLI=~/.composer/vendor/bin/wp-cli

if [ ! -f "$WP_CLI" ]; then
  echo "Error: WP-CLI is not installed. Please install it and try again."
  exit 1
fi

# Prompt for Git URL
read -p "Please enter a valid Git URL: " GIT_URL

# Check if the user provided a Git URL
if [ -z "$GIT_URL" ]; then
  echo "Error: No Git URL provided. Exiting."
  exit 1
fi

# Remove the .git folder
echo "Removing existing .git folder..."
rm -rf .git

# Initialize a new git repository
echo "Initializing new git repository..."
git init
git add .
git commit -m "initial commit"
git remote add origin "$GIT_URL"
git push -u origin master

# Initialize gitflow
echo "Initializing gitflow..."
git flow init -d  # Using default values

# Push all branches
echo "Pushing all branches..."
git push --all

# Copy .env.example to .env
echo "Copying .env.example to .env..."
cp .env.example .env

# Parse the .env.example file and prompt for variable values
echo "Please enter values for the following environment variables (press Enter to use default):"

# Read each line in the .env file
while IFS= read -r line; do
  # Skip empty lines and comments
  if [[ -z "$line" || "$line" == \#* ]]; then
    continue
  fi

  # Extract variable name and default value
  var_name=$(echo "$line" | cut -d '=' -f 1)
  default_value=$(echo "$line" | cut -d '=' -f 2-)

  # Prompt user for input
  read -p "$var_name (default: $default_value): " user_value

  # Use default value if no input is provided
  if [ -z "$user_value" ]; then
    user_value="$default_value"
  fi

  # Write the variable to the .env file
  echo "$var_name=$user_value" >> .env
done < .env.example

# this will fail for now!

# Start Docker
echo "Starting Docker..."
$WP_CLI up

# Run install
echo "Running WordPress install..."
$WP_CLI install

# Run yarn install
echo "Running yarn install..."
$WP_CLI yarn install

# Run composer install
echo "Running composer install..."
$WP_CLI composer install

# Run development server
echo "Running development server..."
$WP_CLI dev

# Remove this README file
echo "Removing README.md..."
rm README.md

# Remove this README file
echo "Removing installer.sh..."
rm installer.sh

# Git Stuff
git branch --set-upstream-to=origin/develop develop
git add .
git commit -m "cleanup"
git push --all

echo "Installation completed successfully!"
