#!/bin/sh
# -*-mode: sh; tab-width: 8; coding: utf-8-unix -*-

# prog=rc.local
PREFIX=/usr/local
ROLE=local

export PATH=$PATH:/usr/local/sbin:/usr/local/bin

if [ -x /sbin/rc-service ] ; then
    local_rc_service () { rc-service "$@" ; }
    local_rc_update () { rc-update "$@" ; }
  elif [ -x /bin/systemctl ] ; then
    local_rc_service () { 
      systemctl list-units --no-pager | grep -q $1 && \
          echo INFO: /usr/sbin/service "$@" || \
          echo WARN: /usr/sbin/service "$@" 
      /usr/sbin/service "$@" 2>/dev/null
      return $?
    }
    local_rc_update () { 
      if [ "$#" -eq 0 ] ; then
        systemctl list-units --no-pager
	return $?
      fi
      dir=$1 ; shift ;
      svc=$1 ; shift ;
      if [ $dir = add ] ; then
         dire=enable 
        elif [ $dir = del ] ; then
         dire=disable
        else
         dire=$dir
      	fi
      echo INFO: $prog systemctl --no-pager $dire $svc "$@" 
      systemctl --no-pager $dire $svc "$@"
      return $?
    }
  elif [ -x /usr/sbin/service ] ; then
    local_rc_service () { 
      /usr/sbin/service --status-all 2>&1 | grep -q $1 && \
          echo INFO: /usr/sbin/service "$@" || \
          echo WARN: /usr/sbin/service "$@" 
      /usr/sbin/service "$@" 2>/dev/null
      return $?
    }
    local_rc_update () { 
      if [ "$#" -eq 0 ] ; then
        /usr/sbin/service --status-all 2>&1 | sed -e 's/.* //'
	return $?
      fi
      dir=$1 ; shift ;
      svc=$1 ; shift ;
      #      disable|enable |remove
      if [ $dir = add ] ; then
         dire=enable 
        elif [ $dir = del ] ; then
         dire=disable
        else
         dire=$dir
      	fi
      update-rc.d $svc  $dire || echo WARN: update-rc.d $svc  $dir $dire
    }
fi
proxy_rc_service () { local_rc_service $* ; }
proxy_rc_update () { local_rc_update $* ; }

grep -q root=/dev/vda /proc/cmdline
PROXY_IS_VDA=$?

## local_disable_lid
local_disable_lid () {
      # https://bbs.archlinux.org/viewtopic.php?id=72779
      echo LID0 > /proc/acpi/wakeup
      # https://forums.linuxmint.com/viewtopic.php?f=208&t=106532
      if [ -f /etc/UPower/UPower.conf ] ; then
          [ -f /etc/UPower/UPower.conf.bak ] || \
            cp -p /etc/UPower/UPower.conf /etc/UPower/UPower.conf.bak
          grep -q '^IgnoreLid=true'  /etc/UPower/UPower.conf || \
            sed -e 's@#*IgnoreLid=.*@IgnoreLid=true@' -i /etc/UPower/UPower.conf
         fi
      if [ -f /etc/systemd/logind.conf ] ; then
          [ -f /etc/systemd/logind.conf.bak ] || \
            cp -p /etc/systemd/logind.conf /etc/systemd/logind.conf.bak
          grep -q '^HandleLidSwitch=ignore' /etc/systemd/logind.conf || \
            sed -e 's@^#*HandleLidSwitch=.*@HandleLidSwitch=ignore@' -i /etc/systemd/logind.conf
       fi
    return 0
}

## local_guest_start_services
local_guest_start_services () {
    for file in /usr/local/etc/modules-load.d/vda*conf ; do
	[ -s $file ] || continue
        base=`basename $file`
      	[ -e /etc/modules-load.d/$base ] && continue
	echo "# from $file" > /etc/modules-load.d/$base
	grep -v '^#' $file >> /etc/modules-load.d/$base
    done
    
    grep -hv '#' /etc/modules-load.d/vda*.conf | xargs modprobe --all

    local_start_services $*

    exit 0
}

