#!/bin/bash

# Initialize variables
commit_message=""
action=""
folder_to_sync=""
external_base_dir="../external-nise.moe"

# Manual argument parsing
while [ "$#" -gt 0 ]; do
  case "$1" in
    sync|create|configure|push)
      action="$1"
      folder_to_sync="$2"
      shift 2
      ;;
    -m)
      commit_message="$2"
      shift 2
      ;;
    *)
      echo "Invalid argument: $1"
      exit 1
      ;;
  esac
done

# Validation
if [ -z "$action" ]; then
  echo "Error: Please provide an action (sync or create)."
  exit 1
fi

if [ -z "$folder_to_sync" ]; then
  echo "Error: Please provide a folder name."
  exit 1
fi

target_folder="$external_base_dir/$folder_to_sync"

# Further validation and action handling
if [ "$action" == "sync" ]; then
  if [ ! -d "$folder_to_sync" ]; then
    echo "Error: Folder '$folder_to_sync' does not exist in the monorepo."
    exit 1
  fi

  mkdir -p "$target_folder"
  echo "Synchronizing files from '$folder_to_sync' to '$target_folder'..."
  rsync -av --delete --exclude-from='.gitignore' --exclude='.git' "$folder_to_sync/" "$target_folder/"

  cd "$target_folder" || { echo "Error: Failed to change directory to $target_folder"; exit 1; }

  git add .
  if [ -z "$commit_message" ]; then
    commit_message=$(date +%Y%m%d)
  fi
  git commit -S -am "$commit_message"

  echo "Synchronization complete and changes committed with message: '$commit_message'."
elif [ "$action" == "configure" ]; then
  echo "Configuring external folder '$target_folder'..."
  cd "$target_folder" || { echo "Error: Failed to change directory to $target_folder"; exit 1; }

  git config user.email "162507023+nise-moe@users.noreply.github.com"
  git config user.name "nise.moe"
  git config gpg.format ssh
  git config commit.gpgsign true
  git config user.signingkey /home/anon/.ssh/nise-moe.pub
elif [ "$action" == "push" ]; then
  echo "Pushing changes to remote repository..."
  cd "$target_folder" || { echo "Error: Failed to change directory to $target_folder"; exit 1; }

  git push origin main
  echo "Changes pushed to remote repository."
elif [ "$action" == "create" ]; then
  mkdir -p "$target_folder"

  cd "$target_folder" || { echo "Error: Failed to change directory to $target_folder"; exit 1; }

  git init
  git config user.email "162507023+nise-moe@users.noreply.github.com"
  git config user.name "nise.moe"
  git config gpg.format ssh
  git config commit.gpgsign true
  git config user.signingkey /home/anon/.ssh/nise-moe.pub
  git branch -M main
  git remote add origin git@github.com:nise-moe/"$folder_to_sync".git

  echo "External folder '$target_folder' created and initialized as a Git repository."
else
  echo "Error: Invalid action '$action'."
  exit 1
fi