#!/usr/bin/env bash
# install_provider_key.sh
# Purpose: Install or remove a provider's SSH public key into ~/.ssh/authorized_keys with clear steps and safety.

set -euo pipefail

# ============= CONFIGURE HERE =============
# Replace the key below with your actual provider public key (single line).
PROVIDER_KEY='ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCx+sQUOgCH01p2GXeaz83ZRiNzzX43+Mepc+D9+X3tQs0a52o0P3TU5AGwfqTlDpah/6+z+qXpRPefGOWQGDd/Zq2tdGqbBWYg5bOUqu7/y6a+2lU7ezwwaOfIi/O12lDVuyaB2LgYzw4VVnFa8Bwz6utWtBtWPgCXYfSiF2PhGFlMk/h7og7urypH7qT6xaUuV6dYCwPddy+HRsVKBGeRB12++bvoBNVjo28emSg8GINJhDeOTZ3RRm9xBDi7As4VMkfsjCF8xPWZFK3nBS+stQtWdsCipCZdHoklOeF5fYFrVVPHfJEPfLogjJrkZfQoBEaXDWNf+ZL8Kw/DScdcPTBGX+yXENh66+MJc3V0Mu+OPkGuezCMex/ubFeTiaxnEo4qtlDsT/Ca0JZTvPGM3BQlHUww820J8fvForohnVNl/PkGAV7Nm1//NdRaLwQCY3VrKwNx0q8hebULVapu5J1t1WS2UxoEynt+Fu69L+PLZoP9VrEYJCy34HbKXVk= root@asuka-vm'
PROVIDER_TAG='provider-support-key'   # used to mark the key line for idempotency and removal
# =========================================

usage() {
  cat <<'EOF'
Usage:
  provider_key.sh [install|remove]

Commands:
  install  - Add provider public key to ~/.ssh/authorized_keys (idempotent)
  remove   - Remove provider public key from ~/.ssh/authorized_keys

Notes:
  - Run as the target user (do not use sudo to run as root unless you intend to install for root).
  - The script creates ~/.ssh if missing and enforces secure permissions.
  - A timestamped backup of authorized_keys is created before changes.
EOF
}

prompt_confirm() {
  local prompt="${1:-Proceed? [y/N]} "
  read -r -p "$prompt" reply
  case "$reply" in
    [yY][eE][sS]|[yY]) return 0 ;;
    *) return 1 ;;
  esac
}

ensure_ssh_dir() {
  echo "Step 1: Ensuring ~/.ssh directory exists and permissions are correct..."
  mkdir -p "${HOME}/.ssh"
  chmod 700 "${HOME}/.ssh"
  echo "  - ~/.ssh is ready."
}

backup_authorized_keys() {
  local ak="${HOME}/.ssh/authorized_keys"
  if [[ -f "$ak" ]]; then
    local ts
    ts="$(date +'%Y%m%d-%H%M%S')"
    local backup="${HOME}/.ssh/authorized_keys.backup.${ts}"
    cp -p "$ak" "$backup"
    echo "  - Backup created: $backup"
  else
    echo "  - No existing authorized_keys; nothing to back up."
  fi
}


ensure_authorized_keys_file() {
  local ak="${HOME}/.ssh/authorized_keys"
  if [[ ! -f "$ak" ]]; then
    echo "Step 2: Creating authorized_keys file..."
    touch "$ak"
    chmod 600 "$ak"
    echo "  - authorized_keys created."
  else
    echo "Step 2: authorized_keys already exists."
  fi
}

add_provider_key() {
  local ak="${HOME}/.ssh/authorized_keys"
  echo "Step 3: Checking if provider key is already installed..."
  if grep -Fq "$PROVIDER_TAG" "$ak"; then
    echo "  - Provider key already present; no duplicate added."
  else
    echo "Step 4: Backing up existing authorized_keys before changes..."
    backup_authorized_keys
    echo "Step 5: Appending provider key..."
    # Write a clearly tagged line so removal is easy
    printf "%s %s\n" "$PROVIDER_KEY" "#${PROVIDER_TAG}" >> "$ak"
    echo "  - Provider key appended."
  fi

  echo "Step 6: Enforcing secure permissions..."
  chmod 600 "$ak"
  echo "  - Permissions set to 600 on authorized_keys."
}

remove_provider_key() {
  local ak="${HOME}/.ssh/authorized_keys"
  if [[ ! -f "$ak" ]]; then
    echo "No authorized_keys file found; nothing to remove."
    return 0
  fi

  echo "Step R1: Backing up authorized_keys before removal..."
  backup_authorized_keys

  echo "Step R2: Removing provider key..."
  # Remove any line containing our tag
  local tmp="${ak}.tmp.$$"
  grep -Fv "#${PROVIDER_TAG}" "$ak" > "$tmp" || true
  mv "$tmp" "$ak"

  echo "Step R3: Enforcing secure permissions..."
  chmod 600 "$ak"
  echo "  - Provider key removed and permissions enforced."
}

main() {
  local cmd="${1:-}"
  case "$cmd" in
    install)
      echo "This script will install the provider's SSH public key into your account."
      echo "Actions:"
      echo "  1) Create ~/.ssh (if missing) and set safe permissions"
      echo "  2) Create or use ~/.ssh/authorized_keys"
      echo "  3) Backup your existing authorized_keys (if present)"
      echo "  4) Append the provider's key (idempotent; no duplicates)"
      echo "  5) Enforce secure permissions (600) on authorized_keys"
      if ! prompt_confirm "Proceed with installation? [y/N] "; then
        echo "Aborted by user."
        exit 1
      fi
      ensure_ssh_dir
      ensure_authorized_keys_file
      add_provider_key
      echo "Done: Provider key is installed."
      ;;
    remove)
      echo "This will remove the provider's SSH public key from your account."
      echo "Actions:"
      echo "  1) Backup your existing authorized_keys"
      echo "  2) Remove the provider key line"
      echo "  3) Enforce secure permissions (600)"
      if ! prompt_confirm "Proceed with removal? [y/N] "; then
        echo "Aborted by user."
        exit 1
      fi
      remove_provider_key
      echo "Done: Provider key has been removed."
      ;;
    *)
      usage
      exit 1
      ;;
  esac
}

main "$@"

