#!/usr/bin/env bash
set +x
set -Eeuo pipefail
umask 077
[[ $EUID -eq 0 ]] || { echo 'Run with sudo.';exit 1; }
[[ ! -f /etc/isp-platform/hub.env ]] || exit 1
. /etc/os-release
[[ $ID:$VERSION_ID == ubuntu:26.04 && $(uname -m) == x86_64 ]] || { echo 'Netcore supports Ubuntu 26.04 x86-64 only.';exit 1; }
[[ ! -f /opt/isp-core/INSTALLER-MANAGED || -f /opt/isp-core/NETCORE ]] || { echo 'Existing legacy Core detected. Use its installer; Netcore migration is a separate operation.'; exit 1; }
install -d -m0700 /var/lib/isp-core
printf '0.1.65\n' > /var/lib/isp-core/NETCORE-REQUESTED
# Snapshots can restore a stale system clock; use the VM hardware clock first.
python3 - <<'CLOCK'
import time
from pathlib import Path
try:
 rtc=int(Path('/sys/class/rtc/rtc0/since_epoch').read_text())
 if rtc>time.time()+300 and rtc<4102444800:time.clock_settime(time.CLOCK_REALTIME,rtc)
except (OSError,ValueError):pass
CLOCK
timedatectl set-ntp true
export DEBIAN_FRONTEND=noninteractive
printf 'Preparing secure Hub connection...\n'
apt-get -o DPkg::Lock::Timeout=300 -o Acquire::ForceIPv4=true -o Acquire::Retries=2 update -qq > /var/log/netmarga-protected-bootstrap.log 2>&1
apt-get -o DPkg::Lock::Timeout=300 -o Acquire::ForceIPv4=true -o Acquire::Retries=2 install -y -qq --no-install-recommends python3 curl ca-certificates openssl wireguard-tools openssh-server sudo >> /var/log/netmarga-protected-bootstrap.log 2>&1
cat > /var/lib/isp-core/protected-release.pub <<'PUBLIC_KEY'
-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA/lvxr6cBYT95XwfQRRPA
AsqeniqxzFSSZs1IoHhufNKfcDh2Z5UVfcVKfzJzvySTaxvTZG2LKDJzWKJ06l5M
PzvLqCOhE8U0OQGqTjBU7Uv0ROwlM5jrdbmJ4t4748PnlTMWnd6CVR+Fgx4U3Z4/
8/bwV6jUfUDVAQtM/QVP54EIWFa9h9IxpiLOwnd9P8pg/uUtIPxiD7jPqv9ASbHe
3a/B6eGlwTzf7V9UhlA9R/p1BTyb5YYuvS8vndFBvpxST+KeqjQRVFbJojFG7XCU
N7WPLblSmLELJd0BgVCs0WhlKpbcsvuWfRwR44Qu8yRu26fdpPY50cgX/NBbrSGC
X3rm/6UZfk5DJhXzK4pX4FUF7bYNJArIqIjYsLgxVlp8upmkPkY3mnMTF+lN5NTV
tOzYZNa6sg/kOBd1XBLi1avWXrmTUEF6lGobgTymNni67qJ9/+2A9CPmpuJlyroI
QxxjkM4STB4EIwMlyTOPmgNyDP/x0tmLn5hBlr5tqVcHAgMBAAE=
-----END PUBLIC KEY-----
PUBLIC_KEY
chmod 0644 /var/lib/isp-core/protected-release.pub
cat > /var/lib/isp-core/protected-verify.py <<'VERIFY'
import json,hashlib,urllib.request,subprocess,os
from pathlib import Path
ROOT=Path('/var/lib/isp-core/protected-release');ROOT.mkdir(mode=0o700,parents=True,exist_ok=True)
URL='https://hub.netmarga.com/netcore/releases/0.1.65/'
def fetch(name):
 data=urllib.request.urlopen(URL+name,timeout=60).read(64*1024*1024)
 (ROOT/name).write_bytes(data);return data
manifest=fetch('manifest.json');fetch('manifest.sig')
subprocess.run(['openssl','dgst','-sha256','-verify','/var/lib/isp-core/protected-release.pub','-signature',str(ROOT/'manifest.sig'),str(ROOT/'manifest.json')],check=True,capture_output=True)
d=json.loads(manifest)
assert d['version']=='0.1.65' and d['product']=='netcore' and d['platform']=='ubuntu26-amd64-python314'
for name,digest in d['files'].items():
 if os.getenv('NETMARGA_BOOTSTRAP_ONLY')=='1' and name!='core_vpn_bootstrap.py':continue
 if '/' in name or name.startswith('.'):raise ValueError('Invalid package filename')
 data=fetch(name)
 if hashlib.sha256(data).hexdigest()!=digest:raise ValueError('Package checksum failed: '+name)
VERIFY
NETMARGA_BOOTSTRAP_ONLY=1 python3 /var/lib/isp-core/protected-verify.py
id isp-core >/dev/null 2>&1 || useradd --system --user-group --home-dir /var/lib/isp-core --shell /usr/sbin/nologin isp-core
chown isp-core:isp-core /var/lib/isp-core
NETMARGA_COMPANY="${NETMARGA_COMPANY:-Pending web setup}" NETMARGA_CONTACT="${NETMARGA_CONTACT:-Administrator}" NETMARGA_EMAIL="${NETMARGA_EMAIL:-setup@netmarga.com}" python3 /var/lib/isp-core/protected-release/core_vpn_bootstrap.py
python3 - <<'QUEUE'
import json,time,urllib.request
from pathlib import Path
c=json.loads(Path('/var/lib/isp-core/credentials.json').read_text());url='https://hub.netmarga.com/api/v1/netcore/'
headers={'Authorization':'Bearer '+c['token'],'Content-Type':'application/json'}
request=urllib.request.Request(url+'queue',data=b'{}',headers=headers)
urllib.request.urlopen(request,timeout=30).read()
import subprocess
address=subprocess.check_output(['hostname','-I'],text=True).split()[0]
previous=''
for i in range(360):
 r=json.load(urllib.request.urlopen(urllib.request.Request(url+'status',headers=headers),timeout=30))
 if r['state']!=previous:print(r.get('message',r['state']),flush=True);previous=r['state']
 if r['state']=='completed':
  password_path=Path('/var/lib/isp-core/initial-admin-password')
  print('\nNetcore installation completed. Username: admin',flush=True)
  if Path('/var/lib/isp-core/first-login.json').exists() and password_path.exists():
   print('Temporary admin password: '+password_path.read_text().strip(),flush=True)
   print('Open https://'+address+':8443/ and sign in. You must choose a new password before continuing.',flush=True)
  else:print('Open https://'+address+':8443/ and sign in with your existing password.',flush=True)
  break
 if r['state']=='failed':raise SystemExit('Hub installation failed; existing access is preserved where possible.')
 time.sleep(5)
else:raise SystemExit('Installation is still pending; check Hub status before rerunning.')
QUEUE