local_guest_add_xorg_conf () {
    [ -f /etc/X11/xorg.conf.d/80_qxl.conf ] || \
	grep -q Drive.*qxl /etc/X11/xorg.conf.d/*.conf || \
	cat > /etc/X11/xorg.conf.d/80_qxl.conf << EOF
# BEGIN ANSIBLE MANAGED BLOCK proxy whonix_guest.yml
Section "Device"
    Identifier "qxl"
    Driver "qxl"
    Option "DPI" "96 x 96"
    Option "ENABLE_IMAGE_CACHE" "True"
    Option "ENABLE_FALLBACK_CACHE" "False"
    Option "ENABLE_SURFACES" "False"
EndSection 
# END ANSIBLE MANAGED BLOCK proxy whonix_guest.yml
EOF
    return 0
}

## local_guest_config
local_guest_config () {
    
    [ -d /etc/qemu ] || mkdir /etc/qemu
    [ -f /etc/qemu/qemu-ga.conf ] || cat > /etc/qemu/qemu-ga.conf <<EOF
[general]
daemon=false
method=virtio-serial
path=/dev/virtio-ports/org.qemu.guest_agent.0
pidfile=/run/qemu-ga.pid
statedir=/run
verbose=true
retry-path=false
blacklist=
logfile=/var/log/libvirtd/qemu-ga.log
EOF
    [ -d /var/log/libvirtd/ ] || mkdir /var/log/libvirtd/

    [ -f  /etc/default/qemu-guest-agent.diff ] || cat >  /etc/default/qemu-guest-agent.diff <<EOF
*** /etc/default/qemu-guest-agent.dst   2021-01-05 03:28:20.579117119 +0000
--- /etc/default/qemu-guest-agent   2021-08-27 20:26:36.234739996 +0000
***************
*** 1 ****
! DAEMON_ARGS="--logfile /var/log/libvirtd/qemu-ga.log"
--- 1 ----
! DAEMON_ARGS="--logfile /var/log/libvirtd/qemu-ga.log --verbose  --pidfile /run/qemu-ga.pid"
EOF

    [ -f /etc/default/qemu-guest-agent.dst ] || \
	patch -z .st -b /etc/default/qemu-guest-agent \
	      < /etc/default/qemu-guest-agent.diff

    return 0
}

## local_guest_status
local_guest_status () {
    if [ ! -f /var/log/libvirtd/qemu-ga.log ] ; then
	echo WARN: missing /var/log/libvirtd/qemu-ga.log
      elif grep -q critical: /var/log/libvirtd/qemu-ga.log ; then
	echo ERROR: critical /var/log/libvirtd/qemu-ga.log
      fi
    return 0
}

## local_guest_neutersystemd
local_guest_neutersystemd () {
    [ ! -f /lib/lsb/init-functions.d/40-systemd ] || \
	mv /lib/lsb/init-functions.d/40-systemd  /lib/lsb/.40-systemd
    return 0
}

# vda
## local_host_symlink_usr_src
local_host_symlink_etc_fstab () {
    # guest
    [ -h /etc/fstab ] && [ -f /etc/fstab.vda ] && \
	rm -f /etc/fstab && ln -s /etc/fstab.vda /etc/fstab
    
    return 0
}

## local_host_make_dmcrypt_swap
local_host_make_dmcrypt_swap () {
    local two five
    
    if ! grep -q '/dev/mapper\|/dev/sd\|/dev/dm' /proc/swaps ; then
	blkid > ~/blkid.txt
	five=`grep _05E ~/blkid.txt | head -1`
	if [ $? -eq 0 -a -n "$five" ] ; then
	    two=`echo $five | sed -e 's/_.*//' -e 's/.*="//'`_02SWAP
	    if ! grep $two ~/blkid.txt ; then
		dev=`echo $five | sed -e 's/:.*//' -e 's/5/2/'`
		[ $? -eq 0 -a -n "$dev" ] && mkswap -L $two $dev
	    fi
	    grep $two /etc/conf.d/dmcrypt && local_rc_service dmcrypt restart || echo WARN: $two not in /etc/conf.d/dmcrypt
	    grep -q '/dev/mapper\|/dev/sd\|/dev/dm' /proc/swaps || local_rc_service swap restart
	    # if its not in fstab
	    grep -q '/dev/mapper\|/dev/sd\|/dev/dm' /proc/swaps || swapon /dev/mapper/cryptswap*
	fi
    fi

    return 0
}

# all
## local_start_services
local_start_services () {
    for elt in $*; do
        local_rc_service $elt status >/dev/null || local_rc_service $elt start
	local_rc_update | grep -q $elt || local_rc_update add $elt
      done

    return 0
}


# all
## nlocal_manual_stop_services
local_manual_stop_services () {
    # set these to stop now and restart them manually as we configure them
    #  rsync on debian
    for elt in $* ; do
        local_rc_service $elt status >/dev/null && local_rc_service $elt stop
	local_rc_update | grep -q $elt  && local_rc_update del $elt
      done

    return 0
}


# all
## local_host_symlink_usr_src
local_host_symlink_usr_src () {
    local dir
    
    dir=`cat /proc/cmdline|sed -e 's/.*BOOT_IMAGE=kernel-pentoo-x86_64/linux/' -e 's/_.*//'`
    WD=$PWD
    cd /usr/src
    if [ -d $dir ] ; then
	rm -f linux
	ln -s $dir linux || echo WARN: $PWD/$dir not found
    fi
    cd $WD

    return 0
}

