tiancheng91 / collection

笔记
https://github.com/tiancheng91/collection/issues
22 stars 1 forks source link

斐讯n1 ubuntu #34

Open tiancheng91 opened 5 years ago

tiancheng91 commented 5 years ago
wget https://mirrors.tuna.tsinghua.edu.cn/ubuntu-cdimage/ubuntu-base/releases/19.10/beta/ubuntu-base-19.10-beta-base-arm64.tar.gz
tar -zxf ubuntu-base-19.10-beta-base-arm64.tar.gz
rm ubuntu-base-19.10-beta-base-arm64.tar.gz

# wget https://github.com/150balbes/Amlogic_s905/raw/master/script/s9xxx_mainline/v02/aml_autoscript.txt -O boot/aml_autoscript.txt
wget https://github.com/150balbes/Amlogic_s905/raw/master/script/s9xxx_mainline/v02/emmc_autoscript.txt -O boot/emmc_autoscript.txt
wget https://github.com/150balbes/Amlogic_s905/raw/master/script/s9xxx_mainline/v02/s905_autoscript.txt -O boot/s905_autoscript.txt
wget https://github.com/150balbes/Build-Armbian/raw/master/packages/bsp/aml-s905/install.sh -O root/install.sh
wget https://github.com/150balbes/Build-Armbian/raw/master/packages/bsp/aml-s905/fstab -O root/fstab

chroot ./
echo "nameserver 114.114.114.114" > /etc/resolv.conf
sed -i "s/ports.ubuntu.com/mirrors.aliyun.com/g" /etc/apt/sources.list
apt update
apt install linux-image-5.3.0-18-generic linux-firmware linux-modules-5.3.0-18-generic initramfs-tools u-boot-tools wget --no-install-recommends
# rm  /etc/initramfs/post-update.d/flash-kernel
apt clean

wget https://raw.githubusercontent.com/RPi-Distro/firmware-nonfree/master/brcm/brcmfmac43455-sdio.txt /lib/firmware/brcmfmac43455-sdio.txt
wget https://github.com/RPi-Distro/bluez-firmware/raw/master/broadcom/BCM4345C0.hcd root/BCM4345C0.hcd /lib/firmware/brcm/BCM4345C0.hcd

echo "root:root" | chpasswd

mkdir -p /etc/systemd/network
echo "[Match]
Name=eth0

[Network]
DHCP=ipv4" > /etc/systemd/network/10-eth0.network

cp /lib/firmware/5.3.0-18-generic/device-tree/amlogic/meson-gxl-s905d-phicomm-n1.dtb /boot/n1.dtb

echo "dtb_name=/n1.dtb
bootargs=root=LABEL=ROOTFS rootflags=data=writeback rw console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0
" > /boot/uEnv.ini

# mkimage -A arm -O linux -T script -C none -d aml_autoscript.txt aml_autoscript  # recovery模式
mkimage -A arm -O linux -T script -C none -d emmc_autoscript.txt emmc_autoscript
mkimage -A arm -O linux -T script -C none -d s905_autoscript.txt s905_autoscript

