#!/bin/sh
set -e

BASE="https://get.cloud2hide.com/dl"
case "$(uname -s)" in
  Linux) os=linux ;;
  Darwin) os=darwin ;;
  *) echo "unsupported OS: $(uname -s)" >&2; exit 1 ;;
esac
case "$(uname -m)" in
  x86_64|amd64) arch=amd64 ;;
  aarch64|arm64) arch=arm64 ;;
  *) echo "unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

fetch() {
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$2" "$1"
  else
    echo "install curl or wget first" >&2
    exit 1
  fi
}

fetch "$BASE/c2h-$os-$arch" "$tmp/c2h"
fetch "$BASE/c2h-tracker-$os-$arch" "$tmp/c2h-tracker" || true
chmod +x "$tmp/c2h"
[ -f "$tmp/c2h-tracker" ] && chmod +x "$tmp/c2h-tracker"

if [ "$(id -u)" = "0" ]; then
  dest="/usr/local/bin"
  install -m 0755 "$tmp/c2h" "$dest/c2h"
  [ -f "$tmp/c2h-tracker" ] && install -m 0755 "$tmp/c2h-tracker" "$dest/c2h-tracker"
  if command -v setcap >/dev/null 2>&1; then
    setcap cap_net_admin+ep "$dest/c2h" 2>/dev/null || true
  fi
  if [ -d /etc/tmpfiles.d ]; then
    echo "z /dev/net/tun 0666 - - -" > /etc/tmpfiles.d/c2h.conf
    if command -v systemd-tmpfiles >/dev/null 2>&1; then
      systemd-tmpfiles --create /etc/tmpfiles.d/c2h.conf 2>/dev/null || true
    fi
  fi
  if [ -d /usr/share/applications ]; then
    curl -fsSL "https://get.cloud2hide.com/desktop" -o /usr/share/applications/c2h.desktop 2>/dev/null || true
  fi
  if command -v firewall-cmd >/dev/null 2>&1; then
    firewall-cmd --permanent --zone=trusted --add-interface=c2h0 2>/dev/null || true
    firewall-cmd --zone=trusted --add-interface=c2h0 2>/dev/null || true
    firewall-cmd --reload 2>/dev/null || true
  fi
else
  dest="$HOME/.local/bin"
  mkdir -p "$dest"
  install -m 0755 "$tmp/c2h" "$dest/c2h"
  [ -f "$tmp/c2h-tracker" ] && install -m 0755 "$tmp/c2h-tracker" "$dest/c2h-tracker"
  if command -v sudo >/dev/null 2>&1; then
    echo "note: the tunnel needs elevated privileges — reinstall with: sudo curl -fsSL https://get.cloud2hide.com | sh"
    echo "      or run: sudo c2h run --config \"$dest/../.config/c2h/config.json\""
  else
    echo "note: the tunnel needs elevated privileges — switch to root (su -) and install:"
    echo "      curl -fsSL https://get.cloud2hide.com | sh"
  fi
fi

echo "c2h installed to $dest/c2h"
case ":$PATH:" in
  *":$dest:"*) ;;
  *) echo "add $dest to your PATH, then run: c2h connect --token <token>" ;;
esac
"$dest/c2h" version
