#!/bin/bash
# set -e

# ───── Configuration du marqueur ─────
MARKER_DIR="/etc/setup-markers"
MARKER="$MARKER_DIR/setup_env_configured"
FORCE=false

# ───── Gestion des arguments ─────
for arg in "$@"; do
  case "$arg" in
    --force)
      FORCE=true
      echo "⚠️  Force mode enabled — setup will re-run even if marker exists."
      ;;
    --help|-h)
      echo "Usage: $0 [--force]"
      echo "  --force   Re-run full setup even if already configured"
      exit 0
      ;;
    *)
      echo "❌ Unknown option: $arg"
      echo "Run with --help for usage."
      exit 1
      ;;
  esac
done

# ───── Skip si déjà configuré ─────
if [ -f "$MARKER" ] && [ "$FORCE" != true ]; then
  echo "✅ Setup already completed — skipping."
  echo "👉 Run with --force to force reconfiguration."
  exit 0
fi

id dbi>/dev/null 2>&1 || read -p "dbi password please: " DBI_PWD
tailscale ip>/dev/null 2>&1 || read -p "Tailscale API Key: " TAIL_MY_API_KEY
docker ps>/dev/null 2>&1 || read -p "Install docker (y/n)? " INST_DOCKER
read -p "Install mergerfs (y/N)? " INST_MERGERFS
read -p "Install vmtools (y/N)? " INST_VMTOOLS

[[ -z "$INST_DOCKER" ]] && INST_DOCKER=n
[[ -z "$INST_MERGERFS" ]] && INST_MERGERFS=n
[[ -z "$INST_VMTOOLS" ]] && INST_VMTOOLS=n

LOG_DIR=/var/log/my_scripts
SCRIPTS_DIR=/opt/scripts_local
MYUSER=dbi
MYUSER_ID=2222
MYHOME_DIR=/home/"$MYUSER"
SSH_DIR="$MYHOME_DIR/.ssh"

apt update
apt upgrade -y
apt install sudo -y

download_template() {
  local MY_TEMPLATE=$1
  local DST_PATH=$2
  HOSTNAME=$(hostname)
  echo "Now downloading template $MY_TEMPLATE ..."  
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" dbi@ket.inxs.me:"$MY_TEMPLATE" "$DST_PATH"
}

install_package() {
  local MY_PACKAGE=$1
  shift
  local MY_PACKAGE_FULLPATH="/myshares/scripts/setup/$MY_PACKAGE"
  local DST_PATH="/tmp/$MY_PACKAGE"
  
  echo "Downloading package $MY_PACKAGE..."
  sudo rsync -avP -e "ssh -o StrictHostKeyChecking=no" dbi@ket.inxs.me:"$MY_PACKAGE_FULLPATH" "$DST_PATH"
  sudo chmod +x "$DST_PATH"
  
  echo "Installing package $MY_PACKAGE..."
  bash "$DST_PATH" "$@"
}

type -p curl >/dev/null || (sudo apt update && sudo apt install curl -y)
rsync >/dev/null 2>&1 || (sudo apt install rsync -y)

sudo groupadd -g 2223 sysadmin
sudo groupadd -g 3333 fs_data

if ! ( id -u dbi ); then 
  echo "Creating user dbi ..."
  sudo useradd -m -p $(openssl passwd -1 "$DBI_PWD") -u "$MYUSER_ID" -s /bin/bash -d "$MYHOME_DIR" -G sudo,sysadmin,fs_data "$MYUSER"
else
  sudo usermod -aG sudo,sysadmin,fs_data "$MYUSER"
fi

sudo usermod -aG sysadmin root
sudo chown root:sysadmin /opt/
sudo chmod g+w /opt
sudo chmod a+x /opt
sudo mkdir -p "$SCRIPTS_DIR" && \
sudo chown root:sysadmin -R "$SCRIPTS_DIR" && \
sudo chmod 771 -R "$SCRIPTS_DIR"
sudo mkdir -p "$LOG_DIR" && \
sudo chown root:sysadmin -R "$LOG_DIR" && \
sudo chmod 771 -R "$LOG_DIR"

