#! /bin/bash
set -e

echo "Enter your server username (ex: root)"
read username
echo "Enter server host (ex: 11.111.111.11)"
read ip_address

echo "########### Connecting to server... ###########"
echo "User: ${username}"
echo "Host: ${ip_address}"

# Prepare server
ssh -o StrictHostKeyChecking=no -l "${username}" "${ip_address}" "
  # Kill any stuck dpkg/apt process
  if pgrep -x apt >/dev/null || pgrep -x dpkg >/dev/null; then
      echo '⚠️ Killing existing apt/dpkg process...'
      sudo killall -9 apt apt-get dpkg || true
  fi

  sudo mkdir -p /var/www/investra && \
  sudo chown -R ${username}:${username} /var/www/investra && \
  sudo dpkg --configure -a && \
  sudo apt-get update -y && \
  sudo apt-get install -y zip unzip
"

# Check local files
if [ -f "./core/admin.zip" ] && [ -f "./deployment.zip" ]; then

    echo "Uploading deployment.zip..."
    scp "./deployment.zip" "${username}@${ip_address}:/var/www/investra"
    ssh -o StrictHostKeyChecking=no -l "${username}" "${ip_address}" \
    "rm -rf /var/www/investra/deployment && unzip /var/www/investra/deployment.zip -d /var/www/investra/deployment"

    echo "Uploading admin.zip..."
    scp "./core/admin.zip" "${username}@${ip_address}:/var/www/investra"
    ssh -o StrictHostKeyChecking=no -l "${username}" "${ip_address}" \
    "rm -rf /var/www/investra/admin && unzip /var/www/investra/admin.zip -d /var/www/investra/admin"
else
  echo "❌ Missing admin.zip, or deployment.zip in ./core or project root"
  exit 1
fi

echo "Checking zx installation..."
if ! command -v zx &> /dev/null; then
    npm i -g zx
fi

echo "✅ Congrats! Deployment script and API files uploaded to the server."