mkimage -A arm -O linux -T ramdisk -C none -a 0 -e 0 -n uInitrd -d /boot/initrd.img-5.3.0-18-generic /boot/uInitrd
cp vmlinuz-5.3.0-18-generic zImage
rm -rf /boot/*.old
tiancheng91 commented 5 years ago

https://github.com/150balbes/Build-Armbian/tree/master/packages/bsp/aml-s905

tiancheng91 commented 5 years ago

echo '/dev/mmcblk1 0x27400000 0x10000' > /etc/fw_env.config fw_printenv

tiancheng91 commented 5 years ago

u-boot-default.img.zip

tiancheng91 commented 5 years ago

https://github.com/yangxuan8282/gen-rpi_os

tiancheng91 commented 5 years ago
EnableSelinux=enforcing
active_slot=_a
aml_dt=gxl_p230_2g
baudrate=115200
bcb_cmd=get_valid_slot;
boot_part=boot
bootcmd=run start_autoscript; run storeboot;
bootdelay=1
cmdline_keys=if keyman init 0x1234; then if keyman read usid ${loadaddr} str; then setenv bootargs ${bootargs} androidboot.serialno=${usid};setenv serial ${usid};fi;if keyman read mac ${loadaddr} str; then setenv bootargs ${bootargs} mac=${mac} androidboot.mac=${mac};fi;if keyman read deviceid ${loadaddr} str; then setenv bootargs ${bootargs} androidboot.deviceid=${deviceid};fi;if keyman read mac_wifi ${loadaddr} str; then setenv bootargs ${bootargs} mac_wifi=${mac_wifi} androidboot.mac_wifi=${mac_wifi};fi;fi;
cvbs_drv=0
cvbsmode=576cvbs
display_bpp=16
display_color_bg=0
display_color_fg=0xffff
display_color_index=16
display_height=1080
display_layer=osd1
display_width=1920
dtb_mem_addr=0x1000000
ethaddr=00:15:18:01:81:31
factory_reset_poweroff_protect=echo wipe_data=${wipe_data}; echo wipe_cache=${wipe_cache};if test ${wipe_data} = failed; then run init_display; run storeargs;if mmcinfo; then run recovery_from_sdcard;fi;if usb start 0; then run recovery_from_udisk;fi;run recovery_from_flash;fi; if test ${wipe_cache} = failed; then run init_display; run storeargs;if mmcinfo; then run recovery_from_sdcard;fi;if usb start 0; then run recovery_from_udisk;fi;run recovery_from_flash;fi;
factorystep=2

fb_addr=0x3d800000
fb_height=1080
fb_width=1920
fdt_high=0x20000000
firstboot=0
gatewayip=10.18.9.1
hdmimode=1080p60hz
hostname=arm_gxbb
init_display=osd open;osd clear;imgread pic logo bootup $loadaddr;bmp display $bootup_offset;bmp scale
initargs=rootfstype=ramfs init=/init console=ttyS0,115200 no_console_suspend earlyprintk=aml-uart,0xc81004c0 ramoops.pstore_en=1 ramoops.record_size=0x8000 ramoops.console_size=0x4000
ipaddr=10.18.9.97
jtag=apao
kernellog.enable=0
loadaddr=1080000
netmask=255.255.255.0
outputmode=1080p60hz
preboot=run bcb_cmd; run factory_reset_poweroff_protect;run upgrade_check;run init_display;run storeargs;run upgrade_key;forceupdate;run switch_bootmode;
recovery_from_flash=setenv bootargs ${bootargs} aml_dt=${aml_dt} recovery_part={recovery_part} recovery_offset={recovery_offset};if itest ${upgrade_step} == 3; then if ext4load mmc 1:2 ${dtb_mem_addr} /recovery/dtb.img; then echo cache dtb.img loaded; fi;if ext4load mmc 1:2 ${loadaddr} /recovery/recovery.img; then echo cache recovery.img loaded; wipeisb; bootm ${loadaddr}; fi;else fi;if imgread kernel ${recovery_part} ${loadaddr} ${recovery_offset}; then wipeisb; bootm ${loadaddr}; fi;
recovery_from_sdcard=setenv bootargs ${bootargs} aml_dt=${aml_dt} recovery_part={recovery_part} recovery_offset={recovery_offset};if fatload mmc 0 ${loadaddr} aml_autoscript; then autoscr ${loadaddr}; fi;if fatload mmc 0 ${loadaddr} recovery.img; then if fatload mmc 0 ${dtb_mem_addr} dtb.img; then echo sd dtb.img loaded; fi;wipeisb; bootm ${loadaddr};fi;
recovery_from_udisk=setenv bootargs ${bootargs} aml_dt=${aml_dt} recovery_part={recovery_part} recovery_offset={recovery_offset};if fatload usb 0 ${loadaddr} aml_autoscript; then autoscr ${loadaddr}; fi;if fatload usb 0 ${loadaddr} recovery.img; then if fatload usb 0 ${dtb_mem_addr} dtb.img; then echo udisk dtb.img loaded; fi;wipeisb; bootm ${loadaddr};fi;
recovery_offset=0
recovery_part=recovery
sdc_burning=sdc_burn ${sdcburncfg}
sdcburncfg=aml_sdc_burn.ini
serverip=10.18.9.113
start_autoscript=if usb start ; then run start_usb_autoscript; fi; if mmcinfo; then run start_mmc_autoscript; fi; run start_emmc_autoscript;
start_emmc_autoscript=if fatload mmc 1 1020000 emmc_autoscript; then autoscr 1020000; fi;
start_mmc_autoscript=if fatload mmc 0 1020000 s905_autoscript; then autoscr 1020000; fi;
start_usb_autoscript=if fatload usb 0 1020000 s905_autoscript; then autoscr 1020000; fi; if fatload usb 1 1020000 s905_autoscript; then autoscr 1020000; fi; if fatload usb 2 1020000 s905_autoscript; then autoscr 1020000; fi; if fatload usb 3 1020000 s905_autoscript; then autoscr 1020000; fi;
storeargs=setenv bootargs ${initargs} androidboot.selinux=${EnableSelinux} logo=${display_layer},loaded,${fb_addr},${outputmode} maxcpus=${maxcpus} vout=${outputmode},enable hdmimode=${hdmimode} cvbsmode=${cvbsmode} hdmitx=${cecconfig} cvbsdrv=${cvbs_drv}  pq=${pq} androidboot.firstboot=${firstboot} androidboot.factorystep=${factorystep} jtag=${jtag}; setenv bootargs ${bootargs} androidboot.hardware=amlogic;run cmdline_keys;setenv bootargs ${bootargs} androidboot.slot_suffix=${active_slot};if itest ${kernellog.enable} == 0; then setenv bootargs ${bootargs} quiet;else fi;
storeboot=if imgread kernel ${boot_part} ${loadaddr}; then bootm ${loadaddr}; fi;run update;
switch_bootmode=get_rebootmode;if test ${reboot_mode} = factory_reset; then run recovery_from_flash;else if test ${reboot_mode} = update; then run update;else if test ${reboot_mode} = cold_boot; then run try_auto_burn; else if test ${reboot_mode} = fastboot; then fastboot;fi;fi;fi;fi;
try_auto_burn=update 700 750;
update=run usb_burning; run sdc_burning; if mmcinfo; then run recovery_from_sdcard;fi;if usb start 0; then run recovery_from_udisk;fi;run recovery_from_flash;
upgrade_check=echo upgrade_step=${upgrade_step}; if itest ${upgrade_step} == 3; then run init_display; run storeargs; run update;else fi;
upgrade_key=if gpio input GPIOAO_2; then echo detect upgrade key; sleep 3;if gpio input GPIOAO_2; then run update; fi;fi;
upgrade_step=2
usb_burning=update 1000
wipe_cache=successful
wipe_data=successful 
tiancheng91 commented 5 years ago

http://www.denx.de/wiki/publish/DULG/to-delete/UBootEnvVariables.html

tiancheng91 commented 5 years ago
echo '
setenv env_addr 0x10400000
setenv kernel_addr 0x11000000
setenv initrd_addr 0x13000000
setenv dtb_mem_addr 0x1000000
setenv boot_start booti ${kernel_addr} ${initrd_addr} ${dtb_mem_addr}
setenv addmac 'if printenv mac; then setenv bootargs ${bootargs} mac=${mac}; elif printenv ethaddr; then setenv bootargs ${bootargs} mac=${ethaddr}; fi'
setenv try_boot_start 'if fatload ${devtype} ${devnum} ${kernel_addr} zImage; then if fatload ${devtype} ${devnum} ${initrd_addr} uInitrd; then fatload ${devtype} ${devnum} ${env_addr} uEnv.ini && env import -t ${env_addr} ${filesize} && run addmac; fatload ${devtype} ${devnum} ${dtb_mem_addr} ${dtb_name} && run boot_start; fi; fi;'
setenv devnum 0
setenv devtype usb
for devnum in 0 1 2 3 ; do run try_boot_start ; done
' > /boot/s905_autoscript.txt

echo '
setenv env_addr 0x10400000
setenv kernel_addr 0x11000000
setenv initrd_addr 0x13000000
setenv dtb_mem_addr 0x1000000
setenv boot_start booti ${kernel_addr} ${initrd_addr} ${dtb_mem_addr}
setenv addmac 'if printenv mac; then setenv bootargs ${bootargs} mac=${mac}; elif printenv ethaddr; then setenv bootargs ${bootargs} mac=${ethaddr}; fi'
if fatload mmc 1 ${kernel_addr} zImage; then if fatload mmc 1 ${initrd_addr} uInitrd; then if fatload mmc 1 ${env_addr} uEnv.ini; then env import -t ${env_addr} ${filesize}; run addmac; fi; if fatload mmc 1 ${dtb_mem_addr} ${dtb_name}; then run boot_start;fi;fi;fi;
' > /boot/emmc_autoscript.txt
tiancheng91 commented 5 years ago

install to disk

# DIR_INSTALL=/data/disk1
echo "Copy BIN"
tar -cf - bin | (cd $DIR_INSTALL; tar -xpf -)
#echo "Copy BOOT"
#mkdir -p $DIR_INSTALL/boot
#tar -cf - boot | (cd $DIR_INSTALL; tar -xpf -)
echo "Create DEV"
mkdir -p $DIR_INSTALL/dev
#tar -cf - dev | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy ETC"
tar -cf - etc | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy HOME"
tar -cf - home | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy LIB"
tar -cf - lib | (cd $DIR_INSTALL; tar -xpf -)
echo "Create MEDIA"
mkdir -p $DIR_INSTALL/media
#tar -cf - media | (cd $DIR_INSTALL; tar -xpf -)
echo "Create MNT"
mkdir -p $DIR_INSTALL/mnt
#tar -cf - mnt | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy OPT"
tar -cf - opt | (cd $DIR_INSTALL; tar -xpf -)
echo "Create PROC"
mkdir -p $DIR_INSTALL/proc
echo "Copy ROOT"
tar -cf - root | (cd $DIR_INSTALL; tar -xpf -)
echo "Create RUN"
mkdir -p $DIR_INSTALL/run
echo "Copy SBIN"
tar -cf - sbin | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy SELINUX"
tar -cf - selinux | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy SRV"
tar -cf - srv | (cd $DIR_INSTALL; tar -xpf -)
echo "Create SYS"
mkdir -p $DIR_INSTALL/sys
echo "Create TMP"
mkdir -p $DIR_INSTALL/tmp
echo "Copy USR"
tar -cf - usr | (cd $DIR_INSTALL; tar -xpf -)
echo "Copy VAR"
tar -cf - var | (cd $DIR_INSTALL; tar -xpf -)
sync
tiancheng91 commented 5 years ago

usb 电源烧毁处理方法

使用usb母线将n1和电脑相连(电脑供电), n1另一usb口插入做好armbian的u盘, 插入电源后, 会先从u盘启动. 进入系统后可以修改emmc上文件

tiancheng91 commented 5 years ago

meson-gpio 中断负载高. 解决方法. https://p3terx.com/archives/n1-armbian-dtb.html

tiancheng91 commented 5 years ago
dtc -I dtb -O dts -o n1.dts /boot/dtb/amlogic/meson-gxl-s905d-phicomm-n1.dtb
vim n1.dts
dtc -I dts -O dtb -o n1.dtb n1.dts

interrupt-controller@9880. #phandle 注视
tiancheng91 commented 4 years ago

问题: 新版本armbian网卡无法获取IP 解决: 新版本网卡默认被设置为了千兆模式, 网线是自制的4芯线,ethtool修改网卡到百兆模式恢复。

tiancheng91 commented 4 years ago
/dev/sda        /mnt/disk1      btrfs           defaults,noatime,ssd_spread             0 0
/dev/sda        /data           btrfs           defaults,noatime,ssd_spread,subvol=data 0 0
/dev/sda        /opt            btrfs           defaults,noatime,ssd_spread,subvol=apps 0 0
tiancheng91 commented 4 years ago
[Unit]
Description=ethtool
DefaultDependencies=no
Before=network-pre.target
Wants=network-pre.target

[Service]
RemainAfterExit=yes
ExecStart=/usr/sbin/ethtool -s eth0 speed 100 duplex full

[Install]
WantedBy=sysinit.target
tiancheng91 commented 4 years ago

https://docs.khadas.com/vim1/BuildBootLogoForUboot.html

tiancheng91 commented 4 years ago
bsdtar -xpf ArchLinuxARM-aarch64-latest.tar.gz -C mountpoint
 Install uboot tools, go to boot folder under mounted partition
cd mountpoint/boot
 Create Uboot Kernel Image, do all following operations as root user
mkimage -A arm64 -O linux -C none -T kernel -a 0x01080000 -e 0x01080000 -d Image uImage
Create Uboot initrd image
mkimage -A arm64 -O linux -T ramdisk -n "initramfs" -C gzip -a 0x13000000 -e 0x13000000 -d initramfs-linux.img uInitramfs
tiancheng91 commented 4 years ago

alpinelinux 镜像构建

#!/bin/sh
#genetate alpine edge n1 armhf/aarch64 image: chmod +x gen-alpine_n1.sh && sudo ./gen-alpine_n1.sh
#depends: apk-tools-static, vim(xxd)

set -x

die() {
    printf '\033[1;31mERROR:\033[0m %s\n' "$@" >&2  # bold red
    exit 1
}

if [ "$(id -u)" -ne 0 ]; then
    die 'This script must be run as root!'
fi

which xxd >/dev/null || exit 

BUILD_DATE="$(date +%Y-%m-%d)"

usage() {
    cat <<EOF
    Usage: gen-alpine_n1.sh [options]
    Valid options are:
        -a ALPINE_ARCH          Options: armhf, aarch64.
        -m ALPINE_MIRROR        URI of the mirror to fetch packages from
                                (default is https://mirrors.tuna.tsinghua.edu.cn/alpine).
        -o OUTPUT_IMG           Output img file
                                (default is BUILD_DATE-alpine-n1-ARCH.img).
        -h                      Show this help message and exit.
EOF
}

while getopts 'a:m:o:h' OPTION; do
    case "$OPTION" in
        a) ALPINE_ARCH="$OPTARG";;
        m) ALPINE_MIRROR="$OPTARG";;
        o) OUTPUT_IMG="$OPTARG";;
        h) usage; exit 0;;
    esac
done 

: ${ALPINE_ARCH:="$(uname -m)"}
: ${ALPINE_MIRROR:="https://mirrors.aliyun.com/alpine"}
: ${OUTPUT_IMG:="${BUILD_DATE}-alpine-n1-${ALPINE_ARCH}.img"}

#=======================  F u n c t i o n s  =======================#

gen_image() {
    fallocate -l $(( 350 * 1024 *1024 )) "$OUTPUT_IMG"
cat > fdisk.cmd <<-EOF
    o
    n
    p
    1

    +128MB
    t
    c
    n
    p
    2

    w
EOF
fdisk "$OUTPUT_IMG" < fdisk.cmd
rm -f fdisk.cmd
}

do_format() {
    mkfs.fat -F32 "$BOOT_DEV"
    mkfs.ext4 "$ROOT_DEV"
    mkdir -p mnt
    mount "$ROOT_DEV" mnt
    mkdir -p mnt/boot
    mount "$BOOT_DEV" mnt/boot
}

setup_mirrors() {
    #mv mnt/etc/apk/repositories mnt/etc/apk/repositories.old

    for ALPINE_REPOS in main community testing ; do
        echo ${ALPINE_MIRROR}/edge/${ALPINE_REPOS} >> mnt/etc/apk/repositories
    done
}

do_apkstrap() {
    apk.static -X ${ALPINE_MIRROR}/edge/main -U --allow-untrusted --root mnt --initdb add alpine-base
}

gen_fstabs() {
    echo "UUID=${BOOT_UUID}  /boot           vfat    defaults          0       2
UUID=${ROOT_UUID}  /               ext4    defaults,noatime  0       1"
}

add_normal_user() {
    addgroup work
    adduser -G work -s /bin/bash -D work
    echo "work:work" | /usr/sbin/chpasswd
    echo "work ALL=NOPASSWD: ALL" >> /etc/sudoers
}

add_user_groups() {
    for USER_GROUP in spi i2c gpio; do
        groupadd -f -r $USER_GROUP
    done
    for USER_GROUP in adm dialout cdrom audio users wheel video games plugdev input gpio spi i2c netdev; do
        adduser work $USER_GROUP
    done
}

setup_ntp_server() {
    sed -i 's/pool.ntp.org/cn.pool.ntp.org/' /etc/init.d/ntpd
}

gen_resize2fs_once_service() {
    cat > /etc/init.d/resize2fs-once <<'EOF'
#!/sbin/openrc-run
command="/usr/bin/resize2fs-once"
command_background=false
depend() {
        after modules
        need localmount
}
EOF

    cat > /usr/bin/resize2fs-once <<'EOF'
#!/bin/sh 
set -xe
ROOT_DEV=$(findmnt / -o source -n)
ROOT_START=$(fdisk -l $(echo "$ROOT_DEV" | sed -E 's/p?2$//') | grep "$ROOT_DEV" | awk '{ print $2 }')
cat > /tmp/fdisk.cmd <<-EOF
    d
    2

    n
    p
    2
    ${ROOT_START}

    w
    EOF
fdisk "$(echo "$ROOT_DEV" | sed -E 's/p?2$//')" < /tmp/fdisk.cmd
rm -f /tmp/fdisk.cmd
partprobe
resize2fs "$ROOT_DEV"
rc-update del resize2fs-once default
#reboot
EOF

chmod +x /etc/init.d/resize2fs-once /usr/bin/resize2fs-once
rc-update add resize2fs-once default
}

make_bash_fancy() {
    su n1 <<-'EOF'
    sh -c 'cat > /home/work/.profile << "EOF"
    if [ -f "$HOME/.bashrc" ] ; then
        source $HOME/.bashrc
    fi
    EOF'

    wget https://github.com/yangxuan8282/phicomm-n1/raw/master/dotfiles/alpine/config/.bashrc -P /home/work
    EOF
}

gen_motd() {

    cat > /etc/motd << "EOF"
Welcome to Alpine!

EOF

    cat > /etc/profile.d/motd.sh << "EOF"
#!/bin/sh

my_ip=$(ip route get 1 | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | tail -1)

root_usage=$(df -h / | awk '/\// {print $(NF-1)}')

echo "
  ⚡  MY IP:   ${my_ip}

  ⚡  DISK USAGE:   ${root_usage}

"
EOF

}

gen_s905_autoscript() {
    cat > /boot/s905_autoscript.cmd <<'EOF'
setenv env_addr    "0x10400000"
setenv kernel_addr "0x11000000"
setenv initrd_addr "0x13000000"
setenv boot_start booti ${kernel_addr} ${initrd_addr} ${dtb_mem_addr}
if fatload usb 0 ${kernel_addr} vmlinuz-amlogic; then if fatload usb 0 ${initrd_addr} uInitrd; then if fatload usb 0 ${env_addr} uEnv.ini; then env import -t ${env_addr} ${filesize};run cmdline_keys;fi; if fatload usb 0 ${dtb_mem_addr} ${dtb_name}; then run boot_start; else store dtb read ${dtb_mem_addr}; run boot_start;fi;fi;fi;
if fatload usb 1 ${kernel_addr} vmlinuz-amlogic; then if fatload usb 1 ${initrd_addr} uInitrd; then if fatload usb 1 ${env_addr} uEnv.ini; then env import -t ${env_addr} ${filesize};run cmdline_keys;fi; if fatload usb 1 ${dtb_mem_addr} ${dtb_name}; then run boot_start; else store dtb read ${dtb_mem_addr}; run boot_start;fi;fi;fi;
if fatload mmc 1:a ${kernel_addr} vmlinuz-amlogic; then if fatload mmc 1:a ${initrd_addr} uInitrd; then if fatload mmc 1:a ${env_addr} uEnv.ini; then env import -t ${env_addr} ${filesize};run cmdline_keys;fi; if fatload mmc 1:a ${dtb_mem_addr} ${dtb_name}; then run boot_start; else store dtb read ${dtb_mem_addr}; run boot_start;fi;fi;fi;
EOF

mkimage -C none -A arm -T script -d /boot/s905_autoscript.cmd /boot/s905_autoscript
}

gen_uEnv_ini() {
    cat > /boot/uEnv.ini <<'EOF'
dtb_name=/dtbs/meson-gxl-s905d-phicomm-n1.dtb
bootargs=root=LABEL=ROOTFS rootflags=data=writeback rw console=ttyAML0,115200n8 console=tty0 no_console_suspend consoleblank=0 fsck.fix=yes fsck.repair=yes net.ifnames=0
EOF

sed -i "s|root=LABEL=ROOTFS|root=UUID=${ROOT_UUID}|" /boot/uEnv.ini

}

install_kernel() {
    echo "install kernel"
    # apk add --no-cache uboot-tools linux-amlogic
}

install_uboot() {
    gen_s905_autoscript
    gen_uEnv_ini

    mkimage -A arm64 -O linux -T ramdisk -C gzip -n uInitrd -d /boot/initramfs-amlogic /boot/uInitrd

}

disable_autoneg() {
    # apk add --no-cache ethtool
    echo "/usr/sbin/ethtool -s eth0 speed 100 duplex full autoneg off" > /etc/local.d/disable-autoneg.start
    chmod +x /etc/local.d/disable-autoneg.start
}

setup_openrc_service() {
    setup-udev -n

    for service in devfs dmesg; do
        rc-update add $service sysinit
    done

    for service in modules sysctl hostname bootmisc swclock syslog; do
        rc-update add $service boot
    done

    for service in dbus haveged sshd ntpd local networkmanager; do
        rc-update add $service default
    done

    for service in mount-ro killprocs savecache; do
        rc-update add $service shutdown
    done

    mkdir -p /run/openrc
    touch /run/openrc/shutdowntime
}

gen_nm_config() {
    cat > /etc/NetworkManager/conf.d/networkmanager.conf <<EOF
[main]
plugins+=ifupdown
dhcp=internal

[ifupdown]
managed=true

[logging]
level=INFO

[device-mac-randomization]
wifi.scan-rand-mac-address=no
EOF
}

gen_syslog_config() {
    sed s/=\"/=\""-C4048 "/  -i /etc/conf.d/syslog
}

gen_env() {
    echo "LOOP_DEV=${LOOP_DEV}
    ALPINE_ARCH=${ALPINE_ARCH}
    ROOT_UUID=${ROOT_UUID}"
}

setup_chroot() {
    chroot mnt /bin/sh <<-EOF
        set -x
        source /root/env_file
        source /etc/profile
        source /root/functions
        rm -f /root/functions /root/env_file
        echo "root:root" | chpasswd
        apk --update add sudo
        add_normal_user
        echo "aml" > /etc/hostname
        echo "127.0.0.1    localhost" > /etc/hosts
        echo "127.0.1.1    aml aml.localdomain" >> /etc/hosts
        apk add --no-cache dbus eudev haveged openssh util-linux coreutils shadow e2fsprogs e2fsprogs-extra tzdata
        apk add --no-cache iw wireless-tools crda networkmanager
        apk add --no-cache nano htop bash bash-completion curl tar ca-certificates wget && update-ca-certificates
        apk add --no-cache uboot-tools linux-amlogic ethtool
        setup_openrc_service
        add_user_groups
        gen_nm_config
        echo "options cfg80211 ieee80211_regdom=CN" > /etc/modprobe.d/cfg80211.conf
        echo "blacklist btsdio" >> /etc/modprobe.d/blacklist.conf
        disable_autoneg
        gen_syslog_config
        setup_ntp_server
        ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
        install_kernel
        gen_resize2fs_once_service
        gen_motd
        make_bash_fancy
        sync
        install_uboot
        rm -rf /tmp/* /boot/*.cmd
EOF
}

mounts() {
    mount -t proc none mnt/proc
    mount -o bind /sys mnt/sys
    mount -o bind /dev mnt/dev
}

umounts() {
    umount mnt/dev
    umount mnt/sys
    umount mnt/proc
    umount mnt/boot
    umount mnt
    losetup -d "$LOOP_DEV"
}

#=======================  F u n c t i o n s  =======================#

pass_function() {
    sed -nE '/^#===.*F u n c t i o n s.*===#/,/^#===.*F u n c t i o n s.*===#/p' "$0"
}

gen_image

LOOP_DEV=$(losetup --partscan --show --find "${OUTPUT_IMG}")
BOOT_DEV="$LOOP_DEV"p1
ROOT_DEV="$LOOP_DEV"p2

do_format

do_apkstrap

IMGID="$(dd if="${OUTPUT_IMG}" skip=440 bs=1 count=4 2>/dev/null | xxd -e | cut -f 2 -d' ')"

BOOT_UUID=$(blkid ${BOOT_DEV} | cut -f 2 -d '"')
ROOT_UUID=$(blkid ${ROOT_DEV} | cut -f 2 -d '"')

gen_fstabs > mnt/etc/fstab

gen_env > mnt/root/env_file

pass_function > mnt/root/functions

mounts

setup_mirrors

cp /etc/resolv.conf mnt/etc/resolv.conf

setup_chroot

umounts

cat >&2 <<-EOF
    ---
    Installation is complete
    Flash to usb disk with: dd if=${OUTPUT_IMG} of=/dev/TARGET_DEV bs=4M

EOF