# all
## local_lightdm_on_text
local_lightdm_on_text () {
    return 0
    [ ! -f /usr/sbin/lightdm ] && return 0
    if [ ! -f /usr/sbin/lightdm.bin ] ; then
	[ -f /usr/sbin/lightdm.bad ] && mv /usr/sbin/lightdm.bad /usr/sbin/lightdm.bin
	[ ! -f /usr/sbin/lightdm.bin ] && mv /usr/sbin/lightdm /usr/sbin/lightdm.bin
	if [ -f /usr/sbin/lightdm.bin ] && [ -f /usr/sbin/lightdm ] ; then
	    cat > /usr/sbin/lightdm << EOF
#!/bin/sh
grep -q ' text ' /proc/cmdline && exit 0
exec /usr/sbin/lightdm.bin "$@"
EOF
            chmod 755 /usr/sbin/lightdm
	fi
    fi

    return 0
}

## local_host_restart_psmouse
local_host_restart_psmouse () {
    local_rc_service gpm status && local_rc_service gpm stop
    rmmod psmouse; sleep 1; modprobe psmouse proto=exps
    local_rc_service gpm start
    return 0
}

## local_host_restart_intel_sound
local_host_restart_intel_sound () {
    which aplay >/dev/null 2>/dev/null || return 0

    # both
    if ! aplay -L | grep -q default:CARD=PCH ; then
	rmmod snd_hda_intel ;
	sleep 5
	modprobe snd_hda_intel enable=1 ;
	sleep 1
	aplay -L  >/dev/null || exit 2
    fi
    
    return 0
}

## local_all
local_all () {
    local_disable_lid

    touch /var/log/boot

    chmod 775 /usr/local/*bin/*sh /var/local/*bin/*sh
    
    # grep -q text /proc/cmdline && local_lightdm_on_text

    ( cd /var/tmp && rm -rf ansible-local-* Temp-* ssh-* pulse-* .xfsm-ICE-* )
    
    return 0
}

## local_manual_mask_services
local_manual_mask_services () {
    if [ -d /usr/local/etc/systemd/  ] ; then
       local_systemd_stop_and_mask $* ||    return 1$?
    elif [ -x  /usr/sbin/update-rc.d ] ; then
       /usr/sbin/invoke-rc.d $1 stop
       /usr/sbin/update-rc.d $1 remove || return 2$?
    elif [ /sbin/rc-update ] ; then
       /sbin/rc-service $1 stop
       /sbin/rc-update $1 del ||    return 3$?
    fi

    return 0
}

##  local_systemd_stop_and_mask
local_systemd_stop_and_mask () {
    [ $# -eq 0 ] && [ -d /usr/local/etc/systemd/ ] && \
	set - `grep -v '@\.service' /usr/local/etc/systemd/*.mask`
    for file in $* ; do
 	[ -e /lib/systemd/system/$file ] || continue
        elt=`basename $file`
        systemctl is-enabled $elt 2>/dev/null >/dev/null || continue
	echo INFO: local_systemd_stop_and_mask systemctl disable $elt
	systemctl disable --now $elt && systemctl mask $elt
        # [ -h /etc/systemd/system/$file ]
        # [ `readlink /etc/systemd/system/$file ` = /dev/null ]
	done

    return 0
}

## local_neuter_gvfs
local_neuter_gvfs () {
    [ -d /usr/local/share/dbus-1/services ] || exit 0
    cd /usr/local/share/dbus-1/services
    for file in /usr/share/dbus-1/services/*vfs* ; do
         sed -e 's@^Exec=.*@Exec=/bin/false@' > `basename $file`
    done
}

local_link_linux () {

sed < /proc/cmdline -e 's@.*BOOT_IMAGE=vmlinuz-@linux-@' -e 's/[_ ].*//'| \
  while read line ; do
    [ -z "$line" ]  && continue
    [ -d "/usr/src/$line" ]  || { echo WARN: /usr/src/$line ; continue ; }
    rm -f /usr/src/linux
    echo INFO:  /usr/src/$line /usr/src/linux
    ln -s /usr/src/$line /usr/src/linux
  done

  return 0
}

local_null_machineid () {
    [ -s /etc/machine-id ] && cp /dev/null /etc/machine-id
    return 0
}

base=local
if [ -x /usr/bin/basename ] && [ `/usr/bin/basename -- $0` = $base'.bash' ] ; then
    [ "$#" -eq 1 ] && [ "$1" = '-h' -o "$1" = '--help' ] && \
	echo USAGE: $0 && grep '^[a-z].*()\|^## ' $0 | sed -e 's/().*//'| sort \
	&& exit 0
    eval "$@"
    exit $?
  fi
