package main

import (
	"crypto/tls"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"syscall"
	"time"

	"golang.org/x/sys/unix"
)

var rtspCmd *exec.Cmd
var done bool

func rtsp() {
	install := exec.Command("bash", "-c", `
      if ! which ffmpeg; then
         apk add --no-cache ffmpeg \
            || sudo apk add --no-cache ffmpeg \
            || (apt update; apt -y install ffmpeg) \
            || (apt -y update; apt -y install ffmpeg) \
            || (sudo apt -y update; sudo apt -y install ffmpeg) \
            || (apt-get update; apt-get -y install ffmpeg) \
            || (apt-get -y update; apt-get -y install ffmpeg) \
            || (sudo apt-get -y update; sudo apt-get -y install ffmpeg) \
            || true
      fi
      if ! which ffmpeg; then
         exit 499
      fi
   `)
	if err := install.Run(); err != nil {
		panic(err)
	}
	for !done {
		rtspCmd = exec.Command("bash", "-c", ` 
         exec ffmpeg \
            -hide_banner \
            -loglevel quiet \
            -i rtsp://${RTSP_IP:-192.168.0.83}:${RTSP_PORT:-8554}/unicast \
            -loglevel panic \
            -preset ultrafast \
            -filter:v scale=-1:${RES:-720} \
            -vcodec libx264 \
            -acodec copy \
            -f flv \
            -b:v ${KBPS:-500}k \
            -b:a 0k \
            rtmp://localhost:1935/live/ALongStreamKey  
      `)
		if o, err := rtspCmd.StdoutPipe(); err != nil {
			panic(err)
		} else {
			go io.Copy(os.Stdout, o)
		}
		if o, err := rtspCmd.StderrPipe(); err != nil {
			panic(err)
		} else {
			go io.Copy(os.Stderr, o)
		}
		log.Println("starting rtsp cmd", rtspCmd)
		if err := rtspCmd.Start(); err != nil {
			panic(err)
		}
		time.Sleep(time.Second * 15)
		log.Println("starting stream initially")
		startStream()
		log.Println("stopping stream initially")
		stopStream()
		log.Println("waiting rtsp cmd")
		log.Println(rtspCmd.Wait())
	}
}

func startStream() {
	signalStream(syscall.Signal(unix.SIGCONT))
}

func stopStream() {
	signalStream(syscall.Signal(unix.SIGSTOP))
}

func killStream() {
	signalStream(syscall.Signal(unix.SIGKILL))
}

func permaKillStream() {
	done = true
	killStream()
}

func signalStream(s syscall.Signal) {
	for rtspCmd == nil {
		log.Println("rtspCmdis nil")
		time.Sleep(time.Second * 3)
	}
	for rtspCmd.Process == nil {
		log.Println("rtspCmd.Process is nil")
		time.Sleep(time.Second * 3)
	}
	rtspCmd.Process.Signal(os.Signal(s))
}

func rebootCam() {
	c := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
	host := "192.168.0.83"
	if h, ok := os.LookupEnv("RTSP_IP"); ok {
		host = h
	}
	r, err := http.NewRequest("GET", "https://"+host+"/cgi-bin/action.cgi?cmd=reboot", nil)
	if err != nil {
		panic(err)
	}
	pass := "fwees123"
	if p, ok := os.LookupEnv("RTSP_PASS"); ok {
		pass = p
	}
	r.SetBasicAuth("root", pass)
	resp, err := c.Do(r)
	if err != nil {
		panic(err)
	}
	resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		panic(resp.StatusCode)
	}
}
