#!/bin/bash

# Script to create a basic iOS SwiftUI Xcode project from template

PROJECT_NAME=$1
BASE_DIR="/Users/mattbruce/Documents/Projects/iPhone/OpenClaw"
TARGET_DIR="${BASE_DIR}/${PROJECT_NAME}"
TEMPLATE_DIR="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Templates/Project Templates/iOS/Application/iOS SwiftUI App.xctemplate"
ORGANIZATION_ID="com.mattbruce"
YEAR=$(date +%Y)
COPYRIGHT="Copyright © ${YEAR} Matt Bruce. All rights reserved."

if [ -z "$PROJECT_NAME" ]; then
  echo "Usage: $0 <project_name>"
  exit 1
fi

if [ -d "$TARGET_DIR" ]; then
  echo "Target directory $TARGET_DIR already exists. Skipping."
  exit 1
fi

# Copy template
cp -R "$TEMPLATE_DIR" "$TARGET_DIR"

cd "$TARGET_DIR"

# Replace placeholders
find . -type f \( -name "*.swift" -o -name "*.plist" -o -name "project.pbxproj" -o -name "*.strings" \) -exec sed -i '' \
  -e "s/___PROJECTNAME___/${PROJECT_NAME}/g" \
  -e "s/___PROJECTNAMEASIDENTIFIER___/${ORGANIZATION_ID}.$(echo ${PROJECT_NAME} | tr '[:upper:]' '[:lower:]')/g" \
  -e "s/___ORGANIZATIONNAME___/Matt Bruce/g" \
  -e "s/___YEAR___/${YEAR}/g" \
  -e "s/___COPYRIGHT___/${COPYRIGHT}/g" \
  {} +

# For project.pbxproj, also update bundle ID, etc.
sed -i '' "s/com.example.apple-samplecode.*/${ORGANIZATION_ID}.$(echo ${PROJECT_NAME} | tr '[:upper:]' '[:lower:]')/g" "${PROJECT_NAME}.xcodeproj/project.pbxproj"

# Set deployment target to iOS 17.0 (edit pbxproj)
sed -i '' 's/IPHONEOS_DEPLOYMENT_TARGET = 15.0;/IPHONEOS_DEPLOYMENT_TARGET = 17.0;/g' "${PROJECT_NAME}.xcodeproj/project.pbxproj"

echo "Created Xcode project at $TARGET_DIR"
echo "To open: open \"$TARGET_DIR/${PROJECT_NAME}.xcodeproj\""
