remove boxid from cfg file name

This commit is contained in:
2025-04-08 14:50:50 +02:00
parent f28b1bcabd
commit 0b3dacfb32
27 changed files with 189 additions and 52 deletions

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:5a:58:e4
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=192.168.1.1/24 eth0=192.168.1.1/24

View File

@ -1,3 +1,7 @@
[BOX]
type=dual-eth-rpi
MAC=d8:3a:dd:51:2b:81
[NETWORK] [NETWORK]
eth0=wan eth0=wan
eth1=192.168.99.5 eth1=192.168.99.5

View File

@ -1,3 +1,7 @@
[BOX]
type=dual-eth-rpi
MAC=d8:3a:dd:51:2a:e6
[NETWORK] [NETWORK]
eth0=wan eth0=wan
eth1=192.168.99.7 eth1=192.168.99.7

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:60:f0:e8
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=192.168.127.254 eth0=192.168.127.254

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:5a:4c:90
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=wan eth0=wan

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:5f:ba:48
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=wan eth0=wan

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:5f:a5:cc
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=wan,192.168.1.0/24 eth0=wan,192.168.1.0/24

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:5f:b6:88
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=wan,192.168.1.0/24 eth0=wan,192.168.1.0/24

View File

@ -1,3 +1,7 @@
[BOX]
type=control-box
MAC=00:0d:b9:5b:2a:64
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=dhcp eth0=dhcp

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:59:1f:ac
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=dhcp eth0=dhcp

View File

@ -1,3 +1,7 @@
[BOX]
type=control-box
MAC=00:0d:b9:5b:26:5c
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=dhcp eth0=dhcp

View File

@ -1,3 +1,7 @@
[BOX]
type=ionopi
MAC=e4:5f:01:ca:0e:2b
; please refer to README.md for help ; please refer to README.md for help
[BOX] [BOX]

4
cfg/linse-rpi2.cfg Normal file
View File

@ -0,0 +1,4 @@
[BOX]
type=ionopimax
MAC=b8:27:eb:41:3f:b2

4
cfg/linse-rpi4.cfg Normal file
View File

@ -0,0 +1,4 @@
[BOX]
type=ionopimax
MAC=b8:27:eb:8a:09:27

4
cfg/linse-rpi5.cfg Normal file
View File

@ -0,0 +1,4 @@
[BOX]
type=ionopimax
MAC=b8:27:eb:ce:a5:ec

View File

@ -1,3 +1,7 @@
[BOX]
type=dual-eth-rpi
MAC=d8:3a:dd:51:2c:7d
[NETWORK] [NETWORK]
eth0=wan eth0=wan
eth1=192.168.127.2 eth1=192.168.127.2

4
cfg/linse-rpi9.cfg Normal file
View File

@ -0,0 +1,4 @@
[BOX]
type=ionopimax
MAC=b8:27:eb:ca:0e:a3

View File

@ -1,3 +1,7 @@
[BOX]
type=bare-apu
MAC=00:0d:b9:59:20:a8
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=192.168.127.2/24 eth0=192.168.127.2/24

View File

@ -1,3 +1,7 @@
[BOX]
type=control-box
MAC=00:0d:b9:5b:25:1c
[NETWORK] [NETWORK]
; please refer to README.md for help ; please refer to README.md for help
eth0=dhcp eth0=dhcp

View File

@ -81,14 +81,15 @@ def change_to_gitea(doit, *repos):
if write_when_new(doit, '.git/hooks/pre-commit', PRE_COMMIT_HOOK): if write_when_new(doit, '.git/hooks/pre-commit', PRE_COMMIT_HOOK):
dirty = True dirty = True
helper_script = parser.get('credential', 'helper', fallback=None) helper_script = parser.get('credential', 'helper', fallback=None)
if helper_script != str('.git/hooks/get_gitea_token'): new_helper = f'{os.getcwd()}/.git/hooks/get_gitea_token'
if helper_script != new_helper:
dirty = True dirty = True
if doit: if doit:
os.system(f'git config credential.helper "{os.getcwd()}/.git/hooks/get_gitea_token"') os.system(f'git config credential.helper "{new_helper}"')
elif helper_script: elif helper_script:
print('need to change gitea credential helper') print('need to change gitea credential helper')
else: else:
print('missing gitea credential helper', e) print('missing gitea credential helper')
url = parser.get('remote "origin"', 'url', fallback=None) url = parser.get('remote "origin"', 'url', fallback=None)
if url != GITEA_URL % repo: if url != GITEA_URL % repo:
dirty = True dirty = True

View File

