#!/bin/bash -e

# Set the repository URL
repo_url=git@github.com:lorenzdonau/tasko.git

# Set the default branch
branch=feature/php8

# Check if the folder location was given
if [ $# -eq 0 ]; then
  # Show an error message if no arguments were passed
  echo "Error: Missing folder path to deploy." >&2
  exit 1
fi

set -e

# Clone the repository if it doesn't exist locally
if [ ! -d "tasko" ]; then
  git clone $repo_url --bare tasko
fi

# Change into the repository directory
cd tasko

# Fetch only once a minute
last_check_file="../last_git_check.txt"
current_timestamp=$(date +%s)

if [ ! -f "$last_check_file" ]; then
  echo "$current_timestamp" > "$last_check_file"
  echo "First time fetching for git"
  git fetch origin $branch:$branch
else
  last_check_timestamp=$(cat "$last_check_file")
  time_diff=$((current_timestamp - last_check_timestamp))

  if [ "$time_diff" -lt 60 ]; then # Change this value if you want to wait less than 60 seconds
    echo "Less than 1 minute has passed since the last check."
    echo "Skipping the check."
  else
      echo "More than 1 minute has passed since the last check."
      echo "Updating git"
      git fetch origin $branch:$branch
  fi
fi

# Create a release folder
releases_folder_path="/var/www/$1/releases"
folder_name=$(date +"%Y%m%d%H%M%S")
new_release_folder_path=$releases_folder_path/$folder_name
mkdir -p $new_release_folder_path

# Create a release to a target folder
echo "git archive $branch | /usr/bin/env tar -x -f - -C $new_release_folder_path"
git archive $branch | /usr/bin/env tar -x -f - -C $new_release_folder_path

## Create folders for shared
# list of dirs to link and create
linked_dirs=(
    storage/app/public/htmlpic
    storage/app/public/icons
    storage/app/app
    storage/app/backup
    storage/app/reports
    storage/framework/views
    storage/framework/sessions
    storage/framework/cache
    storage/reports/free
    public/api/diff
    public/api/result
    storage/app
    storage/module
    storage/debugbar
    storage/logs
    storage/reports
)

shared_folder_path="/var/www/$1/shared"
absolute_path_link_dirs=()
shared_path_directory_to_link=()

for dir in ${linked_dirs[@]}; do
  absolute_path=$new_release_folder_path/$dir
  absolute_path_link_dirs+=($absolute_path)

  shared_path=$shared_folder_path/$dir
  shared_path_directory_to_link+=($shared_path)
done
shared_directory_paths=$(printf " %s" ${absolute_path_link_dirs[@]})
shared2_directory_paths=$(printf " %s" ${shared_path_directory_to_link[@]})
# Create dirs to link to shared folder
echo "SHARED_DIRECTORY_PATHS: $shared_directory_paths"

echo "mkdir -p $shared_directory_paths"
echo "mkdir -p $shared2_directory_paths"
mkdir -p $shared_directory_paths
mkdir -p $shared2_directory_paths

# Create link between shared folder to deployed app paths
length_of_shared_dir=${#linked_dirs[@]}
for ((i=0; i<length_of_shared_dir; i++)); do
  target_folder=${linked_dirs[$i]}
  shared_path=$shared_folder_path/$target_folder
  app_path=$new_release_folder_path/$target_folder
  # Remove path from app if it exists before linking
  if [ -d $app_path ]; then
    echo "rm -rf $app_path"
    rm -rf "$app_path"
  fi
  # Link deployed app path with shared dir path
  echo "ln -s $shared_path $app_path"
  ln -s $shared_path $app_path
done

# Run composer command to install the app
cd $new_release_folder_path

# TODO: SWITCH BACK TO USING COMPOSER FOR PHP VERSION 8 DEPLOY.
composer install --no-dev --quiet --prefer-dist --optimize-autoloader
# php composer.phar self-update
# php composer.phar global update
# php composer.phar install --no-dev --quiet --prefer-dist --optimize-autoloader

echo "DONE Installation"
# Update permission
## TODO: it is not nessary to run thesse command just make sure script is ran with a user included in www-data group
# chmod -R ug+rwx /var/www/ibad.mytasko.de/shared/storage/ /var/www/ibad.mytasko.de/shared/public/api/ /var/www/ibad.mytasko.de/releases/20230107002536/bootstrap/cache/
# chgrp -R www-data /var/www/ibad.mytasko.de/shared/storage/ /var/www/ibad.mytasko.de/shared/public/api/ /var/www/ibad.mytasko.de/releases/20230107002536/bootstrap/cache/

# Check if .env file does not exist in the parent directory
if [ ! -f /var/www/$1/.env ]; then
    echo "Create .env file"
    touch /var/www/$1/.env
    app_key=$(php artisan key:generate --show)

    # Create .env file in the parent directory
    cat > /var/www/$1/.env <<EOF
    APP_NAME=
    APP_ENV=prod
    APP_KEY=$app_key
    APP_DEBUG=false
    APP_URL=

    DB_CONNECTION=mysql
    DB_HOST=
    DB_PORT=
    DB_DATABASE=
    DB_USERNAME=
    DB_PASSWORD=

    BROADCAST_DRIVER=log
    CACHE_DRIVER=file
    QUEUE_CONNECTION=sync
    SESSION_DRIVER=file
    SESSION_LIFETIME=120

    REDIS_HOST=127.0.0.1
    REDIS_PASSWORD=null
    REDIS_PORT=6379

    MAIL_MAILER=smtp
    MAIL_HOST=mailhog
    MAIL_PORT=1025
    MAIL_USERNAME=null
    MAIL_PASSWORD=null
    MAIL_ENCRYPTION=null
    MAIL_FROM_ADDRESS=null
    MAIL_FROM_NAME=""
EOF

    cp /var/www/$1/.env $new_release_folder_path
    echo "Created .env file in the parent directory"
else
    echo ".env file already exists in the parent directory."
    # Copy laravel .env file
    original_env_file="/var/www/$1/.env"
    app_env_file=$new_release_folder_path/.env
    cp $original_env_file $app_env_file
fi


# Run migration
# TODO: enable migration for actual release script
# php artisan migrate --force

# Deploy the app by linking
release_target="/var/www/$1/current"
echo "ln -sfT $new_release_folder_path $release_target"
ln -sfT $new_release_folder_path $release_target

# REMOVE OLDER STALLATIONS

# Number of folders to keep
num_folders_to_keep=10

cd $releases_folder_path
mapfile -t folders < <(find . -maxdepth 1 -type d -name '[0-9]*' | sort -n -r)
num_folders=${#folders[@]}
if (( num_folders > num_folders_to_keep )); then
  for (( i=num_folders_to_keep; i<num_folders; i++ )); do
    rm -rf "${folders[i]}"
    echo "Deleted folder: ${folders[i]}"
  done
fi

chown -R www-data:www-data /var/www/$1