# SSH
if ! [ -f "$SSH_DIR"/id_rsa ] || ! [ -f "$SSH_DIR"/id_ed25519 ]; then
  mkdir -p "$SSH_DIR"
  echo "No id_rsa key file found, generating a new one ..."
  ssh-keygen -b 4096 -t rsa -f "$SSH_DIR/id_rsa" -C "$USER@$HOSTNAME" -q -N ""
  ssh-keygen -t ed25519 -f "$SSH_DIR/id_ed25519" -C "$USER@$HOSTNAME" -q -N ""
else
  echo "id_rsa key detected, skipping ssh key creation ..."  
fi

echo "Applying ssh security on .ssh dir and adding public keys."
touch "$SSH_DIR/authorized_keys" "$SSH_DIR/known_hosts"
sudo chmod 700 -R "$SSH_DIR"
sudo chmod 644 -f "$SSH_DIR/*.pub" "$SSH_DIR/authorized_keys" "$SSH_DIR/known_hosts"
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIG5Tjx2S5EKYANdrhZNucwuiI9by6FF3Lv0F7K+s2fM/ dbi@mbp" >> "$SSH_DIR/authorized_keys"

# TAILSCALE
if ! ( type -p tailscale >/dev/null ); then
  echo "Tailscale not detected, installing ..."
  MY_NETMASK="192.168.10.0/24"
  sudo ip rule add to "$MY_NETMASK" priority 2500 lookup main
  sudo touch /etc/cron.d/tailscale_lan_access
  echo "@reboot root sleep 10 && ip rule update to $MY_NETMASK priority 2500 lookup main" | sudo tee /etc/cron.d/tailscale_lan_access
  sudo chmod 600 /etc/cron.d/tailscale_lan_access
  # $TAIL_MY_API_KEY needs to have a : at the end in order to specify that no pwd is provided
  MY_AUTH_KEY=$(curl -u "$TAIL_MY_API_KEY:" https://api.tailscale.com/api/v2/tailnet/sukkeler@gmail.com/keys   --data-binary '
  {
    "capabilities": {
      "devices": {
        "create": {
          "reusable": false,
          "ephemeral": false,
          "preauthorized": true
        }
      }
    },
    "expirySeconds": 86400,
    "description": "dev access"
  }' | grep -o '"key":"[^"]*' | grep -o '[^"]*$')
  TAIL_AUTH="--authkey=$MY_AUTH_KEY"
  curl -fsSL https://tailscale.com/install.sh | sudo sh
  sudo tailscale up
else
  echo "Tailscale already installed skipping."
fi

# Enable access to lan when tailscale routes are enabled

sudo tailscale set \
--ssh \
--accept-dns \
--operator=dbi \
--auto-update

if ( sudo which tailscale >/dev/null ); then
  echo "Tailscale detected. Applying ufw settings."
  sudo which ufw >/dev/null || sudo apt install ufw &&
  sudo ufw allow in on tailscale0 &&
  sudo ufw allow 41641/udp &&
  sudo ufw --force enable &&
  sudo ufw default deny incoming &&
  sudo ufw default allow outgoing
else
  echo "Tailscale not detected. Skipping."
  exit 1
fi

echo "Applying ssh security policy."
download_template /myshares/shared/etc/ssh/sshd_config.d/gataca.conf /etc/ssh/sshd_config.d/gataca.conf
sudo systemctl restart sshd

echo "Downloading shared_functions locally."
download_template /myshares/scripts/shared_functions.sh /opt/scripts_local/
source /opt/scripts_local/shared_functions.sh

sleep 3 

bash /opt/scripts_remote/setup/install_caddy.sh
install_package install_locale_tz.sh
install_package install_cronicle.sh
[[ "$INST_VMTOOLS" == "y" ]]  && install_package install_vmtools.sh
install_package install_github_config.sh
install_package install_linux_tools.sh
install_package install_lnav.sh
install_package install_files_folders.sh 
install_package install_iterm_config.sh
install_package install_misc_config.sh
# install_package install_msmtp.sh
install_package install_pbs.sh
install_package install_netdata.sh
install_package install_pipx.sh
install_package install_time_client.sh
[[ "$INST_DOCKER" == "y" ]]  && install_package install_docker.sh
[[ "$INST_MERGERFS" == "y" ]]  && install_package install_mergerfs.sh

echo "✅ Setup completed successfully. Creating marker."
sudo mkdir -p "$MARKER_DIR"
sudo touch "$MARKER"