@ -35,7 +35,7 @@ except ImportError:
serial = None serial = None
try: try:
from utils import BoxInfo, check_service, unix_cmd, change_firewall, UndefinedConfigFile from utils import BoxInfo, check_service, unix_cmd, change_firewall, UndefinedConfigFile, convert_cfg
except ImportError: except ImportError:
if 'yes'.startswith(input('install netifaces? [y]')): if 'yes'.startswith(input('install netifaces? [y]')):
os.system('sudo pip3 install --break-system-packages netifaces') os.system('sudo pip3 install --break-system-packages netifaces')
@ -47,7 +47,7 @@ if serial is None:
TOOLS = BoxInfo.TOOLS TOOLS = BoxInfo.TOOLS
BOX_TYPES = {'ionopi', 'ionopimax', 'controlbox', 'bare-apu', 'dual-eth-rpi'} BOX_TYPES = {'ionopi', 'ionopimax', 'control-box', 'bare-apu', 'dual-eth-rpi'}
more_info = False more_info = False
@ -60,7 +60,8 @@ TEMPLATES = {}
TEMPLATES['bare-apu'] = f"""{COMMENT} TEMPLATES['bare-apu'] = f"""{COMMENT}
[BOX] [BOX]
type=bare-apu type=%s
MAC=%s
[NETWORK] [NETWORK]
eth0=wan eth0=wan
@ -72,10 +73,11 @@ eth3=192.168.127.254
3001=192.168.127.254:3001 3001=192.168.127.254:3001
""" """
TEMPLATES['controlbox'] = f"""{COMMENT} TEMPLATES['control-box'] = f"""{COMMENT}
[BOX] [BOX]
type=controlbox type=%s
MAC=%s
[NETWORK] [NETWORK]
eth0=wan eth0=wan
@ -92,7 +94,8 @@ line2=ADDR
TEMPLATES['dual-eth-rpi'] = f"""{COMMENT} TEMPLATES['dual-eth-rpi'] = f"""{COMMENT}
[BOX] [BOX]
type=dual-eth-rpi type=%s
MAC=%s
[NETWORK] [NETWORK]
eth0=wan eth0=wan
@ -103,6 +106,7 @@ GENERIC_TEMPLATE = f"""{COMMENT}
[BOX] [BOX]
type=%s type=%s
MAC=%s
[NETWORK] [NETWORK]
eth0=wan eth0=wan
@ -211,7 +215,7 @@ def router(firewall=False, **opts):
def display_update(cfg): def display_update(cfg):
text = '\n'.join(cfg.get('startup_text', '').split('|')[:3]) text = '\n'.join(cfg.get('startup_text', '').split('|')[:3])
text = text.replace('HOST', box.hostname) \ text = text.replace('HOST', box.hostname) \
.replace('ADDR', box.get_macaddr()) + '\n' .replace('ADDR', box.macaddr) + '\n'
if write_when_new(STARTUP_TEXT, text): if write_when_new(STARTUP_TEXT, text):
print('change startup text') print('change startup text')
if doit: if doit:
@ -482,7 +486,12 @@ def handle_config():
try: try:
config = box.read_config() config = box.read_config()
except UndefinedConfigFile as e: except UndefinedConfigFile as e:
print(e) print(f'{box.cfgfile} not found', e)
if box.oldcfg:
print(f'convert {box.cfgfile} to {convert_cfg(box.cfgfile, box.macaddr)}')
config = box.read_config()
cfgfile = box.cfgfile cfgfile = box.cfgfile
newhostname = box.hostname newhostname = box.hostname
if cfgfile: if cfgfile:
@ -507,7 +516,7 @@ def handle_config():
disp.write(b'\x1b\x1b\x01\xf3') disp.write(b'\x1b\x1b\x01\xf3')
display_available = disp.read(8)[0:4] == b'\x1b\x1b\x05\xf3' display_available = disp.read(8)[0:4] == b'\x1b\x1b\x05\xf3'
if display_available: if display_available:
box.typ = 'controlbox' box.typ = 'control=box'
else: else:
box.typ = 'bare-apu' box.typ = 'bare-apu'
elif box.typ == 'cm4': elif box.typ == 'cm4':
@ -519,23 +528,25 @@ def handle_config():
template = TEMPLATES.get(box.typ) template = TEMPLATES.get(box.typ)
if template is None: if template is None:
box.typ = box.typ or 'unknown-box' box.typ = box.typ or 'unknown-box'
template = GENERIC_TEMPLATE % box.typ template = GENERIC_TEMPLATE
template = template % (box.typ, box.macaddr)
print('no cfg file found for this', box.typ, print('no cfg file found for this', box.typ,
f'with id {box.id:06x} (hostname={box.hostname})') f'with mac address {box.macaddr} (hostname={box.hostname})')
newhostname = input('enter host name: ') newhostname = input('enter host name: ')
if not newhostname: if not newhostname:
print('no hostname given') print('no hostname given')
return False return False
cfgfile = BoxInfo.CFGPATH % (newhostname, box.id) cfgfile = BoxInfo.CFGDIR / f'{newhostname}.cfg'
with open(cfgfile, 'w') as f: with open(cfgfile, 'w') as f:
f.write(template) f.write(template)
config = box.read_config() config = box.read_config()
cfgfile = box.cfgfile cfgfile = box.cfgfile
if box.hostname_changed or cfgfile != BoxInfo.CFGPATH % (newhostname, box.id): if box.hostname_changed or box.hostname != newhostname:
print('changed', box.hostname, newhostname)
box.hostname_changed = True box.hostname_changed = True
if cfgfile: if cfgfile:
newhostname = basename(cfgfile).rpartition('_')[0] newhostname = cfgfile.stem.rpartition('_')[0]
if doit: if doit:
print('bash sethostname.sh') print('bash sethostname.sh')
unix_cmd('bash', f'{TOOLS}/sethostname.sh') unix_cmd('bash', f'{TOOLS}/sethostname.sh')
@ -552,12 +563,10 @@ def handle_config():
try: try:
netcfg = config['NETWORK'] netcfg = config['NETWORK']
for name in netcfg: for name in netcfg:
if name not in box.macaddr: if name not in box.network_interfaces:
print(name)
print(box.macaddr)
print(f'{name} is not a valid network interface name') print(f'{name} is not a valid network interface name')
raise RuntimeError('network interface name system does not match') raise RuntimeError('network interface name system does not match')
for ifname in box.macaddr: for ifname in box.network_interfaces:
content = create_if(ifname, netcfg.get(ifname, 'off')) content = create_if(ifname, netcfg.get(ifname, 'off'))
# content = '\n'.join('%s=%s' % kv for kv in content.items()) # content = '\n'.join('%s=%s' % kv for kv in content.items())
todo = write_when_new(f'/etc/network/interfaces.d/{ifname}', content, as_root=True) todo = write_when_new(f'/etc/network/interfaces.d/{ifname}', content, as_root=True)
@ -586,7 +595,8 @@ def handle_config():
show.dirty = True show.dirty = True
try: try:
replace_in_file('/etc/default/isc-dhcp-server', replace_in_file('/etc/default/isc-dhcp-server',
r'INTERFACESv4="(.*)"', ' '.join([n for n in box.macaddr if n != box.main_if])) r'INTERFACESv4="(.*)"', ' '.join(
[n for n in box.network_interfaces if n != box.main_if]))
except FileNotFoundError: except FileNotFoundError:
if 'yes'.startswith(input('install isc-dhcp-server? [y]')): if 'yes'.startswith(input('install isc-dhcp-server? [y]')):
unix_cmd('apt-get install isc-dhcp-server') unix_cmd('apt-get install isc-dhcp-server')

View File

@ -1,15 +1,12 @@
ETHNAME=$(cat /sys/class/net/eth0/address) ETHNAME=$(cat /sys/class/net/eth0/address)
ETHNAME=${ETHNAME//:/} FOUND=($(grep -l -r MAC=$ETHNAME /home/l_samenv/boxtools/cfg))
BOXID=${ETHNAME: -6}
FOUND="$(shopt -s nullglob; echo /home/l_samenv/boxtools/cfg/*_$BOXID.cfg)"
if [ -z "$FOUND" ]; then if [ -z "$FOUND" ]; then
BOXID=${ETHNAME//:/}
BOXID=${BOXID: -6}
HOSTNAME=box$BOXID HOSTNAME=box$BOXID
else else
FOUND=$(basename ${FOUND[0]}) # remove directory part FOUND=$(basename ${FOUND[0]}) # remove directory part
HOSTNAME=${FOUND%%.*} # remove extension HOSTNAME=${FOUND%%.cfg} # remove extension
if [ $HOSTNAME != "box$BOXID" ]; then
HOSTNAME=${HOSTNAME%_*}
fi
echo "hostname $HOSTNAME" echo "hostname $HOSTNAME"
fi fi
echo $HOSTNAME > /etc/hostname echo $HOSTNAME > /etc/hostname

View File

@ -24,9 +24,48 @@ class UndefinedConfigFile(Exception):
"""config file not found or ambiguous""" """config file not found or ambiguous"""
def convert_cfg(file, macaddr=None):
hostname, boxid = file.stem.split('_')
if macaddr is None:
macaddr = f'--:--:--:{boxid[0:2]}:{boxid[2:4]}:{boxid[4:6]}'
box = BoxInfo(macaddr, True)
config = box.read_config()
network = config.get('NETWORK', {})
if len(network) > 2:
mac1 = '00:0d:b9'
if config.get('DISPLAY'):
typ = 'control-box'
else:
typ = 'bare-apu'
elif len(network) == 2:
mac1 = 'd8:3a:dd'
typ = 'dual-eth-rpi'
else:
if config.get('BOX', {}).get('type') == 'ionopi':
mac1 = 'e4:5f:01'
typ = 'ionopi'
else:
mac1 = 'b8:27:eb'
typ = 'ionopimax'
macaddr = macaddr.replace('--:--:--', mac1)
with open(file) as f:
content = f.read()
newfile = file.parent / f'{hostname}.cfg'
with open(newfile, 'w') as f:
f.write(f'[BOX]\ntype={typ}\nMAC={macaddr}\n\n{content}')
if not file.name.endswith('_'):
file.rename(file.parent / (file.name + '_'))
return newfile
def convert_all():
for file in Path('cfg').glob('*_*.cfg*'):
convert_cfg(file)
class BoxInfo: class BoxInfo:
TOOLS = Path('/home/l_samenv/boxtools') TOOLS = Path('/home/l_samenv/boxtools')
CFGPATH = str(TOOLS / 'cfg' / '%s_%06x.cfg') CFGDIR = TOOLS / 'cfg'
BOX_TYPES = { BOX_TYPES = {
'00:0d:b9': 'apu', # bare apu or control box '00:0d:b9': 'apu', # bare apu or control box
'b8:27:eb': 'cm3', # guess iono pi max 'b8:27:eb': 'cm3', # guess iono pi max
@ -34,15 +73,19 @@ class BoxInfo:
'd8:3a:dd': 'cm4', # guess dual-eth-rpi 'd8:3a:dd': 'cm4', # guess dual-eth-rpi
} }
def __init__(self): def __init__(self, macaddr=None, relcfg=None):
if relcfg:
self.CFGDIR = Path('cfg')
self.id = None self.id = None
self.typ = None self.typ = None
self.hostname = socket.gethostname() self.hostname = socket.gethostname()
self.change_if_names = False self.change_if_names = False
self.cfgfile = None self.cfgfile = None
self.config = None self.config = None
self.macaddr = {} self.network_interfaces = {}
self.main_if = None self.main_if = None
self.oldcfg = False
if macaddr is None:
for ifdev in sorted(glob('/sys/class/net/*/address')): for ifdev in sorted(glob('/sys/class/net/*/address')):
ifname = ifdev.split('/')[-2] ifname = ifdev.split('/')[-2]
if ifname == 'lo': # do not consider loopback interface if ifname == 'lo': # do not consider loopback interface
@ -51,22 +94,32 @@ class BoxInfo:
self.change_if_names = True self.change_if_names = True
ifname = f'eth{int(ifname[3]) - 1}' ifname = f'eth{int(ifname[3]) - 1}'
with open(ifdev) as f: with open(ifdev) as f:
self.macaddr[ifname] = addr = f.read().strip().lower() self.network_interfaces[ifname] = addr = f.read().strip().lower()
if ifname in ('eth0', 'enp1s0'): if ifname in ('eth0', 'enp1s0'):
self.id = int(''.join(addr.split(':')[-3:]), 16) & 0xffffff print('my mac address', addr)
self.typ = self.BOX_TYPES.get(addr[:8]) macaddr = addr
self.main_if = ifname self.main_if = ifname
self.macaddr = macaddr
if macaddr:
self.id = int(''.join(macaddr.split(':')[-3:]), 16) & 0xffffff
self.typ = self.BOX_TYPES.get(macaddr[:8])
self.hwtype = self.typ # this is one of the values in BOX_TYPE and will not change self.hwtype = self.typ # this is one of the values in BOX_TYPE and will not change
def get_macaddr(self):
return self.macaddr.get(self.main_if)
def read_config(self, section=None): def read_config(self, section=None):
cfgfiles = glob(self.CFGPATH % ('*', self.id)) cfgfiles = []
for file in self.CFGDIR.glob('*.cfg'):
with open(file) as f:
for line in f:
if line.startswith(f'MAC={self.macaddr}'):
cfgfiles.append(file)
break
if not cfgfiles:
cfgfiles = list(self.CFGDIR.glob(f'*_{self.id:06x}.cfg*'))
self.oldcfg = True
if len(cfgfiles) > 1: if len(cfgfiles) > 1:
raise AmbiguousConfigFile('ambiguous cfgfile: %r' % cfgfiles) raise AmbiguousConfigFile('ambiguous cfgfile: %r' % cfgfiles)
if section and not cfgfiles: if section and not cfgfiles:
raise UndefinedConfigFile('no cfg file found for %s' % self.id) raise UndefinedConfigFile('no cfg file found for %s' % self.macaddr)
if cfgfiles: if cfgfiles:
self.cfgfile = cfgfiles[0] self.cfgfile = cfgfiles[0]
else: else: